0a53a3e291ceff2378a0c447bed322d04becdb15
[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/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/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::FSINCOS, MVT::f64, Expand);
611     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
612     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
613     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
614
615     // Expand FP immediates into loads from the stack, except for the special
616     // cases we handle.
617     addLegalFPImmediate(APFloat(+0.0)); // xorpd
618     addLegalFPImmediate(APFloat(+0.0f)); // xorps
619   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
620     // Use SSE for f32, x87 for f64.
621     // Set up the FP register classes.
622     addRegisterClass(MVT::f32, &X86::FR32RegClass);
623     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
624
625     // Use ANDPS to simulate FABS.
626     setOperationAction(ISD::FABS , MVT::f32, Custom);
627
628     // Use XORP to simulate FNEG.
629     setOperationAction(ISD::FNEG , MVT::f32, Custom);
630
631     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
632
633     // Use ANDPS and ORPS to simulate FCOPYSIGN.
634     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
635     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
636
637     // We don't support sin/cos/fmod
638     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
639     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
640     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
641
642     // Special cases we handle for FP constants.
643     addLegalFPImmediate(APFloat(+0.0f)); // xorps
644     addLegalFPImmediate(APFloat(+0.0)); // FLD0
645     addLegalFPImmediate(APFloat(+1.0)); // FLD1
646     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
647     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
648
649     if (!TM.Options.UnsafeFPMath) {
650       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
651       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
652       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
653     }
654   } else if (!TM.Options.UseSoftFloat) {
655     // f32 and f64 in x87.
656     // Set up the FP register classes.
657     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
658     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
659
660     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
661     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
662     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
663     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
664
665     if (!TM.Options.UnsafeFPMath) {
666       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
667       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
671       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672     }
673     addLegalFPImmediate(APFloat(+0.0)); // FLD0
674     addLegalFPImmediate(APFloat(+1.0)); // FLD1
675     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
676     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
677     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
678     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
679     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
680     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
681   }
682
683   // We don't support FMA.
684   setOperationAction(ISD::FMA, MVT::f64, Expand);
685   setOperationAction(ISD::FMA, MVT::f32, Expand);
686
687   // Long double always uses X87.
688   if (!TM.Options.UseSoftFloat) {
689     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
690     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
691     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
692     {
693       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
694       addLegalFPImmediate(TmpFlt);  // FLD0
695       TmpFlt.changeSign();
696       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
697
698       bool ignored;
699       APFloat TmpFlt2(+1.0);
700       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
701                       &ignored);
702       addLegalFPImmediate(TmpFlt2);  // FLD1
703       TmpFlt2.changeSign();
704       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
705     }
706
707     if (!TM.Options.UnsafeFPMath) {
708       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
709       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
710       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
711     }
712
713     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
714     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
715     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
716     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
717     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
718     setOperationAction(ISD::FMA, MVT::f80, Expand);
719   }
720
721   // Always use a library call for pow.
722   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
723   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
724   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
725
726   setOperationAction(ISD::FLOG, MVT::f80, Expand);
727   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
728   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
729   setOperationAction(ISD::FEXP, MVT::f80, Expand);
730   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
731
732   // First set operation action for all vector types to either promote
733   // (for widening) or expand (for scalarization). Then we will selectively
734   // turn on ones that can be effectively codegen'd.
735   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
736            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
737     MVT VT = (MVT::SimpleValueType)i;
738     setOperationAction(ISD::ADD , VT, Expand);
739     setOperationAction(ISD::SUB , VT, Expand);
740     setOperationAction(ISD::FADD, VT, Expand);
741     setOperationAction(ISD::FNEG, VT, Expand);
742     setOperationAction(ISD::FSUB, VT, Expand);
743     setOperationAction(ISD::MUL , VT, Expand);
744     setOperationAction(ISD::FMUL, VT, Expand);
745     setOperationAction(ISD::SDIV, VT, Expand);
746     setOperationAction(ISD::UDIV, VT, Expand);
747     setOperationAction(ISD::FDIV, VT, Expand);
748     setOperationAction(ISD::SREM, VT, Expand);
749     setOperationAction(ISD::UREM, VT, Expand);
750     setOperationAction(ISD::LOAD, VT, Expand);
751     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
752     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
753     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
754     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
755     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
756     setOperationAction(ISD::FABS, VT, Expand);
757     setOperationAction(ISD::FSIN, VT, Expand);
758     setOperationAction(ISD::FSINCOS, VT, Expand);
759     setOperationAction(ISD::FCOS, VT, Expand);
760     setOperationAction(ISD::FSINCOS, VT, Expand);
761     setOperationAction(ISD::FREM, VT, Expand);
762     setOperationAction(ISD::FMA,  VT, Expand);
763     setOperationAction(ISD::FPOWI, VT, Expand);
764     setOperationAction(ISD::FSQRT, VT, Expand);
765     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
766     setOperationAction(ISD::FFLOOR, VT, Expand);
767     setOperationAction(ISD::FCEIL, VT, Expand);
768     setOperationAction(ISD::FTRUNC, VT, Expand);
769     setOperationAction(ISD::FRINT, VT, Expand);
770     setOperationAction(ISD::FNEARBYINT, VT, Expand);
771     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
772     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
773     setOperationAction(ISD::SDIVREM, VT, Expand);
774     setOperationAction(ISD::UDIVREM, VT, Expand);
775     setOperationAction(ISD::FPOW, VT, Expand);
776     setOperationAction(ISD::CTPOP, VT, Expand);
777     setOperationAction(ISD::CTTZ, VT, Expand);
778     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
779     setOperationAction(ISD::CTLZ, VT, Expand);
780     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
781     setOperationAction(ISD::SHL, VT, Expand);
782     setOperationAction(ISD::SRA, VT, Expand);
783     setOperationAction(ISD::SRL, VT, Expand);
784     setOperationAction(ISD::ROTL, VT, Expand);
785     setOperationAction(ISD::ROTR, VT, Expand);
786     setOperationAction(ISD::BSWAP, VT, Expand);
787     setOperationAction(ISD::SETCC, VT, Expand);
788     setOperationAction(ISD::FLOG, VT, Expand);
789     setOperationAction(ISD::FLOG2, VT, Expand);
790     setOperationAction(ISD::FLOG10, VT, Expand);
791     setOperationAction(ISD::FEXP, VT, Expand);
792     setOperationAction(ISD::FEXP2, VT, Expand);
793     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
794     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
795     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
796     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
797     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
798     setOperationAction(ISD::TRUNCATE, VT, Expand);
799     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
800     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
801     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
802     setOperationAction(ISD::VSELECT, VT, Expand);
803     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
804              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
805       setTruncStoreAction(VT,
806                           (MVT::SimpleValueType)InnerVT, Expand);
807     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
808     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
809     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
810   }
811
812   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
813   // with -msoft-float, disable use of MMX as well.
814   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
815     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
816     // No operations on x86mmx supported, everything uses intrinsics.
817   }
818
819   // MMX-sized vectors (other than x86mmx) are expected to be expanded
820   // into smaller operations.
821   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
822   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
823   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
824   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
825   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
826   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
827   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
828   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
829   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
830   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
831   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
832   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
833   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
834   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
835   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
836   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
837   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
838   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
839   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
840   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
841   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
842   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
843   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
844   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
845   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
846   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
847   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
848   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
849   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
850
851   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
852     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
853
854     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
855     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
856     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
857     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
858     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
859     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
860     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
861     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
862     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
863     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
864     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
865     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
866   }
867
868   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
869     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
870
871     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
872     // registers cannot be used even for integer operations.
873     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
874     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
875     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
876     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
877
878     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
879     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
880     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
881     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
882     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
883     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
884     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
885     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
886     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
887     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
888     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
889     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
890     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
891     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
892     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
893     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
894     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
895     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
896
897     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
898     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
899     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
900     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
901
902     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
903     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
904     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
905     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
906     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
907
908     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
909     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910       MVT VT = (MVT::SimpleValueType)i;
911       // Do not attempt to custom lower non-power-of-2 vectors
912       if (!isPowerOf2_32(VT.getVectorNumElements()))
913         continue;
914       // Do not attempt to custom lower non-128-bit vectors
915       if (!VT.is128BitVector())
916         continue;
917       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
918       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
919       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
920     }
921
922     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
925     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
926     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
927     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
928
929     if (Subtarget->is64Bit()) {
930       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
931       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
932     }
933
934     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
935     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
936       MVT VT = (MVT::SimpleValueType)i;
937
938       // Do not attempt to promote non-128-bit vectors
939       if (!VT.is128BitVector())
940         continue;
941
942       setOperationAction(ISD::AND,    VT, Promote);
943       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
944       setOperationAction(ISD::OR,     VT, Promote);
945       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
946       setOperationAction(ISD::XOR,    VT, Promote);
947       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
948       setOperationAction(ISD::LOAD,   VT, Promote);
949       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
950       setOperationAction(ISD::SELECT, VT, Promote);
951       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
952     }
953
954     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
955
956     // Custom lower v2i64 and v2f64 selects.
957     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
958     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
959     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
960     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
961
962     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
963     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
964
965     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
966     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
967     // As there is no 64-bit GPR available, we need build a special custom
968     // sequence to convert from v2i32 to v2f32.
969     if (!Subtarget->is64Bit())
970       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
971
972     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
973     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
974
975     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
976   }
977
978   if (Subtarget->hasSSE41()) {
979     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
980     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
981     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
982     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
983     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
984     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
985     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
986     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
987     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
988     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
989
990     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
991     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
992     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
993     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
994     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
995     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
996     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
997     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
998     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
999     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1000
1001     // FIXME: Do we need to handle scalar-to-vector here?
1002     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1003
1004     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1005     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1006     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1007     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1008     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1009
1010     // i8 and i16 vectors are custom , because the source register and source
1011     // source memory operand types are not the same width.  f32 vectors are
1012     // custom since the immediate controlling the insert encodes additional
1013     // information.
1014     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1015     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1016     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1017     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1018
1019     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1020     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1021     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1022     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1023
1024     // FIXME: these should be Legal but thats only for the case where
1025     // the index is constant.  For now custom expand to deal with that.
1026     if (Subtarget->is64Bit()) {
1027       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1028       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1029     }
1030   }
1031
1032   if (Subtarget->hasSSE2()) {
1033     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1034     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1035
1036     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1037     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1038
1039     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1040     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1041
1042     if (Subtarget->hasInt256()) {
1043       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1044       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1045
1046       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1047       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1048
1049       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1050     } else {
1051       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1052       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1053
1054       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1055       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1056
1057       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1058     }
1059     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1060     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1061   }
1062
1063   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1064     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1065     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1066     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1067     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1068     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1069     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1070
1071     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1072     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1073     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1074
1075     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1076     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1077     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1078     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1080     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1081     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1082     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1083     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1084     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1085     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1086     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1087
1088     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1089     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1091     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1093     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1094     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1095     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1096     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1097     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1098     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1099     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1100
1101     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1102     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1103
1104     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1105
1106     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1107     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1108     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1109
1110     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1111     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1112     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1113
1114     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1115
1116     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1117     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1118
1119     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1120     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1121
1122     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1123     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1124
1125     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1126
1127     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1128     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1129     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1131
1132     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1133     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1134     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1135
1136     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1137     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1138     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1139     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1140
1141     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1142     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1143     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1144     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1146     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1147
1148     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1149       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1150       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1151       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1152       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1153       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1154       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1155     }
1156
1157     if (Subtarget->hasInt256()) {
1158       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1159       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1160       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1161       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1162
1163       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1164       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1165       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1166       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1167
1168       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1169       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1170       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1171       // Don't lower v32i8 because there is no 128-bit byte mul
1172
1173       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1174
1175       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1177
1178       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1179       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1180
1181       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1182
1183       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1184     } else {
1185       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1187       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1188       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1189
1190       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1191       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1192       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1193       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1194
1195       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1196       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1197       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1198       // Don't lower v32i8 because there is no 128-bit byte mul
1199
1200       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1201       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1202
1203       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1205
1206       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1207     }
1208
1209     // Custom lower several nodes for 256-bit types.
1210     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1211              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1212       MVT VT = (MVT::SimpleValueType)i;
1213
1214       // Extract subvector is special because the value type
1215       // (result) is 128-bit but the source is 256-bit wide.
1216       if (VT.is128BitVector())
1217         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1218
1219       // Do not attempt to custom lower other non-256-bit vectors
1220       if (!VT.is256BitVector())
1221         continue;
1222
1223       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1224       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1225       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1226       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1227       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1228       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1229       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1230     }
1231
1232     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1233     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1234       MVT VT = (MVT::SimpleValueType)i;
1235
1236       // Do not attempt to promote non-256-bit vectors
1237       if (!VT.is256BitVector())
1238         continue;
1239
1240       setOperationAction(ISD::AND,    VT, Promote);
1241       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1242       setOperationAction(ISD::OR,     VT, Promote);
1243       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1244       setOperationAction(ISD::XOR,    VT, Promote);
1245       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1246       setOperationAction(ISD::LOAD,   VT, Promote);
1247       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1248       setOperationAction(ISD::SELECT, VT, Promote);
1249       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1250     }
1251   }
1252
1253   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1254   // of this type with custom code.
1255   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1256            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1257     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1258                        Custom);
1259   }
1260
1261   // We want to custom lower some of our intrinsics.
1262   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1263   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1264
1265   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1266   // handle type legalization for these operations here.
1267   //
1268   // FIXME: We really should do custom legalization for addition and
1269   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1270   // than generic legalization for 64-bit multiplication-with-overflow, though.
1271   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1272     // Add/Sub/Mul with overflow operations are custom lowered.
1273     MVT VT = IntVTs[i];
1274     setOperationAction(ISD::SADDO, VT, Custom);
1275     setOperationAction(ISD::UADDO, VT, Custom);
1276     setOperationAction(ISD::SSUBO, VT, Custom);
1277     setOperationAction(ISD::USUBO, VT, Custom);
1278     setOperationAction(ISD::SMULO, VT, Custom);
1279     setOperationAction(ISD::UMULO, VT, Custom);
1280   }
1281
1282   // There are no 8-bit 3-address imul/mul instructions
1283   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1284   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1285
1286   if (!Subtarget->is64Bit()) {
1287     // These libcalls are not available in 32-bit.
1288     setLibcallName(RTLIB::SHL_I128, 0);
1289     setLibcallName(RTLIB::SRL_I128, 0);
1290     setLibcallName(RTLIB::SRA_I128, 0);
1291   }
1292
1293   // Combine sin / cos into one node or libcall if possible.
1294   if (Subtarget->hasSinCos()) {
1295     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1296     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1297     if (Subtarget->isTargetDarwin() && Subtarget->is64Bit()) {
1298       // For MacOSX, we don't want to the normal expansion of a libcall to
1299       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1300       // traffic.
1301       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1302       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1303     }
1304   }
1305
1306   // We have target-specific dag combine patterns for the following nodes:
1307   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1308   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1309   setTargetDAGCombine(ISD::VSELECT);
1310   setTargetDAGCombine(ISD::SELECT);
1311   setTargetDAGCombine(ISD::SHL);
1312   setTargetDAGCombine(ISD::SRA);
1313   setTargetDAGCombine(ISD::SRL);
1314   setTargetDAGCombine(ISD::OR);
1315   setTargetDAGCombine(ISD::AND);
1316   setTargetDAGCombine(ISD::ADD);
1317   setTargetDAGCombine(ISD::FADD);
1318   setTargetDAGCombine(ISD::FSUB);
1319   setTargetDAGCombine(ISD::FMA);
1320   setTargetDAGCombine(ISD::SUB);
1321   setTargetDAGCombine(ISD::LOAD);
1322   setTargetDAGCombine(ISD::STORE);
1323   setTargetDAGCombine(ISD::ZERO_EXTEND);
1324   setTargetDAGCombine(ISD::ANY_EXTEND);
1325   setTargetDAGCombine(ISD::SIGN_EXTEND);
1326   setTargetDAGCombine(ISD::TRUNCATE);
1327   setTargetDAGCombine(ISD::SINT_TO_FP);
1328   setTargetDAGCombine(ISD::SETCC);
1329   if (Subtarget->is64Bit())
1330     setTargetDAGCombine(ISD::MUL);
1331   setTargetDAGCombine(ISD::XOR);
1332
1333   computeRegisterProperties();
1334
1335   // On Darwin, -Os means optimize for size without hurting performance,
1336   // do not reduce the limit.
1337   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1338   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1339   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1340   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1341   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1342   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1343   setPrefLoopAlignment(4); // 2^4 bytes.
1344   benefitFromCodePlacementOpt = true;
1345
1346   // Predictable cmov don't hurt on atom because it's in-order.
1347   predictableSelectIsExpensive = !Subtarget->isAtom();
1348
1349   setPrefFunctionAlignment(4); // 2^4 bytes.
1350 }
1351
1352 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1353   if (!VT.isVector()) return MVT::i8;
1354   return VT.changeVectorElementTypeToInteger();
1355 }
1356
1357 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1358 /// the desired ByVal argument alignment.
1359 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1360   if (MaxAlign == 16)
1361     return;
1362   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1363     if (VTy->getBitWidth() == 128)
1364       MaxAlign = 16;
1365   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1366     unsigned EltAlign = 0;
1367     getMaxByValAlign(ATy->getElementType(), EltAlign);
1368     if (EltAlign > MaxAlign)
1369       MaxAlign = EltAlign;
1370   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1371     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1372       unsigned EltAlign = 0;
1373       getMaxByValAlign(STy->getElementType(i), EltAlign);
1374       if (EltAlign > MaxAlign)
1375         MaxAlign = EltAlign;
1376       if (MaxAlign == 16)
1377         break;
1378     }
1379   }
1380 }
1381
1382 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1383 /// function arguments in the caller parameter area. For X86, aggregates
1384 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1385 /// are at 4-byte boundaries.
1386 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1387   if (Subtarget->is64Bit()) {
1388     // Max of 8 and alignment of type.
1389     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1390     if (TyAlign > 8)
1391       return TyAlign;
1392     return 8;
1393   }
1394
1395   unsigned Align = 4;
1396   if (Subtarget->hasSSE1())
1397     getMaxByValAlign(Ty, Align);
1398   return Align;
1399 }
1400
1401 /// getOptimalMemOpType - Returns the target specific optimal type for load
1402 /// and store operations as a result of memset, memcpy, and memmove
1403 /// lowering. If DstAlign is zero that means it's safe to destination
1404 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1405 /// means there isn't a need to check it against alignment requirement,
1406 /// probably because the source does not need to be loaded. If 'IsMemset' is
1407 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1408 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1409 /// source is constant so it does not need to be loaded.
1410 /// It returns EVT::Other if the type should be determined using generic
1411 /// target-independent logic.
1412 EVT
1413 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1414                                        unsigned DstAlign, unsigned SrcAlign,
1415                                        bool IsMemset, bool ZeroMemset,
1416                                        bool MemcpyStrSrc,
1417                                        MachineFunction &MF) const {
1418   const Function *F = MF.getFunction();
1419   if ((!IsMemset || ZeroMemset) &&
1420       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1421                                        Attribute::NoImplicitFloat)) {
1422     if (Size >= 16 &&
1423         (Subtarget->isUnalignedMemAccessFast() ||
1424          ((DstAlign == 0 || DstAlign >= 16) &&
1425           (SrcAlign == 0 || SrcAlign >= 16)))) {
1426       if (Size >= 32) {
1427         if (Subtarget->hasInt256())
1428           return MVT::v8i32;
1429         if (Subtarget->hasFp256())
1430           return MVT::v8f32;
1431       }
1432       if (Subtarget->hasSSE2())
1433         return MVT::v4i32;
1434       if (Subtarget->hasSSE1())
1435         return MVT::v4f32;
1436     } else if (!MemcpyStrSrc && Size >= 8 &&
1437                !Subtarget->is64Bit() &&
1438                Subtarget->hasSSE2()) {
1439       // Do not use f64 to lower memcpy if source is string constant. It's
1440       // better to use i32 to avoid the loads.
1441       return MVT::f64;
1442     }
1443   }
1444   if (Subtarget->is64Bit() && Size >= 8)
1445     return MVT::i64;
1446   return MVT::i32;
1447 }
1448
1449 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1450   if (VT == MVT::f32)
1451     return X86ScalarSSEf32;
1452   else if (VT == MVT::f64)
1453     return X86ScalarSSEf64;
1454   return true;
1455 }
1456
1457 bool
1458 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1459   if (Fast)
1460     *Fast = Subtarget->isUnalignedMemAccessFast();
1461   return true;
1462 }
1463
1464 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1465 /// current function.  The returned value is a member of the
1466 /// MachineJumpTableInfo::JTEntryKind enum.
1467 unsigned X86TargetLowering::getJumpTableEncoding() const {
1468   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1469   // symbol.
1470   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1471       Subtarget->isPICStyleGOT())
1472     return MachineJumpTableInfo::EK_Custom32;
1473
1474   // Otherwise, use the normal jump table encoding heuristics.
1475   return TargetLowering::getJumpTableEncoding();
1476 }
1477
1478 const MCExpr *
1479 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1480                                              const MachineBasicBlock *MBB,
1481                                              unsigned uid,MCContext &Ctx) const{
1482   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1483          Subtarget->isPICStyleGOT());
1484   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1485   // entries.
1486   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1487                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1488 }
1489
1490 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1491 /// jumptable.
1492 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1493                                                     SelectionDAG &DAG) const {
1494   if (!Subtarget->is64Bit())
1495     // This doesn't have DebugLoc associated with it, but is not really the
1496     // same as a Register.
1497     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1498   return Table;
1499 }
1500
1501 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1502 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1503 /// MCExpr.
1504 const MCExpr *X86TargetLowering::
1505 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1506                              MCContext &Ctx) const {
1507   // X86-64 uses RIP relative addressing based on the jump table label.
1508   if (Subtarget->isPICStyleRIPRel())
1509     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1510
1511   // Otherwise, the reference is relative to the PIC base.
1512   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1513 }
1514
1515 // FIXME: Why this routine is here? Move to RegInfo!
1516 std::pair<const TargetRegisterClass*, uint8_t>
1517 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1518   const TargetRegisterClass *RRC = 0;
1519   uint8_t Cost = 1;
1520   switch (VT.SimpleTy) {
1521   default:
1522     return TargetLowering::findRepresentativeClass(VT);
1523   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1524     RRC = Subtarget->is64Bit() ?
1525       (const TargetRegisterClass*)&X86::GR64RegClass :
1526       (const TargetRegisterClass*)&X86::GR32RegClass;
1527     break;
1528   case MVT::x86mmx:
1529     RRC = &X86::VR64RegClass;
1530     break;
1531   case MVT::f32: case MVT::f64:
1532   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1533   case MVT::v4f32: case MVT::v2f64:
1534   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1535   case MVT::v4f64:
1536     RRC = &X86::VR128RegClass;
1537     break;
1538   }
1539   return std::make_pair(RRC, Cost);
1540 }
1541
1542 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1543                                                unsigned &Offset) const {
1544   if (!Subtarget->isTargetLinux())
1545     return false;
1546
1547   if (Subtarget->is64Bit()) {
1548     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1549     Offset = 0x28;
1550     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1551       AddressSpace = 256;
1552     else
1553       AddressSpace = 257;
1554   } else {
1555     // %gs:0x14 on i386
1556     Offset = 0x14;
1557     AddressSpace = 256;
1558   }
1559   return true;
1560 }
1561
1562 //===----------------------------------------------------------------------===//
1563 //               Return Value Calling Convention Implementation
1564 //===----------------------------------------------------------------------===//
1565
1566 #include "X86GenCallingConv.inc"
1567
1568 bool
1569 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1570                                   MachineFunction &MF, bool isVarArg,
1571                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1572                         LLVMContext &Context) const {
1573   SmallVector<CCValAssign, 16> RVLocs;
1574   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1575                  RVLocs, Context);
1576   return CCInfo.CheckReturn(Outs, RetCC_X86);
1577 }
1578
1579 SDValue
1580 X86TargetLowering::LowerReturn(SDValue Chain,
1581                                CallingConv::ID CallConv, bool isVarArg,
1582                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1583                                const SmallVectorImpl<SDValue> &OutVals,
1584                                DebugLoc dl, SelectionDAG &DAG) const {
1585   MachineFunction &MF = DAG.getMachineFunction();
1586   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1587
1588   SmallVector<CCValAssign, 16> RVLocs;
1589   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1590                  RVLocs, *DAG.getContext());
1591   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1592
1593   // Add the regs to the liveout set for the function.
1594   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1595   for (unsigned i = 0; i != RVLocs.size(); ++i)
1596     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1597       MRI.addLiveOut(RVLocs[i].getLocReg());
1598
1599   SDValue Flag;
1600
1601   SmallVector<SDValue, 6> RetOps;
1602   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1603   // Operand #1 = Bytes To Pop
1604   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1605                    MVT::i16));
1606
1607   // Copy the result values into the output registers.
1608   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1609     CCValAssign &VA = RVLocs[i];
1610     assert(VA.isRegLoc() && "Can only return in registers!");
1611     SDValue ValToCopy = OutVals[i];
1612     EVT ValVT = ValToCopy.getValueType();
1613
1614     // Promote values to the appropriate types
1615     if (VA.getLocInfo() == CCValAssign::SExt)
1616       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1617     else if (VA.getLocInfo() == CCValAssign::ZExt)
1618       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1619     else if (VA.getLocInfo() == CCValAssign::AExt)
1620       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1621     else if (VA.getLocInfo() == CCValAssign::BCvt)
1622       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1623
1624     // If this is x86-64, and we disabled SSE, we can't return FP values,
1625     // or SSE or MMX vectors.
1626     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1627          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1628           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1629       report_fatal_error("SSE register return with SSE disabled");
1630     }
1631     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1632     // llvm-gcc has never done it right and no one has noticed, so this
1633     // should be OK for now.
1634     if (ValVT == MVT::f64 &&
1635         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1636       report_fatal_error("SSE2 register return with SSE2 disabled");
1637
1638     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1639     // the RET instruction and handled by the FP Stackifier.
1640     if (VA.getLocReg() == X86::ST0 ||
1641         VA.getLocReg() == X86::ST1) {
1642       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1643       // change the value to the FP stack register class.
1644       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1645         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1646       RetOps.push_back(ValToCopy);
1647       // Don't emit a copytoreg.
1648       continue;
1649     }
1650
1651     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1652     // which is returned in RAX / RDX.
1653     if (Subtarget->is64Bit()) {
1654       if (ValVT == MVT::x86mmx) {
1655         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1656           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1657           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1658                                   ValToCopy);
1659           // If we don't have SSE2 available, convert to v4f32 so the generated
1660           // register is legal.
1661           if (!Subtarget->hasSSE2())
1662             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1663         }
1664       }
1665     }
1666
1667     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1668     Flag = Chain.getValue(1);
1669   }
1670
1671   // The x86-64 ABIs require that for returning structs by value we copy
1672   // the sret argument into %rax/%eax (depending on ABI) for the return.
1673   // We saved the argument into a virtual register in the entry block,
1674   // so now we copy the value out and into %rax/%eax.
1675   if (Subtarget->is64Bit() &&
1676       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1677     MachineFunction &MF = DAG.getMachineFunction();
1678     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1679     unsigned Reg = FuncInfo->getSRetReturnReg();
1680     assert(Reg &&
1681            "SRetReturnReg should have been set in LowerFormalArguments().");
1682     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1683
1684     unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1685     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1686     Flag = Chain.getValue(1);
1687
1688     // RAX/EAX now acts like a return value.
1689     MRI.addLiveOut(RetValReg);
1690   }
1691
1692   RetOps[0] = Chain;  // Update chain.
1693
1694   // Add the flag if we have it.
1695   if (Flag.getNode())
1696     RetOps.push_back(Flag);
1697
1698   return DAG.getNode(X86ISD::RET_FLAG, dl,
1699                      MVT::Other, &RetOps[0], RetOps.size());
1700 }
1701
1702 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1703   if (N->getNumValues() != 1)
1704     return false;
1705   if (!N->hasNUsesOfValue(1, 0))
1706     return false;
1707
1708   SDValue TCChain = Chain;
1709   SDNode *Copy = *N->use_begin();
1710   if (Copy->getOpcode() == ISD::CopyToReg) {
1711     // If the copy has a glue operand, we conservatively assume it isn't safe to
1712     // perform a tail call.
1713     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1714       return false;
1715     TCChain = Copy->getOperand(0);
1716   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1717     return false;
1718
1719   bool HasRet = false;
1720   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1721        UI != UE; ++UI) {
1722     if (UI->getOpcode() != X86ISD::RET_FLAG)
1723       return false;
1724     HasRet = true;
1725   }
1726
1727   if (!HasRet)
1728     return false;
1729
1730   Chain = TCChain;
1731   return true;
1732 }
1733
1734 MVT
1735 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1736                                             ISD::NodeType ExtendKind) const {
1737   MVT ReturnMVT;
1738   // TODO: Is this also valid on 32-bit?
1739   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1740     ReturnMVT = MVT::i8;
1741   else
1742     ReturnMVT = MVT::i32;
1743
1744   MVT MinVT = getRegisterType(ReturnMVT);
1745   return VT.bitsLT(MinVT) ? MinVT : VT;
1746 }
1747
1748 /// LowerCallResult - Lower the result values of a call into the
1749 /// appropriate copies out of appropriate physical registers.
1750 ///
1751 SDValue
1752 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1753                                    CallingConv::ID CallConv, bool isVarArg,
1754                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1755                                    DebugLoc dl, SelectionDAG &DAG,
1756                                    SmallVectorImpl<SDValue> &InVals) const {
1757
1758   // Assign locations to each value returned by this call.
1759   SmallVector<CCValAssign, 16> RVLocs;
1760   bool Is64Bit = Subtarget->is64Bit();
1761   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1762                  getTargetMachine(), RVLocs, *DAG.getContext());
1763   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1764
1765   // Copy all of the result registers out of their specified physreg.
1766   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1767     CCValAssign &VA = RVLocs[i];
1768     EVT CopyVT = VA.getValVT();
1769
1770     // If this is x86-64, and we disabled SSE, we can't return FP values
1771     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1772         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1773       report_fatal_error("SSE register return with SSE disabled");
1774     }
1775
1776     SDValue Val;
1777
1778     // If this is a call to a function that returns an fp value on the floating
1779     // point stack, we must guarantee the value is popped from the stack, so
1780     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1781     // if the return value is not used. We use the FpPOP_RETVAL instruction
1782     // instead.
1783     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1784       // If we prefer to use the value in xmm registers, copy it out as f80 and
1785       // use a truncate to move it from fp stack reg to xmm reg.
1786       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1787       SDValue Ops[] = { Chain, InFlag };
1788       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1789                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1790       Val = Chain.getValue(0);
1791
1792       // Round the f80 to the right size, which also moves it to the appropriate
1793       // xmm register.
1794       if (CopyVT != VA.getValVT())
1795         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1796                           // This truncation won't change the value.
1797                           DAG.getIntPtrConstant(1));
1798     } else {
1799       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1800                                  CopyVT, InFlag).getValue(1);
1801       Val = Chain.getValue(0);
1802     }
1803     InFlag = Chain.getValue(2);
1804     InVals.push_back(Val);
1805   }
1806
1807   return Chain;
1808 }
1809
1810 //===----------------------------------------------------------------------===//
1811 //                C & StdCall & Fast Calling Convention implementation
1812 //===----------------------------------------------------------------------===//
1813 //  StdCall calling convention seems to be standard for many Windows' API
1814 //  routines and around. It differs from C calling convention just a little:
1815 //  callee should clean up the stack, not caller. Symbols should be also
1816 //  decorated in some fancy way :) It doesn't support any vector arguments.
1817 //  For info on fast calling convention see Fast Calling Convention (tail call)
1818 //  implementation LowerX86_32FastCCCallTo.
1819
1820 /// CallIsStructReturn - Determines whether a call uses struct return
1821 /// semantics.
1822 enum StructReturnType {
1823   NotStructReturn,
1824   RegStructReturn,
1825   StackStructReturn
1826 };
1827 static StructReturnType
1828 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1829   if (Outs.empty())
1830     return NotStructReturn;
1831
1832   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1833   if (!Flags.isSRet())
1834     return NotStructReturn;
1835   if (Flags.isInReg())
1836     return RegStructReturn;
1837   return StackStructReturn;
1838 }
1839
1840 /// ArgsAreStructReturn - Determines whether a function uses struct
1841 /// return semantics.
1842 static StructReturnType
1843 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1844   if (Ins.empty())
1845     return NotStructReturn;
1846
1847   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1848   if (!Flags.isSRet())
1849     return NotStructReturn;
1850   if (Flags.isInReg())
1851     return RegStructReturn;
1852   return StackStructReturn;
1853 }
1854
1855 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1856 /// by "Src" to address "Dst" with size and alignment information specified by
1857 /// the specific parameter attribute. The copy will be passed as a byval
1858 /// function parameter.
1859 static SDValue
1860 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1861                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1862                           DebugLoc dl) {
1863   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1864
1865   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1866                        /*isVolatile*/false, /*AlwaysInline=*/true,
1867                        MachinePointerInfo(), MachinePointerInfo());
1868 }
1869
1870 /// IsTailCallConvention - Return true if the calling convention is one that
1871 /// supports tail call optimization.
1872 static bool IsTailCallConvention(CallingConv::ID CC) {
1873   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1874           CC == CallingConv::HiPE);
1875 }
1876
1877 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1878   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1879     return false;
1880
1881   CallSite CS(CI);
1882   CallingConv::ID CalleeCC = CS.getCallingConv();
1883   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1884     return false;
1885
1886   return true;
1887 }
1888
1889 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1890 /// a tailcall target by changing its ABI.
1891 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1892                                    bool GuaranteedTailCallOpt) {
1893   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1894 }
1895
1896 SDValue
1897 X86TargetLowering::LowerMemArgument(SDValue Chain,
1898                                     CallingConv::ID CallConv,
1899                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1900                                     DebugLoc dl, SelectionDAG &DAG,
1901                                     const CCValAssign &VA,
1902                                     MachineFrameInfo *MFI,
1903                                     unsigned i) const {
1904   // Create the nodes corresponding to a load from this parameter slot.
1905   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1906   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1907                               getTargetMachine().Options.GuaranteedTailCallOpt);
1908   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1909   EVT ValVT;
1910
1911   // If value is passed by pointer we have address passed instead of the value
1912   // itself.
1913   if (VA.getLocInfo() == CCValAssign::Indirect)
1914     ValVT = VA.getLocVT();
1915   else
1916     ValVT = VA.getValVT();
1917
1918   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1919   // changed with more analysis.
1920   // In case of tail call optimization mark all arguments mutable. Since they
1921   // could be overwritten by lowering of arguments in case of a tail call.
1922   if (Flags.isByVal()) {
1923     unsigned Bytes = Flags.getByValSize();
1924     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1925     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1926     return DAG.getFrameIndex(FI, getPointerTy());
1927   } else {
1928     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1929                                     VA.getLocMemOffset(), isImmutable);
1930     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1931     return DAG.getLoad(ValVT, dl, Chain, FIN,
1932                        MachinePointerInfo::getFixedStack(FI),
1933                        false, false, false, 0);
1934   }
1935 }
1936
1937 SDValue
1938 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1939                                         CallingConv::ID CallConv,
1940                                         bool isVarArg,
1941                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1942                                         DebugLoc dl,
1943                                         SelectionDAG &DAG,
1944                                         SmallVectorImpl<SDValue> &InVals)
1945                                           const {
1946   MachineFunction &MF = DAG.getMachineFunction();
1947   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1948
1949   const Function* Fn = MF.getFunction();
1950   if (Fn->hasExternalLinkage() &&
1951       Subtarget->isTargetCygMing() &&
1952       Fn->getName() == "main")
1953     FuncInfo->setForceFramePointer(true);
1954
1955   MachineFrameInfo *MFI = MF.getFrameInfo();
1956   bool Is64Bit = Subtarget->is64Bit();
1957   bool IsWindows = Subtarget->isTargetWindows();
1958   bool IsWin64 = Subtarget->isTargetWin64();
1959
1960   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1961          "Var args not supported with calling convention fastcc, ghc or hipe");
1962
1963   // Assign locations to all of the incoming arguments.
1964   SmallVector<CCValAssign, 16> ArgLocs;
1965   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1966                  ArgLocs, *DAG.getContext());
1967
1968   // Allocate shadow area for Win64
1969   if (IsWin64) {
1970     CCInfo.AllocateStack(32, 8);
1971   }
1972
1973   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1974
1975   unsigned LastVal = ~0U;
1976   SDValue ArgValue;
1977   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1978     CCValAssign &VA = ArgLocs[i];
1979     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1980     // places.
1981     assert(VA.getValNo() != LastVal &&
1982            "Don't support value assigned to multiple locs yet");
1983     (void)LastVal;
1984     LastVal = VA.getValNo();
1985
1986     if (VA.isRegLoc()) {
1987       EVT RegVT = VA.getLocVT();
1988       const TargetRegisterClass *RC;
1989       if (RegVT == MVT::i32)
1990         RC = &X86::GR32RegClass;
1991       else if (Is64Bit && RegVT == MVT::i64)
1992         RC = &X86::GR64RegClass;
1993       else if (RegVT == MVT::f32)
1994         RC = &X86::FR32RegClass;
1995       else if (RegVT == MVT::f64)
1996         RC = &X86::FR64RegClass;
1997       else if (RegVT.is256BitVector())
1998         RC = &X86::VR256RegClass;
1999       else if (RegVT.is128BitVector())
2000         RC = &X86::VR128RegClass;
2001       else if (RegVT == MVT::x86mmx)
2002         RC = &X86::VR64RegClass;
2003       else
2004         llvm_unreachable("Unknown argument type!");
2005
2006       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2007       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2008
2009       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2010       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2011       // right size.
2012       if (VA.getLocInfo() == CCValAssign::SExt)
2013         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2014                                DAG.getValueType(VA.getValVT()));
2015       else if (VA.getLocInfo() == CCValAssign::ZExt)
2016         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2017                                DAG.getValueType(VA.getValVT()));
2018       else if (VA.getLocInfo() == CCValAssign::BCvt)
2019         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2020
2021       if (VA.isExtInLoc()) {
2022         // Handle MMX values passed in XMM regs.
2023         if (RegVT.isVector())
2024           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2025         else
2026           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2027       }
2028     } else {
2029       assert(VA.isMemLoc());
2030       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2031     }
2032
2033     // If value is passed via pointer - do a load.
2034     if (VA.getLocInfo() == CCValAssign::Indirect)
2035       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2036                              MachinePointerInfo(), false, false, false, 0);
2037
2038     InVals.push_back(ArgValue);
2039   }
2040
2041   // The x86-64 ABIs require that for returning structs by value we copy
2042   // the sret argument into %rax/%eax (depending on ABI) for the return.
2043   // Save the argument into a virtual register so that we can access it
2044   // from the return points.
2045   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2046     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2047     unsigned Reg = FuncInfo->getSRetReturnReg();
2048     if (!Reg) {
2049       MVT PtrTy = getPointerTy();
2050       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2051       FuncInfo->setSRetReturnReg(Reg);
2052     }
2053     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2054     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2055   }
2056
2057   unsigned StackSize = CCInfo.getNextStackOffset();
2058   // Align stack specially for tail calls.
2059   if (FuncIsMadeTailCallSafe(CallConv,
2060                              MF.getTarget().Options.GuaranteedTailCallOpt))
2061     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2062
2063   // If the function takes variable number of arguments, make a frame index for
2064   // the start of the first vararg value... for expansion of llvm.va_start.
2065   if (isVarArg) {
2066     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2067                     CallConv != CallingConv::X86_ThisCall)) {
2068       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2069     }
2070     if (Is64Bit) {
2071       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2072
2073       // FIXME: We should really autogenerate these arrays
2074       static const uint16_t GPR64ArgRegsWin64[] = {
2075         X86::RCX, X86::RDX, X86::R8,  X86::R9
2076       };
2077       static const uint16_t GPR64ArgRegs64Bit[] = {
2078         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2079       };
2080       static const uint16_t XMMArgRegs64Bit[] = {
2081         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2082         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2083       };
2084       const uint16_t *GPR64ArgRegs;
2085       unsigned NumXMMRegs = 0;
2086
2087       if (IsWin64) {
2088         // The XMM registers which might contain var arg parameters are shadowed
2089         // in their paired GPR.  So we only need to save the GPR to their home
2090         // slots.
2091         TotalNumIntRegs = 4;
2092         GPR64ArgRegs = GPR64ArgRegsWin64;
2093       } else {
2094         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2095         GPR64ArgRegs = GPR64ArgRegs64Bit;
2096
2097         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2098                                                 TotalNumXMMRegs);
2099       }
2100       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2101                                                        TotalNumIntRegs);
2102
2103       bool NoImplicitFloatOps = Fn->getAttributes().
2104         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2105       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2106              "SSE register cannot be used when SSE is disabled!");
2107       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2108                NoImplicitFloatOps) &&
2109              "SSE register cannot be used when SSE is disabled!");
2110       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2111           !Subtarget->hasSSE1())
2112         // Kernel mode asks for SSE to be disabled, so don't push them
2113         // on the stack.
2114         TotalNumXMMRegs = 0;
2115
2116       if (IsWin64) {
2117         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2118         // Get to the caller-allocated home save location.  Add 8 to account
2119         // for the return address.
2120         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2121         FuncInfo->setRegSaveFrameIndex(
2122           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2123         // Fixup to set vararg frame on shadow area (4 x i64).
2124         if (NumIntRegs < 4)
2125           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2126       } else {
2127         // For X86-64, if there are vararg parameters that are passed via
2128         // registers, then we must store them to their spots on the stack so
2129         // they may be loaded by deferencing the result of va_next.
2130         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2131         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2132         FuncInfo->setRegSaveFrameIndex(
2133           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2134                                false));
2135       }
2136
2137       // Store the integer parameter registers.
2138       SmallVector<SDValue, 8> MemOps;
2139       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2140                                         getPointerTy());
2141       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2142       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2143         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2144                                   DAG.getIntPtrConstant(Offset));
2145         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2146                                      &X86::GR64RegClass);
2147         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2148         SDValue Store =
2149           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2150                        MachinePointerInfo::getFixedStack(
2151                          FuncInfo->getRegSaveFrameIndex(), Offset),
2152                        false, false, 0);
2153         MemOps.push_back(Store);
2154         Offset += 8;
2155       }
2156
2157       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2158         // Now store the XMM (fp + vector) parameter registers.
2159         SmallVector<SDValue, 11> SaveXMMOps;
2160         SaveXMMOps.push_back(Chain);
2161
2162         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2163         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2164         SaveXMMOps.push_back(ALVal);
2165
2166         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2167                                FuncInfo->getRegSaveFrameIndex()));
2168         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2169                                FuncInfo->getVarArgsFPOffset()));
2170
2171         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2172           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2173                                        &X86::VR128RegClass);
2174           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2175           SaveXMMOps.push_back(Val);
2176         }
2177         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2178                                      MVT::Other,
2179                                      &SaveXMMOps[0], SaveXMMOps.size()));
2180       }
2181
2182       if (!MemOps.empty())
2183         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2184                             &MemOps[0], MemOps.size());
2185     }
2186   }
2187
2188   // Some CCs need callee pop.
2189   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2190                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2191     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2192   } else {
2193     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2194     // If this is an sret function, the return should pop the hidden pointer.
2195     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2196         argsAreStructReturn(Ins) == StackStructReturn)
2197       FuncInfo->setBytesToPopOnReturn(4);
2198   }
2199
2200   if (!Is64Bit) {
2201     // RegSaveFrameIndex is X86-64 only.
2202     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2203     if (CallConv == CallingConv::X86_FastCall ||
2204         CallConv == CallingConv::X86_ThisCall)
2205       // fastcc functions can't have varargs.
2206       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2207   }
2208
2209   FuncInfo->setArgumentStackSize(StackSize);
2210
2211   return Chain;
2212 }
2213
2214 SDValue
2215 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2216                                     SDValue StackPtr, SDValue Arg,
2217                                     DebugLoc dl, SelectionDAG &DAG,
2218                                     const CCValAssign &VA,
2219                                     ISD::ArgFlagsTy Flags) const {
2220   unsigned LocMemOffset = VA.getLocMemOffset();
2221   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2222   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2223   if (Flags.isByVal())
2224     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2225
2226   return DAG.getStore(Chain, dl, Arg, PtrOff,
2227                       MachinePointerInfo::getStack(LocMemOffset),
2228                       false, false, 0);
2229 }
2230
2231 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2232 /// optimization is performed and it is required.
2233 SDValue
2234 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2235                                            SDValue &OutRetAddr, SDValue Chain,
2236                                            bool IsTailCall, bool Is64Bit,
2237                                            int FPDiff, DebugLoc dl) const {
2238   // Adjust the Return address stack slot.
2239   EVT VT = getPointerTy();
2240   OutRetAddr = getReturnAddressFrameIndex(DAG);
2241
2242   // Load the "old" Return address.
2243   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2244                            false, false, false, 0);
2245   return SDValue(OutRetAddr.getNode(), 1);
2246 }
2247
2248 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2249 /// optimization is performed and it is required (FPDiff!=0).
2250 static SDValue
2251 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2252                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2253                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2254   // Store the return address to the appropriate stack slot.
2255   if (!FPDiff) return Chain;
2256   // Calculate the new stack slot for the return address.
2257   int NewReturnAddrFI =
2258     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2259   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2260   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2261                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2262                        false, false, 0);
2263   return Chain;
2264 }
2265
2266 SDValue
2267 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2268                              SmallVectorImpl<SDValue> &InVals) const {
2269   SelectionDAG &DAG                     = CLI.DAG;
2270   DebugLoc &dl                          = CLI.DL;
2271   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2272   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2273   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2274   SDValue Chain                         = CLI.Chain;
2275   SDValue Callee                        = CLI.Callee;
2276   CallingConv::ID CallConv              = CLI.CallConv;
2277   bool &isTailCall                      = CLI.IsTailCall;
2278   bool isVarArg                         = CLI.IsVarArg;
2279
2280   MachineFunction &MF = DAG.getMachineFunction();
2281   bool Is64Bit        = Subtarget->is64Bit();
2282   bool IsWin64        = Subtarget->isTargetWin64();
2283   bool IsWindows      = Subtarget->isTargetWindows();
2284   StructReturnType SR = callIsStructReturn(Outs);
2285   bool IsSibcall      = false;
2286
2287   if (MF.getTarget().Options.DisableTailCalls)
2288     isTailCall = false;
2289
2290   if (isTailCall) {
2291     // Check if it's really possible to do a tail call.
2292     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2293                     isVarArg, SR != NotStructReturn,
2294                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2295                     Outs, OutVals, Ins, DAG);
2296
2297     // Sibcalls are automatically detected tailcalls which do not require
2298     // ABI changes.
2299     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2300       IsSibcall = true;
2301
2302     if (isTailCall)
2303       ++NumTailCalls;
2304   }
2305
2306   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2307          "Var args not supported with calling convention fastcc, ghc or hipe");
2308
2309   // Analyze operands of the call, assigning locations to each operand.
2310   SmallVector<CCValAssign, 16> ArgLocs;
2311   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2312                  ArgLocs, *DAG.getContext());
2313
2314   // Allocate shadow area for Win64
2315   if (IsWin64) {
2316     CCInfo.AllocateStack(32, 8);
2317   }
2318
2319   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2320
2321   // Get a count of how many bytes are to be pushed on the stack.
2322   unsigned NumBytes = CCInfo.getNextStackOffset();
2323   if (IsSibcall)
2324     // This is a sibcall. The memory operands are available in caller's
2325     // own caller's stack.
2326     NumBytes = 0;
2327   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2328            IsTailCallConvention(CallConv))
2329     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2330
2331   int FPDiff = 0;
2332   if (isTailCall && !IsSibcall) {
2333     // Lower arguments at fp - stackoffset + fpdiff.
2334     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2335     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2336
2337     FPDiff = NumBytesCallerPushed - NumBytes;
2338
2339     // Set the delta of movement of the returnaddr stackslot.
2340     // But only set if delta is greater than previous delta.
2341     if (FPDiff < X86Info->getTCReturnAddrDelta())
2342       X86Info->setTCReturnAddrDelta(FPDiff);
2343   }
2344
2345   if (!IsSibcall)
2346     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2347
2348   SDValue RetAddrFrIdx;
2349   // Load return address for tail calls.
2350   if (isTailCall && FPDiff)
2351     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2352                                     Is64Bit, FPDiff, dl);
2353
2354   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2355   SmallVector<SDValue, 8> MemOpChains;
2356   SDValue StackPtr;
2357
2358   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2359   // of tail call optimization arguments are handle later.
2360   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2361     CCValAssign &VA = ArgLocs[i];
2362     EVT RegVT = VA.getLocVT();
2363     SDValue Arg = OutVals[i];
2364     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2365     bool isByVal = Flags.isByVal();
2366
2367     // Promote the value if needed.
2368     switch (VA.getLocInfo()) {
2369     default: llvm_unreachable("Unknown loc info!");
2370     case CCValAssign::Full: break;
2371     case CCValAssign::SExt:
2372       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2373       break;
2374     case CCValAssign::ZExt:
2375       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2376       break;
2377     case CCValAssign::AExt:
2378       if (RegVT.is128BitVector()) {
2379         // Special case: passing MMX values in XMM registers.
2380         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2381         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2382         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2383       } else
2384         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2385       break;
2386     case CCValAssign::BCvt:
2387       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2388       break;
2389     case CCValAssign::Indirect: {
2390       // Store the argument.
2391       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2392       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2393       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2394                            MachinePointerInfo::getFixedStack(FI),
2395                            false, false, 0);
2396       Arg = SpillSlot;
2397       break;
2398     }
2399     }
2400
2401     if (VA.isRegLoc()) {
2402       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2403       if (isVarArg && IsWin64) {
2404         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2405         // shadow reg if callee is a varargs function.
2406         unsigned ShadowReg = 0;
2407         switch (VA.getLocReg()) {
2408         case X86::XMM0: ShadowReg = X86::RCX; break;
2409         case X86::XMM1: ShadowReg = X86::RDX; break;
2410         case X86::XMM2: ShadowReg = X86::R8; break;
2411         case X86::XMM3: ShadowReg = X86::R9; break;
2412         }
2413         if (ShadowReg)
2414           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2415       }
2416     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2417       assert(VA.isMemLoc());
2418       if (StackPtr.getNode() == 0)
2419         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2420                                       getPointerTy());
2421       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2422                                              dl, DAG, VA, Flags));
2423     }
2424   }
2425
2426   if (!MemOpChains.empty())
2427     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2428                         &MemOpChains[0], MemOpChains.size());
2429
2430   if (Subtarget->isPICStyleGOT()) {
2431     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2432     // GOT pointer.
2433     if (!isTailCall) {
2434       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2435                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2436     } else {
2437       // If we are tail calling and generating PIC/GOT style code load the
2438       // address of the callee into ECX. The value in ecx is used as target of
2439       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2440       // for tail calls on PIC/GOT architectures. Normally we would just put the
2441       // address of GOT into ebx and then call target@PLT. But for tail calls
2442       // ebx would be restored (since ebx is callee saved) before jumping to the
2443       // target@PLT.
2444
2445       // Note: The actual moving to ECX is done further down.
2446       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2447       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2448           !G->getGlobal()->hasProtectedVisibility())
2449         Callee = LowerGlobalAddress(Callee, DAG);
2450       else if (isa<ExternalSymbolSDNode>(Callee))
2451         Callee = LowerExternalSymbol(Callee, DAG);
2452     }
2453   }
2454
2455   if (Is64Bit && isVarArg && !IsWin64) {
2456     // From AMD64 ABI document:
2457     // For calls that may call functions that use varargs or stdargs
2458     // (prototype-less calls or calls to functions containing ellipsis (...) in
2459     // the declaration) %al is used as hidden argument to specify the number
2460     // of SSE registers used. The contents of %al do not need to match exactly
2461     // the number of registers, but must be an ubound on the number of SSE
2462     // registers used and is in the range 0 - 8 inclusive.
2463
2464     // Count the number of XMM registers allocated.
2465     static const uint16_t XMMArgRegs[] = {
2466       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2467       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2468     };
2469     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2470     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2471            && "SSE registers cannot be used when SSE is disabled");
2472
2473     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2474                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2475   }
2476
2477   // For tail calls lower the arguments to the 'real' stack slot.
2478   if (isTailCall) {
2479     // Force all the incoming stack arguments to be loaded from the stack
2480     // before any new outgoing arguments are stored to the stack, because the
2481     // outgoing stack slots may alias the incoming argument stack slots, and
2482     // the alias isn't otherwise explicit. This is slightly more conservative
2483     // than necessary, because it means that each store effectively depends
2484     // on every argument instead of just those arguments it would clobber.
2485     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2486
2487     SmallVector<SDValue, 8> MemOpChains2;
2488     SDValue FIN;
2489     int FI = 0;
2490     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2491       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2492         CCValAssign &VA = ArgLocs[i];
2493         if (VA.isRegLoc())
2494           continue;
2495         assert(VA.isMemLoc());
2496         SDValue Arg = OutVals[i];
2497         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2498         // Create frame index.
2499         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2500         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2501         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2502         FIN = DAG.getFrameIndex(FI, getPointerTy());
2503
2504         if (Flags.isByVal()) {
2505           // Copy relative to framepointer.
2506           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2507           if (StackPtr.getNode() == 0)
2508             StackPtr = DAG.getCopyFromReg(Chain, dl,
2509                                           RegInfo->getStackRegister(),
2510                                           getPointerTy());
2511           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2512
2513           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2514                                                            ArgChain,
2515                                                            Flags, DAG, dl));
2516         } else {
2517           // Store relative to framepointer.
2518           MemOpChains2.push_back(
2519             DAG.getStore(ArgChain, dl, Arg, FIN,
2520                          MachinePointerInfo::getFixedStack(FI),
2521                          false, false, 0));
2522         }
2523       }
2524     }
2525
2526     if (!MemOpChains2.empty())
2527       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2528                           &MemOpChains2[0], MemOpChains2.size());
2529
2530     // Store the return address to the appropriate stack slot.
2531     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2532                                      getPointerTy(), RegInfo->getSlotSize(),
2533                                      FPDiff, dl);
2534   }
2535
2536   // Build a sequence of copy-to-reg nodes chained together with token chain
2537   // and flag operands which copy the outgoing args into registers.
2538   SDValue InFlag;
2539   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2540     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2541                              RegsToPass[i].second, InFlag);
2542     InFlag = Chain.getValue(1);
2543   }
2544
2545   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2546     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2547     // In the 64-bit large code model, we have to make all calls
2548     // through a register, since the call instruction's 32-bit
2549     // pc-relative offset may not be large enough to hold the whole
2550     // address.
2551   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2552     // If the callee is a GlobalAddress node (quite common, every direct call
2553     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2554     // it.
2555
2556     // We should use extra load for direct calls to dllimported functions in
2557     // non-JIT mode.
2558     const GlobalValue *GV = G->getGlobal();
2559     if (!GV->hasDLLImportLinkage()) {
2560       unsigned char OpFlags = 0;
2561       bool ExtraLoad = false;
2562       unsigned WrapperKind = ISD::DELETED_NODE;
2563
2564       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2565       // external symbols most go through the PLT in PIC mode.  If the symbol
2566       // has hidden or protected visibility, or if it is static or local, then
2567       // we don't need to use the PLT - we can directly call it.
2568       if (Subtarget->isTargetELF() &&
2569           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2570           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2571         OpFlags = X86II::MO_PLT;
2572       } else if (Subtarget->isPICStyleStubAny() &&
2573                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
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       } else if (Subtarget->isPICStyleRIPRel() &&
2581                  isa<Function>(GV) &&
2582                  cast<Function>(GV)->getAttributes().
2583                    hasAttribute(AttributeSet::FunctionIndex,
2584                                 Attribute::NonLazyBind)) {
2585         // If the function is marked as non-lazy, generate an indirect call
2586         // which loads from the GOT directly. This avoids runtime overhead
2587         // at the cost of eager binding (and one extra byte of encoding).
2588         OpFlags = X86II::MO_GOTPCREL;
2589         WrapperKind = X86ISD::WrapperRIP;
2590         ExtraLoad = true;
2591       }
2592
2593       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2594                                           G->getOffset(), OpFlags);
2595
2596       // Add a wrapper if needed.
2597       if (WrapperKind != ISD::DELETED_NODE)
2598         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2599       // Add extra indirection if needed.
2600       if (ExtraLoad)
2601         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2602                              MachinePointerInfo::getGOT(),
2603                              false, false, false, 0);
2604     }
2605   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2606     unsigned char OpFlags = 0;
2607
2608     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2609     // external symbols should go through the PLT.
2610     if (Subtarget->isTargetELF() &&
2611         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2612       OpFlags = X86II::MO_PLT;
2613     } else if (Subtarget->isPICStyleStubAny() &&
2614                (!Subtarget->getTargetTriple().isMacOSX() ||
2615                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2616       // PC-relative references to external symbols should go through $stub,
2617       // unless we're building with the leopard linker or later, which
2618       // automatically synthesizes these stubs.
2619       OpFlags = X86II::MO_DARWIN_STUB;
2620     }
2621
2622     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2623                                          OpFlags);
2624   }
2625
2626   // Returns a chain & a flag for retval copy to use.
2627   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2628   SmallVector<SDValue, 8> Ops;
2629
2630   if (!IsSibcall && isTailCall) {
2631     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2632                            DAG.getIntPtrConstant(0, true), InFlag);
2633     InFlag = Chain.getValue(1);
2634   }
2635
2636   Ops.push_back(Chain);
2637   Ops.push_back(Callee);
2638
2639   if (isTailCall)
2640     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2641
2642   // Add argument registers to the end of the list so that they are known live
2643   // into the call.
2644   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2645     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2646                                   RegsToPass[i].second.getValueType()));
2647
2648   // Add a register mask operand representing the call-preserved registers.
2649   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2650   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2651   assert(Mask && "Missing call preserved mask for calling convention");
2652   Ops.push_back(DAG.getRegisterMask(Mask));
2653
2654   if (InFlag.getNode())
2655     Ops.push_back(InFlag);
2656
2657   if (isTailCall) {
2658     // We used to do:
2659     //// If this is the first return lowered for this function, add the regs
2660     //// to the liveout set for the function.
2661     // This isn't right, although it's probably harmless on x86; liveouts
2662     // should be computed from returns not tail calls.  Consider a void
2663     // function making a tail call to a function returning int.
2664     return DAG.getNode(X86ISD::TC_RETURN, dl,
2665                        NodeTys, &Ops[0], Ops.size());
2666   }
2667
2668   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2669   InFlag = Chain.getValue(1);
2670
2671   // Create the CALLSEQ_END node.
2672   unsigned NumBytesForCalleeToPush;
2673   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2674                        getTargetMachine().Options.GuaranteedTailCallOpt))
2675     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2676   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2677            SR == StackStructReturn)
2678     // If this is a call to a struct-return function, the callee
2679     // pops the hidden struct pointer, so we have to push it back.
2680     // This is common for Darwin/X86, Linux & Mingw32 targets.
2681     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2682     NumBytesForCalleeToPush = 4;
2683   else
2684     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2685
2686   // Returns a flag for retval copy to use.
2687   if (!IsSibcall) {
2688     Chain = DAG.getCALLSEQ_END(Chain,
2689                                DAG.getIntPtrConstant(NumBytes, true),
2690                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2691                                                      true),
2692                                InFlag);
2693     InFlag = Chain.getValue(1);
2694   }
2695
2696   // Handle result values, copying them out of physregs into vregs that we
2697   // return.
2698   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2699                          Ins, dl, DAG, InVals);
2700 }
2701
2702 //===----------------------------------------------------------------------===//
2703 //                Fast Calling Convention (tail call) implementation
2704 //===----------------------------------------------------------------------===//
2705
2706 //  Like std call, callee cleans arguments, convention except that ECX is
2707 //  reserved for storing the tail called function address. Only 2 registers are
2708 //  free for argument passing (inreg). Tail call optimization is performed
2709 //  provided:
2710 //                * tailcallopt is enabled
2711 //                * caller/callee are fastcc
2712 //  On X86_64 architecture with GOT-style position independent code only local
2713 //  (within module) calls are supported at the moment.
2714 //  To keep the stack aligned according to platform abi the function
2715 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2716 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2717 //  If a tail called function callee has more arguments than the caller the
2718 //  caller needs to make sure that there is room to move the RETADDR to. This is
2719 //  achieved by reserving an area the size of the argument delta right after the
2720 //  original REtADDR, but before the saved framepointer or the spilled registers
2721 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2722 //  stack layout:
2723 //    arg1
2724 //    arg2
2725 //    RETADDR
2726 //    [ new RETADDR
2727 //      move area ]
2728 //    (possible EBP)
2729 //    ESI
2730 //    EDI
2731 //    local1 ..
2732
2733 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2734 /// for a 16 byte align requirement.
2735 unsigned
2736 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2737                                                SelectionDAG& DAG) const {
2738   MachineFunction &MF = DAG.getMachineFunction();
2739   const TargetMachine &TM = MF.getTarget();
2740   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2741   unsigned StackAlignment = TFI.getStackAlignment();
2742   uint64_t AlignMask = StackAlignment - 1;
2743   int64_t Offset = StackSize;
2744   unsigned SlotSize = RegInfo->getSlotSize();
2745   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2746     // Number smaller than 12 so just add the difference.
2747     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2748   } else {
2749     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2750     Offset = ((~AlignMask) & Offset) + StackAlignment +
2751       (StackAlignment-SlotSize);
2752   }
2753   return Offset;
2754 }
2755
2756 /// MatchingStackOffset - Return true if the given stack call argument is
2757 /// already available in the same position (relatively) of the caller's
2758 /// incoming argument stack.
2759 static
2760 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2761                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2762                          const X86InstrInfo *TII) {
2763   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2764   int FI = INT_MAX;
2765   if (Arg.getOpcode() == ISD::CopyFromReg) {
2766     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2767     if (!TargetRegisterInfo::isVirtualRegister(VR))
2768       return false;
2769     MachineInstr *Def = MRI->getVRegDef(VR);
2770     if (!Def)
2771       return false;
2772     if (!Flags.isByVal()) {
2773       if (!TII->isLoadFromStackSlot(Def, FI))
2774         return false;
2775     } else {
2776       unsigned Opcode = Def->getOpcode();
2777       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2778           Def->getOperand(1).isFI()) {
2779         FI = Def->getOperand(1).getIndex();
2780         Bytes = Flags.getByValSize();
2781       } else
2782         return false;
2783     }
2784   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2785     if (Flags.isByVal())
2786       // ByVal argument is passed in as a pointer but it's now being
2787       // dereferenced. e.g.
2788       // define @foo(%struct.X* %A) {
2789       //   tail call @bar(%struct.X* byval %A)
2790       // }
2791       return false;
2792     SDValue Ptr = Ld->getBasePtr();
2793     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2794     if (!FINode)
2795       return false;
2796     FI = FINode->getIndex();
2797   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2798     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2799     FI = FINode->getIndex();
2800     Bytes = Flags.getByValSize();
2801   } else
2802     return false;
2803
2804   assert(FI != INT_MAX);
2805   if (!MFI->isFixedObjectIndex(FI))
2806     return false;
2807   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2808 }
2809
2810 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2811 /// for tail call optimization. Targets which want to do tail call
2812 /// optimization should implement this function.
2813 bool
2814 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2815                                                      CallingConv::ID CalleeCC,
2816                                                      bool isVarArg,
2817                                                      bool isCalleeStructRet,
2818                                                      bool isCallerStructRet,
2819                                                      Type *RetTy,
2820                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2821                                     const SmallVectorImpl<SDValue> &OutVals,
2822                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2823                                                      SelectionDAG& DAG) const {
2824   if (!IsTailCallConvention(CalleeCC) &&
2825       CalleeCC != CallingConv::C)
2826     return false;
2827
2828   // If -tailcallopt is specified, make fastcc functions tail-callable.
2829   const MachineFunction &MF = DAG.getMachineFunction();
2830   const Function *CallerF = DAG.getMachineFunction().getFunction();
2831
2832   // If the function return type is x86_fp80 and the callee return type is not,
2833   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2834   // perform a tailcall optimization here.
2835   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2836     return false;
2837
2838   CallingConv::ID CallerCC = CallerF->getCallingConv();
2839   bool CCMatch = CallerCC == CalleeCC;
2840
2841   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2842     if (IsTailCallConvention(CalleeCC) && CCMatch)
2843       return true;
2844     return false;
2845   }
2846
2847   // Look for obvious safe cases to perform tail call optimization that do not
2848   // require ABI changes. This is what gcc calls sibcall.
2849
2850   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2851   // emit a special epilogue.
2852   if (RegInfo->needsStackRealignment(MF))
2853     return false;
2854
2855   // Also avoid sibcall optimization if either caller or callee uses struct
2856   // return semantics.
2857   if (isCalleeStructRet || isCallerStructRet)
2858     return false;
2859
2860   // An stdcall caller is expected to clean up its arguments; the callee
2861   // isn't going to do that.
2862   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2863     return false;
2864
2865   // Do not sibcall optimize vararg calls unless all arguments are passed via
2866   // registers.
2867   if (isVarArg && !Outs.empty()) {
2868
2869     // Optimizing for varargs on Win64 is unlikely to be safe without
2870     // additional testing.
2871     if (Subtarget->isTargetWin64())
2872       return false;
2873
2874     SmallVector<CCValAssign, 16> ArgLocs;
2875     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2876                    getTargetMachine(), ArgLocs, *DAG.getContext());
2877
2878     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2879     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2880       if (!ArgLocs[i].isRegLoc())
2881         return false;
2882   }
2883
2884   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2885   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2886   // this into a sibcall.
2887   bool Unused = false;
2888   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2889     if (!Ins[i].Used) {
2890       Unused = true;
2891       break;
2892     }
2893   }
2894   if (Unused) {
2895     SmallVector<CCValAssign, 16> RVLocs;
2896     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2897                    getTargetMachine(), RVLocs, *DAG.getContext());
2898     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2899     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2900       CCValAssign &VA = RVLocs[i];
2901       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2902         return false;
2903     }
2904   }
2905
2906   // If the calling conventions do not match, then we'd better make sure the
2907   // results are returned in the same way as what the caller expects.
2908   if (!CCMatch) {
2909     SmallVector<CCValAssign, 16> RVLocs1;
2910     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2911                     getTargetMachine(), RVLocs1, *DAG.getContext());
2912     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2913
2914     SmallVector<CCValAssign, 16> RVLocs2;
2915     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2916                     getTargetMachine(), RVLocs2, *DAG.getContext());
2917     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2918
2919     if (RVLocs1.size() != RVLocs2.size())
2920       return false;
2921     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2922       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2923         return false;
2924       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2925         return false;
2926       if (RVLocs1[i].isRegLoc()) {
2927         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2928           return false;
2929       } else {
2930         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2931           return false;
2932       }
2933     }
2934   }
2935
2936   // If the callee takes no arguments then go on to check the results of the
2937   // call.
2938   if (!Outs.empty()) {
2939     // Check if stack adjustment is needed. For now, do not do this if any
2940     // argument is passed on the stack.
2941     SmallVector<CCValAssign, 16> ArgLocs;
2942     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2943                    getTargetMachine(), ArgLocs, *DAG.getContext());
2944
2945     // Allocate shadow area for Win64
2946     if (Subtarget->isTargetWin64()) {
2947       CCInfo.AllocateStack(32, 8);
2948     }
2949
2950     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2951     if (CCInfo.getNextStackOffset()) {
2952       MachineFunction &MF = DAG.getMachineFunction();
2953       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2954         return false;
2955
2956       // Check if the arguments are already laid out in the right way as
2957       // the caller's fixed stack objects.
2958       MachineFrameInfo *MFI = MF.getFrameInfo();
2959       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2960       const X86InstrInfo *TII =
2961         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2962       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2963         CCValAssign &VA = ArgLocs[i];
2964         SDValue Arg = OutVals[i];
2965         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2966         if (VA.getLocInfo() == CCValAssign::Indirect)
2967           return false;
2968         if (!VA.isRegLoc()) {
2969           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2970                                    MFI, MRI, TII))
2971             return false;
2972         }
2973       }
2974     }
2975
2976     // If the tailcall address may be in a register, then make sure it's
2977     // possible to register allocate for it. In 32-bit, the call address can
2978     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2979     // callee-saved registers are restored. These happen to be the same
2980     // registers used to pass 'inreg' arguments so watch out for those.
2981     if (!Subtarget->is64Bit() &&
2982         !isa<GlobalAddressSDNode>(Callee) &&
2983         !isa<ExternalSymbolSDNode>(Callee)) {
2984       unsigned NumInRegs = 0;
2985       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2986         CCValAssign &VA = ArgLocs[i];
2987         if (!VA.isRegLoc())
2988           continue;
2989         unsigned Reg = VA.getLocReg();
2990         switch (Reg) {
2991         default: break;
2992         case X86::EAX: case X86::EDX: case X86::ECX:
2993           if (++NumInRegs == 3)
2994             return false;
2995           break;
2996         }
2997       }
2998     }
2999   }
3000
3001   return true;
3002 }
3003
3004 FastISel *
3005 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3006                                   const TargetLibraryInfo *libInfo) const {
3007   return X86::createFastISel(funcInfo, libInfo);
3008 }
3009
3010 //===----------------------------------------------------------------------===//
3011 //                           Other Lowering Hooks
3012 //===----------------------------------------------------------------------===//
3013
3014 static bool MayFoldLoad(SDValue Op) {
3015   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3016 }
3017
3018 static bool MayFoldIntoStore(SDValue Op) {
3019   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3020 }
3021
3022 static bool isTargetShuffle(unsigned Opcode) {
3023   switch(Opcode) {
3024   default: return false;
3025   case X86ISD::PSHUFD:
3026   case X86ISD::PSHUFHW:
3027   case X86ISD::PSHUFLW:
3028   case X86ISD::SHUFP:
3029   case X86ISD::PALIGNR:
3030   case X86ISD::MOVLHPS:
3031   case X86ISD::MOVLHPD:
3032   case X86ISD::MOVHLPS:
3033   case X86ISD::MOVLPS:
3034   case X86ISD::MOVLPD:
3035   case X86ISD::MOVSHDUP:
3036   case X86ISD::MOVSLDUP:
3037   case X86ISD::MOVDDUP:
3038   case X86ISD::MOVSS:
3039   case X86ISD::MOVSD:
3040   case X86ISD::UNPCKL:
3041   case X86ISD::UNPCKH:
3042   case X86ISD::VPERMILP:
3043   case X86ISD::VPERM2X128:
3044   case X86ISD::VPERMI:
3045     return true;
3046   }
3047 }
3048
3049 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3050                                     SDValue V1, SelectionDAG &DAG) {
3051   switch(Opc) {
3052   default: llvm_unreachable("Unknown x86 shuffle node");
3053   case X86ISD::MOVSHDUP:
3054   case X86ISD::MOVSLDUP:
3055   case X86ISD::MOVDDUP:
3056     return DAG.getNode(Opc, dl, VT, V1);
3057   }
3058 }
3059
3060 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3061                                     SDValue V1, unsigned TargetMask,
3062                                     SelectionDAG &DAG) {
3063   switch(Opc) {
3064   default: llvm_unreachable("Unknown x86 shuffle node");
3065   case X86ISD::PSHUFD:
3066   case X86ISD::PSHUFHW:
3067   case X86ISD::PSHUFLW:
3068   case X86ISD::VPERMILP:
3069   case X86ISD::VPERMI:
3070     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3071   }
3072 }
3073
3074 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3075                                     SDValue V1, SDValue V2, unsigned TargetMask,
3076                                     SelectionDAG &DAG) {
3077   switch(Opc) {
3078   default: llvm_unreachable("Unknown x86 shuffle node");
3079   case X86ISD::PALIGNR:
3080   case X86ISD::SHUFP:
3081   case X86ISD::VPERM2X128:
3082     return DAG.getNode(Opc, dl, VT, V1, V2,
3083                        DAG.getConstant(TargetMask, MVT::i8));
3084   }
3085 }
3086
3087 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3088                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3089   switch(Opc) {
3090   default: llvm_unreachable("Unknown x86 shuffle node");
3091   case X86ISD::MOVLHPS:
3092   case X86ISD::MOVLHPD:
3093   case X86ISD::MOVHLPS:
3094   case X86ISD::MOVLPS:
3095   case X86ISD::MOVLPD:
3096   case X86ISD::MOVSS:
3097   case X86ISD::MOVSD:
3098   case X86ISD::UNPCKL:
3099   case X86ISD::UNPCKH:
3100     return DAG.getNode(Opc, dl, VT, V1, V2);
3101   }
3102 }
3103
3104 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3105   MachineFunction &MF = DAG.getMachineFunction();
3106   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3107   int ReturnAddrIndex = FuncInfo->getRAIndex();
3108
3109   if (ReturnAddrIndex == 0) {
3110     // Set up a frame object for the return address.
3111     unsigned SlotSize = RegInfo->getSlotSize();
3112     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3113                                                            false);
3114     FuncInfo->setRAIndex(ReturnAddrIndex);
3115   }
3116
3117   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3118 }
3119
3120 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3121                                        bool hasSymbolicDisplacement) {
3122   // Offset should fit into 32 bit immediate field.
3123   if (!isInt<32>(Offset))
3124     return false;
3125
3126   // If we don't have a symbolic displacement - we don't have any extra
3127   // restrictions.
3128   if (!hasSymbolicDisplacement)
3129     return true;
3130
3131   // FIXME: Some tweaks might be needed for medium code model.
3132   if (M != CodeModel::Small && M != CodeModel::Kernel)
3133     return false;
3134
3135   // For small code model we assume that latest object is 16MB before end of 31
3136   // bits boundary. We may also accept pretty large negative constants knowing
3137   // that all objects are in the positive half of address space.
3138   if (M == CodeModel::Small && Offset < 16*1024*1024)
3139     return true;
3140
3141   // For kernel code model we know that all object resist in the negative half
3142   // of 32bits address space. We may not accept negative offsets, since they may
3143   // be just off and we may accept pretty large positive ones.
3144   if (M == CodeModel::Kernel && Offset > 0)
3145     return true;
3146
3147   return false;
3148 }
3149
3150 /// isCalleePop - Determines whether the callee is required to pop its
3151 /// own arguments. Callee pop is necessary to support tail calls.
3152 bool X86::isCalleePop(CallingConv::ID CallingConv,
3153                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3154   if (IsVarArg)
3155     return false;
3156
3157   switch (CallingConv) {
3158   default:
3159     return false;
3160   case CallingConv::X86_StdCall:
3161     return !is64Bit;
3162   case CallingConv::X86_FastCall:
3163     return !is64Bit;
3164   case CallingConv::X86_ThisCall:
3165     return !is64Bit;
3166   case CallingConv::Fast:
3167     return TailCallOpt;
3168   case CallingConv::GHC:
3169     return TailCallOpt;
3170   case CallingConv::HiPE:
3171     return TailCallOpt;
3172   }
3173 }
3174
3175 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3176 /// specific condition code, returning the condition code and the LHS/RHS of the
3177 /// comparison to make.
3178 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3179                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3180   if (!isFP) {
3181     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3182       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3183         // X > -1   -> X == 0, jump !sign.
3184         RHS = DAG.getConstant(0, RHS.getValueType());
3185         return X86::COND_NS;
3186       }
3187       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3188         // X < 0   -> X == 0, jump on sign.
3189         return X86::COND_S;
3190       }
3191       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3192         // X < 1   -> X <= 0
3193         RHS = DAG.getConstant(0, RHS.getValueType());
3194         return X86::COND_LE;
3195       }
3196     }
3197
3198     switch (SetCCOpcode) {
3199     default: llvm_unreachable("Invalid integer condition!");
3200     case ISD::SETEQ:  return X86::COND_E;
3201     case ISD::SETGT:  return X86::COND_G;
3202     case ISD::SETGE:  return X86::COND_GE;
3203     case ISD::SETLT:  return X86::COND_L;
3204     case ISD::SETLE:  return X86::COND_LE;
3205     case ISD::SETNE:  return X86::COND_NE;
3206     case ISD::SETULT: return X86::COND_B;
3207     case ISD::SETUGT: return X86::COND_A;
3208     case ISD::SETULE: return X86::COND_BE;
3209     case ISD::SETUGE: return X86::COND_AE;
3210     }
3211   }
3212
3213   // First determine if it is required or is profitable to flip the operands.
3214
3215   // If LHS is a foldable load, but RHS is not, flip the condition.
3216   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3217       !ISD::isNON_EXTLoad(RHS.getNode())) {
3218     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3219     std::swap(LHS, RHS);
3220   }
3221
3222   switch (SetCCOpcode) {
3223   default: break;
3224   case ISD::SETOLT:
3225   case ISD::SETOLE:
3226   case ISD::SETUGT:
3227   case ISD::SETUGE:
3228     std::swap(LHS, RHS);
3229     break;
3230   }
3231
3232   // On a floating point condition, the flags are set as follows:
3233   // ZF  PF  CF   op
3234   //  0 | 0 | 0 | X > Y
3235   //  0 | 0 | 1 | X < Y
3236   //  1 | 0 | 0 | X == Y
3237   //  1 | 1 | 1 | unordered
3238   switch (SetCCOpcode) {
3239   default: llvm_unreachable("Condcode should be pre-legalized away");
3240   case ISD::SETUEQ:
3241   case ISD::SETEQ:   return X86::COND_E;
3242   case ISD::SETOLT:              // flipped
3243   case ISD::SETOGT:
3244   case ISD::SETGT:   return X86::COND_A;
3245   case ISD::SETOLE:              // flipped
3246   case ISD::SETOGE:
3247   case ISD::SETGE:   return X86::COND_AE;
3248   case ISD::SETUGT:              // flipped
3249   case ISD::SETULT:
3250   case ISD::SETLT:   return X86::COND_B;
3251   case ISD::SETUGE:              // flipped
3252   case ISD::SETULE:
3253   case ISD::SETLE:   return X86::COND_BE;
3254   case ISD::SETONE:
3255   case ISD::SETNE:   return X86::COND_NE;
3256   case ISD::SETUO:   return X86::COND_P;
3257   case ISD::SETO:    return X86::COND_NP;
3258   case ISD::SETOEQ:
3259   case ISD::SETUNE:  return X86::COND_INVALID;
3260   }
3261 }
3262
3263 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3264 /// code. Current x86 isa includes the following FP cmov instructions:
3265 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3266 static bool hasFPCMov(unsigned X86CC) {
3267   switch (X86CC) {
3268   default:
3269     return false;
3270   case X86::COND_B:
3271   case X86::COND_BE:
3272   case X86::COND_E:
3273   case X86::COND_P:
3274   case X86::COND_A:
3275   case X86::COND_AE:
3276   case X86::COND_NE:
3277   case X86::COND_NP:
3278     return true;
3279   }
3280 }
3281
3282 /// isFPImmLegal - Returns true if the target can instruction select the
3283 /// specified FP immediate natively. If false, the legalizer will
3284 /// materialize the FP immediate as a load from a constant pool.
3285 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3286   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3287     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3288       return true;
3289   }
3290   return false;
3291 }
3292
3293 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3294 /// the specified range (L, H].
3295 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3296   return (Val < 0) || (Val >= Low && Val < Hi);
3297 }
3298
3299 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3300 /// specified value.
3301 static bool isUndefOrEqual(int Val, int CmpVal) {
3302   return (Val < 0 || Val == CmpVal);
3303 }
3304
3305 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3306 /// from position Pos and ending in Pos+Size, falls within the specified
3307 /// sequential range (L, L+Pos]. or is undef.
3308 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3309                                        unsigned Pos, unsigned Size, int Low) {
3310   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3311     if (!isUndefOrEqual(Mask[i], Low))
3312       return false;
3313   return true;
3314 }
3315
3316 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3318 /// the second operand.
3319 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3320   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3321     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3322   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3323     return (Mask[0] < 2 && Mask[1] < 2);
3324   return false;
3325 }
3326
3327 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3328 /// is suitable for input to PSHUFHW.
3329 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3330   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3331     return false;
3332
3333   // Lower quadword copied in order or undef.
3334   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3335     return false;
3336
3337   // Upper quadword shuffled.
3338   for (unsigned i = 4; i != 8; ++i)
3339     if (!isUndefOrInRange(Mask[i], 4, 8))
3340       return false;
3341
3342   if (VT == MVT::v16i16) {
3343     // Lower quadword copied in order or undef.
3344     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3345       return false;
3346
3347     // Upper quadword shuffled.
3348     for (unsigned i = 12; i != 16; ++i)
3349       if (!isUndefOrInRange(Mask[i], 12, 16))
3350         return false;
3351   }
3352
3353   return true;
3354 }
3355
3356 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3357 /// is suitable for input to PSHUFLW.
3358 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3359   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3360     return false;
3361
3362   // Upper quadword copied in order.
3363   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3364     return false;
3365
3366   // Lower quadword shuffled.
3367   for (unsigned i = 0; i != 4; ++i)
3368     if (!isUndefOrInRange(Mask[i], 0, 4))
3369       return false;
3370
3371   if (VT == MVT::v16i16) {
3372     // Upper quadword copied in order.
3373     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3374       return false;
3375
3376     // Lower quadword shuffled.
3377     for (unsigned i = 8; i != 12; ++i)
3378       if (!isUndefOrInRange(Mask[i], 8, 12))
3379         return false;
3380   }
3381
3382   return true;
3383 }
3384
3385 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3386 /// is suitable for input to PALIGNR.
3387 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3388                           const X86Subtarget *Subtarget) {
3389   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3390       (VT.is256BitVector() && !Subtarget->hasInt256()))
3391     return false;
3392
3393   unsigned NumElts = VT.getVectorNumElements();
3394   unsigned NumLanes = VT.getSizeInBits()/128;
3395   unsigned NumLaneElts = NumElts/NumLanes;
3396
3397   // Do not handle 64-bit element shuffles with palignr.
3398   if (NumLaneElts == 2)
3399     return false;
3400
3401   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3402     unsigned i;
3403     for (i = 0; i != NumLaneElts; ++i) {
3404       if (Mask[i+l] >= 0)
3405         break;
3406     }
3407
3408     // Lane is all undef, go to next lane
3409     if (i == NumLaneElts)
3410       continue;
3411
3412     int Start = Mask[i+l];
3413
3414     // Make sure its in this lane in one of the sources
3415     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3416         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3417       return false;
3418
3419     // If not lane 0, then we must match lane 0
3420     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3421       return false;
3422
3423     // Correct second source to be contiguous with first source
3424     if (Start >= (int)NumElts)
3425       Start -= NumElts - NumLaneElts;
3426
3427     // Make sure we're shifting in the right direction.
3428     if (Start <= (int)(i+l))
3429       return false;
3430
3431     Start -= i;
3432
3433     // Check the rest of the elements to see if they are consecutive.
3434     for (++i; i != NumLaneElts; ++i) {
3435       int Idx = Mask[i+l];
3436
3437       // Make sure its in this lane
3438       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3439           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3440         return false;
3441
3442       // If not lane 0, then we must match lane 0
3443       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3444         return false;
3445
3446       if (Idx >= (int)NumElts)
3447         Idx -= NumElts - NumLaneElts;
3448
3449       if (!isUndefOrEqual(Idx, Start+i))
3450         return false;
3451
3452     }
3453   }
3454
3455   return true;
3456 }
3457
3458 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3459 /// the two vector operands have swapped position.
3460 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3461                                      unsigned NumElems) {
3462   for (unsigned i = 0; i != NumElems; ++i) {
3463     int idx = Mask[i];
3464     if (idx < 0)
3465       continue;
3466     else if (idx < (int)NumElems)
3467       Mask[i] = idx + NumElems;
3468     else
3469       Mask[i] = idx - NumElems;
3470   }
3471 }
3472
3473 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3474 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3475 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3476 /// reverse of what x86 shuffles want.
3477 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3478                         bool Commuted = false) {
3479   if (!HasFp256 && VT.is256BitVector())
3480     return false;
3481
3482   unsigned NumElems = VT.getVectorNumElements();
3483   unsigned NumLanes = VT.getSizeInBits()/128;
3484   unsigned NumLaneElems = NumElems/NumLanes;
3485
3486   if (NumLaneElems != 2 && NumLaneElems != 4)
3487     return false;
3488
3489   // VSHUFPSY divides the resulting vector into 4 chunks.
3490   // The sources are also splitted into 4 chunks, and each destination
3491   // chunk must come from a different source chunk.
3492   //
3493   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3494   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3495   //
3496   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3497   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3498   //
3499   // VSHUFPDY divides the resulting vector into 4 chunks.
3500   // The sources are also splitted into 4 chunks, and each destination
3501   // chunk must come from a different source chunk.
3502   //
3503   //  SRC1 =>      X3       X2       X1       X0
3504   //  SRC2 =>      Y3       Y2       Y1       Y0
3505   //
3506   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3507   //
3508   unsigned HalfLaneElems = NumLaneElems/2;
3509   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3510     for (unsigned i = 0; i != NumLaneElems; ++i) {
3511       int Idx = Mask[i+l];
3512       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3513       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3514         return false;
3515       // For VSHUFPSY, the mask of the second half must be the same as the
3516       // first but with the appropriate offsets. This works in the same way as
3517       // VPERMILPS works with masks.
3518       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3519         continue;
3520       if (!isUndefOrEqual(Idx, Mask[i]+l))
3521         return false;
3522     }
3523   }
3524
3525   return true;
3526 }
3527
3528 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3529 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3530 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3531   if (!VT.is128BitVector())
3532     return false;
3533
3534   unsigned NumElems = VT.getVectorNumElements();
3535
3536   if (NumElems != 4)
3537     return false;
3538
3539   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3540   return isUndefOrEqual(Mask[0], 6) &&
3541          isUndefOrEqual(Mask[1], 7) &&
3542          isUndefOrEqual(Mask[2], 2) &&
3543          isUndefOrEqual(Mask[3], 3);
3544 }
3545
3546 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3547 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3548 /// <2, 3, 2, 3>
3549 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3550   if (!VT.is128BitVector())
3551     return false;
3552
3553   unsigned NumElems = VT.getVectorNumElements();
3554
3555   if (NumElems != 4)
3556     return false;
3557
3558   return isUndefOrEqual(Mask[0], 2) &&
3559          isUndefOrEqual(Mask[1], 3) &&
3560          isUndefOrEqual(Mask[2], 2) &&
3561          isUndefOrEqual(Mask[3], 3);
3562 }
3563
3564 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3565 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3566 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3567   if (!VT.is128BitVector())
3568     return false;
3569
3570   unsigned NumElems = VT.getVectorNumElements();
3571
3572   if (NumElems != 2 && NumElems != 4)
3573     return false;
3574
3575   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3576     if (!isUndefOrEqual(Mask[i], i + NumElems))
3577       return false;
3578
3579   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3580     if (!isUndefOrEqual(Mask[i], i))
3581       return false;
3582
3583   return true;
3584 }
3585
3586 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3587 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3588 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3589   if (!VT.is128BitVector())
3590     return false;
3591
3592   unsigned NumElems = VT.getVectorNumElements();
3593
3594   if (NumElems != 2 && NumElems != 4)
3595     return false;
3596
3597   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3598     if (!isUndefOrEqual(Mask[i], i))
3599       return false;
3600
3601   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3602     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3603       return false;
3604
3605   return true;
3606 }
3607
3608 //
3609 // Some special combinations that can be optimized.
3610 //
3611 static
3612 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3613                                SelectionDAG &DAG) {
3614   MVT VT = SVOp->getValueType(0).getSimpleVT();
3615   DebugLoc dl = SVOp->getDebugLoc();
3616
3617   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3618     return SDValue();
3619
3620   ArrayRef<int> Mask = SVOp->getMask();
3621
3622   // These are the special masks that may be optimized.
3623   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3624   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3625   bool MatchEvenMask = true;
3626   bool MatchOddMask  = true;
3627   for (int i=0; i<8; ++i) {
3628     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3629       MatchEvenMask = false;
3630     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3631       MatchOddMask = false;
3632   }
3633
3634   if (!MatchEvenMask && !MatchOddMask)
3635     return SDValue();
3636
3637   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3638
3639   SDValue Op0 = SVOp->getOperand(0);
3640   SDValue Op1 = SVOp->getOperand(1);
3641
3642   if (MatchEvenMask) {
3643     // Shift the second operand right to 32 bits.
3644     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3645     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3646   } else {
3647     // Shift the first operand left to 32 bits.
3648     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3649     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3650   }
3651   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3652   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3653 }
3654
3655 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3656 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3657 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3658                          bool HasInt256, bool V2IsSplat = false) {
3659   unsigned NumElts = VT.getVectorNumElements();
3660
3661   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3662          "Unsupported vector type for unpckh");
3663
3664   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3665       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3666     return false;
3667
3668   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3669   // independently on 128-bit lanes.
3670   unsigned NumLanes = VT.getSizeInBits()/128;
3671   unsigned NumLaneElts = NumElts/NumLanes;
3672
3673   for (unsigned l = 0; l != NumLanes; ++l) {
3674     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3675          i != (l+1)*NumLaneElts;
3676          i += 2, ++j) {
3677       int BitI  = Mask[i];
3678       int BitI1 = Mask[i+1];
3679       if (!isUndefOrEqual(BitI, j))
3680         return false;
3681       if (V2IsSplat) {
3682         if (!isUndefOrEqual(BitI1, NumElts))
3683           return false;
3684       } else {
3685         if (!isUndefOrEqual(BitI1, j + NumElts))
3686           return false;
3687       }
3688     }
3689   }
3690
3691   return true;
3692 }
3693
3694 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3695 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3696 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3697                          bool HasInt256, bool V2IsSplat = false) {
3698   unsigned NumElts = VT.getVectorNumElements();
3699
3700   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3701          "Unsupported vector type for unpckh");
3702
3703   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3704       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3705     return false;
3706
3707   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3708   // independently on 128-bit lanes.
3709   unsigned NumLanes = VT.getSizeInBits()/128;
3710   unsigned NumLaneElts = NumElts/NumLanes;
3711
3712   for (unsigned l = 0; l != NumLanes; ++l) {
3713     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3714          i != (l+1)*NumLaneElts; i += 2, ++j) {
3715       int BitI  = Mask[i];
3716       int BitI1 = Mask[i+1];
3717       if (!isUndefOrEqual(BitI, j))
3718         return false;
3719       if (V2IsSplat) {
3720         if (isUndefOrEqual(BitI1, NumElts))
3721           return false;
3722       } else {
3723         if (!isUndefOrEqual(BitI1, j+NumElts))
3724           return false;
3725       }
3726     }
3727   }
3728   return true;
3729 }
3730
3731 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3732 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3733 /// <0, 0, 1, 1>
3734 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3735   unsigned NumElts = VT.getVectorNumElements();
3736   bool Is256BitVec = VT.is256BitVector();
3737
3738   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3739          "Unsupported vector type for unpckh");
3740
3741   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3742       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3743     return false;
3744
3745   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3746   // FIXME: Need a better way to get rid of this, there's no latency difference
3747   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3748   // the former later. We should also remove the "_undef" special mask.
3749   if (NumElts == 4 && Is256BitVec)
3750     return false;
3751
3752   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3753   // independently on 128-bit lanes.
3754   unsigned NumLanes = VT.getSizeInBits()/128;
3755   unsigned NumLaneElts = NumElts/NumLanes;
3756
3757   for (unsigned l = 0; l != NumLanes; ++l) {
3758     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3759          i != (l+1)*NumLaneElts;
3760          i += 2, ++j) {
3761       int BitI  = Mask[i];
3762       int BitI1 = Mask[i+1];
3763
3764       if (!isUndefOrEqual(BitI, j))
3765         return false;
3766       if (!isUndefOrEqual(BitI1, j))
3767         return false;
3768     }
3769   }
3770
3771   return true;
3772 }
3773
3774 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3775 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3776 /// <2, 2, 3, 3>
3777 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3778   unsigned NumElts = VT.getVectorNumElements();
3779
3780   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3781          "Unsupported vector type for unpckh");
3782
3783   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3784       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3785     return false;
3786
3787   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3788   // independently on 128-bit lanes.
3789   unsigned NumLanes = VT.getSizeInBits()/128;
3790   unsigned NumLaneElts = NumElts/NumLanes;
3791
3792   for (unsigned l = 0; l != NumLanes; ++l) {
3793     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3794          i != (l+1)*NumLaneElts; i += 2, ++j) {
3795       int BitI  = Mask[i];
3796       int BitI1 = Mask[i+1];
3797       if (!isUndefOrEqual(BitI, j))
3798         return false;
3799       if (!isUndefOrEqual(BitI1, j))
3800         return false;
3801     }
3802   }
3803   return true;
3804 }
3805
3806 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3807 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3808 /// MOVSD, and MOVD, i.e. setting the lowest element.
3809 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3810   if (VT.getVectorElementType().getSizeInBits() < 32)
3811     return false;
3812   if (!VT.is128BitVector())
3813     return false;
3814
3815   unsigned NumElts = VT.getVectorNumElements();
3816
3817   if (!isUndefOrEqual(Mask[0], NumElts))
3818     return false;
3819
3820   for (unsigned i = 1; i != NumElts; ++i)
3821     if (!isUndefOrEqual(Mask[i], i))
3822       return false;
3823
3824   return true;
3825 }
3826
3827 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3828 /// as permutations between 128-bit chunks or halves. As an example: this
3829 /// shuffle bellow:
3830 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3831 /// The first half comes from the second half of V1 and the second half from the
3832 /// the second half of V2.
3833 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3834   if (!HasFp256 || !VT.is256BitVector())
3835     return false;
3836
3837   // The shuffle result is divided into half A and half B. In total the two
3838   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3839   // B must come from C, D, E or F.
3840   unsigned HalfSize = VT.getVectorNumElements()/2;
3841   bool MatchA = false, MatchB = false;
3842
3843   // Check if A comes from one of C, D, E, F.
3844   for (unsigned Half = 0; Half != 4; ++Half) {
3845     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3846       MatchA = true;
3847       break;
3848     }
3849   }
3850
3851   // Check if B comes from one of C, D, E, F.
3852   for (unsigned Half = 0; Half != 4; ++Half) {
3853     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3854       MatchB = true;
3855       break;
3856     }
3857   }
3858
3859   return MatchA && MatchB;
3860 }
3861
3862 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3863 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3864 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3865   MVT VT = SVOp->getValueType(0).getSimpleVT();
3866
3867   unsigned HalfSize = VT.getVectorNumElements()/2;
3868
3869   unsigned FstHalf = 0, SndHalf = 0;
3870   for (unsigned i = 0; i < HalfSize; ++i) {
3871     if (SVOp->getMaskElt(i) > 0) {
3872       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3873       break;
3874     }
3875   }
3876   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3877     if (SVOp->getMaskElt(i) > 0) {
3878       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3879       break;
3880     }
3881   }
3882
3883   return (FstHalf | (SndHalf << 4));
3884 }
3885
3886 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3888 /// Note that VPERMIL mask matching is different depending whether theunderlying
3889 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3890 /// to the same elements of the low, but to the higher half of the source.
3891 /// In VPERMILPD the two lanes could be shuffled independently of each other
3892 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3893 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3894   if (!HasFp256)
3895     return false;
3896
3897   unsigned NumElts = VT.getVectorNumElements();
3898   // Only match 256-bit with 32/64-bit types
3899   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3900     return false;
3901
3902   unsigned NumLanes = VT.getSizeInBits()/128;
3903   unsigned LaneSize = NumElts/NumLanes;
3904   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3905     for (unsigned i = 0; i != LaneSize; ++i) {
3906       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3907         return false;
3908       if (NumElts != 8 || l == 0)
3909         continue;
3910       // VPERMILPS handling
3911       if (Mask[i] < 0)
3912         continue;
3913       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3914         return false;
3915     }
3916   }
3917
3918   return true;
3919 }
3920
3921 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3922 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3923 /// element of vector 2 and the other elements to come from vector 1 in order.
3924 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3925                                bool V2IsSplat = false, bool V2IsUndef = false) {
3926   if (!VT.is128BitVector())
3927     return false;
3928
3929   unsigned NumOps = VT.getVectorNumElements();
3930   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3931     return false;
3932
3933   if (!isUndefOrEqual(Mask[0], 0))
3934     return false;
3935
3936   for (unsigned i = 1; i != NumOps; ++i)
3937     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3938           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3939           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3940       return false;
3941
3942   return true;
3943 }
3944
3945 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3946 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3947 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3948 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3949                            const X86Subtarget *Subtarget) {
3950   if (!Subtarget->hasSSE3())
3951     return false;
3952
3953   unsigned NumElems = VT.getVectorNumElements();
3954
3955   if ((VT.is128BitVector() && NumElems != 4) ||
3956       (VT.is256BitVector() && NumElems != 8))
3957     return false;
3958
3959   // "i+1" is the value the indexed mask element must have
3960   for (unsigned i = 0; i != NumElems; i += 2)
3961     if (!isUndefOrEqual(Mask[i], i+1) ||
3962         !isUndefOrEqual(Mask[i+1], i+1))
3963       return false;
3964
3965   return true;
3966 }
3967
3968 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3969 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3970 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3971 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3972                            const X86Subtarget *Subtarget) {
3973   if (!Subtarget->hasSSE3())
3974     return false;
3975
3976   unsigned NumElems = VT.getVectorNumElements();
3977
3978   if ((VT.is128BitVector() && NumElems != 4) ||
3979       (VT.is256BitVector() && NumElems != 8))
3980     return false;
3981
3982   // "i" is the value the indexed mask element must have
3983   for (unsigned i = 0; i != NumElems; i += 2)
3984     if (!isUndefOrEqual(Mask[i], i) ||
3985         !isUndefOrEqual(Mask[i+1], i))
3986       return false;
3987
3988   return true;
3989 }
3990
3991 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3992 /// specifies a shuffle of elements that is suitable for input to 256-bit
3993 /// version of MOVDDUP.
3994 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3995   if (!HasFp256 || !VT.is256BitVector())
3996     return false;
3997
3998   unsigned NumElts = VT.getVectorNumElements();
3999   if (NumElts != 4)
4000     return false;
4001
4002   for (unsigned i = 0; i != NumElts/2; ++i)
4003     if (!isUndefOrEqual(Mask[i], 0))
4004       return false;
4005   for (unsigned i = NumElts/2; i != NumElts; ++i)
4006     if (!isUndefOrEqual(Mask[i], NumElts/2))
4007       return false;
4008   return true;
4009 }
4010
4011 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4012 /// specifies a shuffle of elements that is suitable for input to 128-bit
4013 /// version of MOVDDUP.
4014 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4015   if (!VT.is128BitVector())
4016     return false;
4017
4018   unsigned e = VT.getVectorNumElements() / 2;
4019   for (unsigned i = 0; i != e; ++i)
4020     if (!isUndefOrEqual(Mask[i], i))
4021       return false;
4022   for (unsigned i = 0; i != e; ++i)
4023     if (!isUndefOrEqual(Mask[e+i], i))
4024       return false;
4025   return true;
4026 }
4027
4028 /// isVEXTRACTF128Index - Return true if the specified
4029 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4030 /// suitable for input to VEXTRACTF128.
4031 bool X86::isVEXTRACTF128Index(SDNode *N) {
4032   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4033     return false;
4034
4035   // The index should be aligned on a 128-bit boundary.
4036   uint64_t Index =
4037     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4038
4039   MVT VT = N->getValueType(0).getSimpleVT();
4040   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4041   bool Result = (Index * ElSize) % 128 == 0;
4042
4043   return Result;
4044 }
4045
4046 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4047 /// operand specifies a subvector insert that is suitable for input to
4048 /// VINSERTF128.
4049 bool X86::isVINSERTF128Index(SDNode *N) {
4050   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4051     return false;
4052
4053   // The index should be aligned on a 128-bit boundary.
4054   uint64_t Index =
4055     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4056
4057   MVT VT = N->getValueType(0).getSimpleVT();
4058   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4059   bool Result = (Index * ElSize) % 128 == 0;
4060
4061   return Result;
4062 }
4063
4064 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4065 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4066 /// Handles 128-bit and 256-bit.
4067 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4068   MVT VT = N->getValueType(0).getSimpleVT();
4069
4070   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4071          "Unsupported vector type for PSHUF/SHUFP");
4072
4073   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4074   // independently on 128-bit lanes.
4075   unsigned NumElts = VT.getVectorNumElements();
4076   unsigned NumLanes = VT.getSizeInBits()/128;
4077   unsigned NumLaneElts = NumElts/NumLanes;
4078
4079   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4080          "Only supports 2 or 4 elements per lane");
4081
4082   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4083   unsigned Mask = 0;
4084   for (unsigned i = 0; i != NumElts; ++i) {
4085     int Elt = N->getMaskElt(i);
4086     if (Elt < 0) continue;
4087     Elt &= NumLaneElts - 1;
4088     unsigned ShAmt = (i << Shift) % 8;
4089     Mask |= Elt << ShAmt;
4090   }
4091
4092   return Mask;
4093 }
4094
4095 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4096 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4097 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4098   MVT VT = N->getValueType(0).getSimpleVT();
4099
4100   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4101          "Unsupported vector type for PSHUFHW");
4102
4103   unsigned NumElts = VT.getVectorNumElements();
4104
4105   unsigned Mask = 0;
4106   for (unsigned l = 0; l != NumElts; l += 8) {
4107     // 8 nodes per lane, but we only care about the last 4.
4108     for (unsigned i = 0; i < 4; ++i) {
4109       int Elt = N->getMaskElt(l+i+4);
4110       if (Elt < 0) continue;
4111       Elt &= 0x3; // only 2-bits.
4112       Mask |= Elt << (i * 2);
4113     }
4114   }
4115
4116   return Mask;
4117 }
4118
4119 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4120 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4121 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4122   MVT VT = N->getValueType(0).getSimpleVT();
4123
4124   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4125          "Unsupported vector type for PSHUFHW");
4126
4127   unsigned NumElts = VT.getVectorNumElements();
4128
4129   unsigned Mask = 0;
4130   for (unsigned l = 0; l != NumElts; l += 8) {
4131     // 8 nodes per lane, but we only care about the first 4.
4132     for (unsigned i = 0; i < 4; ++i) {
4133       int Elt = N->getMaskElt(l+i);
4134       if (Elt < 0) continue;
4135       Elt &= 0x3; // only 2-bits
4136       Mask |= Elt << (i * 2);
4137     }
4138   }
4139
4140   return Mask;
4141 }
4142
4143 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4144 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4145 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4146   MVT VT = SVOp->getValueType(0).getSimpleVT();
4147   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4148
4149   unsigned NumElts = VT.getVectorNumElements();
4150   unsigned NumLanes = VT.getSizeInBits()/128;
4151   unsigned NumLaneElts = NumElts/NumLanes;
4152
4153   int Val = 0;
4154   unsigned i;
4155   for (i = 0; i != NumElts; ++i) {
4156     Val = SVOp->getMaskElt(i);
4157     if (Val >= 0)
4158       break;
4159   }
4160   if (Val >= (int)NumElts)
4161     Val -= NumElts - NumLaneElts;
4162
4163   assert(Val - i > 0 && "PALIGNR imm should be positive");
4164   return (Val - i) * EltSize;
4165 }
4166
4167 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4168 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4169 /// instructions.
4170 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4171   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4172     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4173
4174   uint64_t Index =
4175     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4176
4177   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4178   MVT ElVT = VecVT.getVectorElementType();
4179
4180   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4181   return Index / NumElemsPerChunk;
4182 }
4183
4184 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4185 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4186 /// instructions.
4187 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4188   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4189     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4190
4191   uint64_t Index =
4192     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4193
4194   MVT VecVT = N->getValueType(0).getSimpleVT();
4195   MVT ElVT = VecVT.getVectorElementType();
4196
4197   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4198   return Index / NumElemsPerChunk;
4199 }
4200
4201 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4202 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4203 /// Handles 256-bit.
4204 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4205   MVT VT = N->getValueType(0).getSimpleVT();
4206
4207   unsigned NumElts = VT.getVectorNumElements();
4208
4209   assert((VT.is256BitVector() && NumElts == 4) &&
4210          "Unsupported vector type for VPERMQ/VPERMPD");
4211
4212   unsigned Mask = 0;
4213   for (unsigned i = 0; i != NumElts; ++i) {
4214     int Elt = N->getMaskElt(i);
4215     if (Elt < 0)
4216       continue;
4217     Mask |= Elt << (i*2);
4218   }
4219
4220   return Mask;
4221 }
4222 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4223 /// constant +0.0.
4224 bool X86::isZeroNode(SDValue Elt) {
4225   return ((isa<ConstantSDNode>(Elt) &&
4226            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4227           (isa<ConstantFPSDNode>(Elt) &&
4228            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4229 }
4230
4231 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4232 /// their permute mask.
4233 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4234                                     SelectionDAG &DAG) {
4235   MVT VT = SVOp->getValueType(0).getSimpleVT();
4236   unsigned NumElems = VT.getVectorNumElements();
4237   SmallVector<int, 8> MaskVec;
4238
4239   for (unsigned i = 0; i != NumElems; ++i) {
4240     int Idx = SVOp->getMaskElt(i);
4241     if (Idx >= 0) {
4242       if (Idx < (int)NumElems)
4243         Idx += NumElems;
4244       else
4245         Idx -= NumElems;
4246     }
4247     MaskVec.push_back(Idx);
4248   }
4249   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4250                               SVOp->getOperand(0), &MaskVec[0]);
4251 }
4252
4253 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4254 /// match movhlps. The lower half elements should come from upper half of
4255 /// V1 (and in order), and the upper half elements should come from the upper
4256 /// half of V2 (and in order).
4257 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4258   if (!VT.is128BitVector())
4259     return false;
4260   if (VT.getVectorNumElements() != 4)
4261     return false;
4262   for (unsigned i = 0, e = 2; i != e; ++i)
4263     if (!isUndefOrEqual(Mask[i], i+2))
4264       return false;
4265   for (unsigned i = 2; i != 4; ++i)
4266     if (!isUndefOrEqual(Mask[i], i+4))
4267       return false;
4268   return true;
4269 }
4270
4271 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4272 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4273 /// required.
4274 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4275   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4276     return false;
4277   N = N->getOperand(0).getNode();
4278   if (!ISD::isNON_EXTLoad(N))
4279     return false;
4280   if (LD)
4281     *LD = cast<LoadSDNode>(N);
4282   return true;
4283 }
4284
4285 // Test whether the given value is a vector value which will be legalized
4286 // into a load.
4287 static bool WillBeConstantPoolLoad(SDNode *N) {
4288   if (N->getOpcode() != ISD::BUILD_VECTOR)
4289     return false;
4290
4291   // Check for any non-constant elements.
4292   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4293     switch (N->getOperand(i).getNode()->getOpcode()) {
4294     case ISD::UNDEF:
4295     case ISD::ConstantFP:
4296     case ISD::Constant:
4297       break;
4298     default:
4299       return false;
4300     }
4301
4302   // Vectors of all-zeros and all-ones are materialized with special
4303   // instructions rather than being loaded.
4304   return !ISD::isBuildVectorAllZeros(N) &&
4305          !ISD::isBuildVectorAllOnes(N);
4306 }
4307
4308 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4309 /// match movlp{s|d}. The lower half elements should come from lower half of
4310 /// V1 (and in order), and the upper half elements should come from the upper
4311 /// half of V2 (and in order). And since V1 will become the source of the
4312 /// MOVLP, it must be either a vector load or a scalar load to vector.
4313 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4314                                ArrayRef<int> Mask, EVT VT) {
4315   if (!VT.is128BitVector())
4316     return false;
4317
4318   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4319     return false;
4320   // Is V2 is a vector load, don't do this transformation. We will try to use
4321   // load folding shufps op.
4322   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4323     return false;
4324
4325   unsigned NumElems = VT.getVectorNumElements();
4326
4327   if (NumElems != 2 && NumElems != 4)
4328     return false;
4329   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4330     if (!isUndefOrEqual(Mask[i], i))
4331       return false;
4332   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4333     if (!isUndefOrEqual(Mask[i], i+NumElems))
4334       return false;
4335   return true;
4336 }
4337
4338 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4339 /// all the same.
4340 static bool isSplatVector(SDNode *N) {
4341   if (N->getOpcode() != ISD::BUILD_VECTOR)
4342     return false;
4343
4344   SDValue SplatValue = N->getOperand(0);
4345   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4346     if (N->getOperand(i) != SplatValue)
4347       return false;
4348   return true;
4349 }
4350
4351 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4352 /// to an zero vector.
4353 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4354 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4355   SDValue V1 = N->getOperand(0);
4356   SDValue V2 = N->getOperand(1);
4357   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4358   for (unsigned i = 0; i != NumElems; ++i) {
4359     int Idx = N->getMaskElt(i);
4360     if (Idx >= (int)NumElems) {
4361       unsigned Opc = V2.getOpcode();
4362       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4363         continue;
4364       if (Opc != ISD::BUILD_VECTOR ||
4365           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4366         return false;
4367     } else if (Idx >= 0) {
4368       unsigned Opc = V1.getOpcode();
4369       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4370         continue;
4371       if (Opc != ISD::BUILD_VECTOR ||
4372           !X86::isZeroNode(V1.getOperand(Idx)))
4373         return false;
4374     }
4375   }
4376   return true;
4377 }
4378
4379 /// getZeroVector - Returns a vector of specified type with all zero elements.
4380 ///
4381 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4382                              SelectionDAG &DAG, DebugLoc dl) {
4383   assert(VT.isVector() && "Expected a vector type");
4384
4385   // Always build SSE zero vectors as <4 x i32> bitcasted
4386   // to their dest type. This ensures they get CSE'd.
4387   SDValue Vec;
4388   if (VT.is128BitVector()) {  // SSE
4389     if (Subtarget->hasSSE2()) {  // SSE2
4390       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4391       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4392     } else { // SSE1
4393       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4394       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4395     }
4396   } else if (VT.is256BitVector()) { // AVX
4397     if (Subtarget->hasInt256()) { // AVX2
4398       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4399       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4400       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4401     } else {
4402       // 256-bit logic and arithmetic instructions in AVX are all
4403       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4404       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4405       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4406       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4407     }
4408   } else
4409     llvm_unreachable("Unexpected vector type");
4410
4411   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4412 }
4413
4414 /// getOnesVector - Returns a vector of specified type with all bits set.
4415 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4416 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4417 /// Then bitcast to their original type, ensuring they get CSE'd.
4418 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4419                              DebugLoc dl) {
4420   assert(VT.isVector() && "Expected a vector type");
4421
4422   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4423   SDValue Vec;
4424   if (VT.is256BitVector()) {
4425     if (HasInt256) { // AVX2
4426       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4427       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4428     } else { // AVX
4429       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4430       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4431     }
4432   } else if (VT.is128BitVector()) {
4433     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4434   } else
4435     llvm_unreachable("Unexpected vector type");
4436
4437   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4438 }
4439
4440 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4441 /// that point to V2 points to its first element.
4442 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4443   for (unsigned i = 0; i != NumElems; ++i) {
4444     if (Mask[i] > (int)NumElems) {
4445       Mask[i] = NumElems;
4446     }
4447   }
4448 }
4449
4450 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4451 /// operation of specified width.
4452 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4453                        SDValue V2) {
4454   unsigned NumElems = VT.getVectorNumElements();
4455   SmallVector<int, 8> Mask;
4456   Mask.push_back(NumElems);
4457   for (unsigned i = 1; i != NumElems; ++i)
4458     Mask.push_back(i);
4459   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4460 }
4461
4462 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4463 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4464                           SDValue V2) {
4465   unsigned NumElems = VT.getVectorNumElements();
4466   SmallVector<int, 8> Mask;
4467   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4468     Mask.push_back(i);
4469     Mask.push_back(i + NumElems);
4470   }
4471   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4472 }
4473
4474 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4475 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4476                           SDValue V2) {
4477   unsigned NumElems = VT.getVectorNumElements();
4478   SmallVector<int, 8> Mask;
4479   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4480     Mask.push_back(i + Half);
4481     Mask.push_back(i + NumElems + Half);
4482   }
4483   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4484 }
4485
4486 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4487 // a generic shuffle instruction because the target has no such instructions.
4488 // Generate shuffles which repeat i16 and i8 several times until they can be
4489 // represented by v4f32 and then be manipulated by target suported shuffles.
4490 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4491   EVT VT = V.getValueType();
4492   int NumElems = VT.getVectorNumElements();
4493   DebugLoc dl = V.getDebugLoc();
4494
4495   while (NumElems > 4) {
4496     if (EltNo < NumElems/2) {
4497       V = getUnpackl(DAG, dl, VT, V, V);
4498     } else {
4499       V = getUnpackh(DAG, dl, VT, V, V);
4500       EltNo -= NumElems/2;
4501     }
4502     NumElems >>= 1;
4503   }
4504   return V;
4505 }
4506
4507 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4508 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4509   EVT VT = V.getValueType();
4510   DebugLoc dl = V.getDebugLoc();
4511
4512   if (VT.is128BitVector()) {
4513     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4514     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4515     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4516                              &SplatMask[0]);
4517   } else if (VT.is256BitVector()) {
4518     // To use VPERMILPS to splat scalars, the second half of indicies must
4519     // refer to the higher part, which is a duplication of the lower one,
4520     // because VPERMILPS can only handle in-lane permutations.
4521     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4522                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4523
4524     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4525     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4526                              &SplatMask[0]);
4527   } else
4528     llvm_unreachable("Vector size not supported");
4529
4530   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4531 }
4532
4533 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4534 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4535   EVT SrcVT = SV->getValueType(0);
4536   SDValue V1 = SV->getOperand(0);
4537   DebugLoc dl = SV->getDebugLoc();
4538
4539   int EltNo = SV->getSplatIndex();
4540   int NumElems = SrcVT.getVectorNumElements();
4541   bool Is256BitVec = SrcVT.is256BitVector();
4542
4543   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4544          "Unknown how to promote splat for type");
4545
4546   // Extract the 128-bit part containing the splat element and update
4547   // the splat element index when it refers to the higher register.
4548   if (Is256BitVec) {
4549     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4550     if (EltNo >= NumElems/2)
4551       EltNo -= NumElems/2;
4552   }
4553
4554   // All i16 and i8 vector types can't be used directly by a generic shuffle
4555   // instruction because the target has no such instruction. Generate shuffles
4556   // which repeat i16 and i8 several times until they fit in i32, and then can
4557   // be manipulated by target suported shuffles.
4558   EVT EltVT = SrcVT.getVectorElementType();
4559   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4560     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4561
4562   // Recreate the 256-bit vector and place the same 128-bit vector
4563   // into the low and high part. This is necessary because we want
4564   // to use VPERM* to shuffle the vectors
4565   if (Is256BitVec) {
4566     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4567   }
4568
4569   return getLegalSplat(DAG, V1, EltNo);
4570 }
4571
4572 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4573 /// vector of zero or undef vector.  This produces a shuffle where the low
4574 /// element of V2 is swizzled into the zero/undef vector, landing at element
4575 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4576 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4577                                            bool IsZero,
4578                                            const X86Subtarget *Subtarget,
4579                                            SelectionDAG &DAG) {
4580   EVT VT = V2.getValueType();
4581   SDValue V1 = IsZero
4582     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4583   unsigned NumElems = VT.getVectorNumElements();
4584   SmallVector<int, 16> MaskVec;
4585   for (unsigned i = 0; i != NumElems; ++i)
4586     // If this is the insertion idx, put the low elt of V2 here.
4587     MaskVec.push_back(i == Idx ? NumElems : i);
4588   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4589 }
4590
4591 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4592 /// target specific opcode. Returns true if the Mask could be calculated.
4593 /// Sets IsUnary to true if only uses one source.
4594 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4595                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4596   unsigned NumElems = VT.getVectorNumElements();
4597   SDValue ImmN;
4598
4599   IsUnary = false;
4600   switch(N->getOpcode()) {
4601   case X86ISD::SHUFP:
4602     ImmN = N->getOperand(N->getNumOperands()-1);
4603     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4604     break;
4605   case X86ISD::UNPCKH:
4606     DecodeUNPCKHMask(VT, Mask);
4607     break;
4608   case X86ISD::UNPCKL:
4609     DecodeUNPCKLMask(VT, Mask);
4610     break;
4611   case X86ISD::MOVHLPS:
4612     DecodeMOVHLPSMask(NumElems, Mask);
4613     break;
4614   case X86ISD::MOVLHPS:
4615     DecodeMOVLHPSMask(NumElems, Mask);
4616     break;
4617   case X86ISD::PALIGNR:
4618     ImmN = N->getOperand(N->getNumOperands()-1);
4619     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4620     break;
4621   case X86ISD::PSHUFD:
4622   case X86ISD::VPERMILP:
4623     ImmN = N->getOperand(N->getNumOperands()-1);
4624     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4625     IsUnary = true;
4626     break;
4627   case X86ISD::PSHUFHW:
4628     ImmN = N->getOperand(N->getNumOperands()-1);
4629     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4630     IsUnary = true;
4631     break;
4632   case X86ISD::PSHUFLW:
4633     ImmN = N->getOperand(N->getNumOperands()-1);
4634     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4635     IsUnary = true;
4636     break;
4637   case X86ISD::VPERMI:
4638     ImmN = N->getOperand(N->getNumOperands()-1);
4639     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4640     IsUnary = true;
4641     break;
4642   case X86ISD::MOVSS:
4643   case X86ISD::MOVSD: {
4644     // The index 0 always comes from the first element of the second source,
4645     // this is why MOVSS and MOVSD are used in the first place. The other
4646     // elements come from the other positions of the first source vector
4647     Mask.push_back(NumElems);
4648     for (unsigned i = 1; i != NumElems; ++i) {
4649       Mask.push_back(i);
4650     }
4651     break;
4652   }
4653   case X86ISD::VPERM2X128:
4654     ImmN = N->getOperand(N->getNumOperands()-1);
4655     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4656     if (Mask.empty()) return false;
4657     break;
4658   case X86ISD::MOVDDUP:
4659   case X86ISD::MOVLHPD:
4660   case X86ISD::MOVLPD:
4661   case X86ISD::MOVLPS:
4662   case X86ISD::MOVSHDUP:
4663   case X86ISD::MOVSLDUP:
4664     // Not yet implemented
4665     return false;
4666   default: llvm_unreachable("unknown target shuffle node");
4667   }
4668
4669   return true;
4670 }
4671
4672 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4673 /// element of the result of the vector shuffle.
4674 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4675                                    unsigned Depth) {
4676   if (Depth == 6)
4677     return SDValue();  // Limit search depth.
4678
4679   SDValue V = SDValue(N, 0);
4680   EVT VT = V.getValueType();
4681   unsigned Opcode = V.getOpcode();
4682
4683   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4684   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4685     int Elt = SV->getMaskElt(Index);
4686
4687     if (Elt < 0)
4688       return DAG.getUNDEF(VT.getVectorElementType());
4689
4690     unsigned NumElems = VT.getVectorNumElements();
4691     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4692                                          : SV->getOperand(1);
4693     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4694   }
4695
4696   // Recurse into target specific vector shuffles to find scalars.
4697   if (isTargetShuffle(Opcode)) {
4698     MVT ShufVT = V.getValueType().getSimpleVT();
4699     unsigned NumElems = ShufVT.getVectorNumElements();
4700     SmallVector<int, 16> ShuffleMask;
4701     bool IsUnary;
4702
4703     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4704       return SDValue();
4705
4706     int Elt = ShuffleMask[Index];
4707     if (Elt < 0)
4708       return DAG.getUNDEF(ShufVT.getVectorElementType());
4709
4710     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4711                                          : N->getOperand(1);
4712     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4713                                Depth+1);
4714   }
4715
4716   // Actual nodes that may contain scalar elements
4717   if (Opcode == ISD::BITCAST) {
4718     V = V.getOperand(0);
4719     EVT SrcVT = V.getValueType();
4720     unsigned NumElems = VT.getVectorNumElements();
4721
4722     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4723       return SDValue();
4724   }
4725
4726   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4727     return (Index == 0) ? V.getOperand(0)
4728                         : DAG.getUNDEF(VT.getVectorElementType());
4729
4730   if (V.getOpcode() == ISD::BUILD_VECTOR)
4731     return V.getOperand(Index);
4732
4733   return SDValue();
4734 }
4735
4736 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4737 /// shuffle operation which come from a consecutively from a zero. The
4738 /// search can start in two different directions, from left or right.
4739 static
4740 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4741                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4742   unsigned i;
4743   for (i = 0; i != NumElems; ++i) {
4744     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4745     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4746     if (!(Elt.getNode() &&
4747          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4748       break;
4749   }
4750
4751   return i;
4752 }
4753
4754 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4755 /// correspond consecutively to elements from one of the vector operands,
4756 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4757 static
4758 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4759                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4760                               unsigned NumElems, unsigned &OpNum) {
4761   bool SeenV1 = false;
4762   bool SeenV2 = false;
4763
4764   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4765     int Idx = SVOp->getMaskElt(i);
4766     // Ignore undef indicies
4767     if (Idx < 0)
4768       continue;
4769
4770     if (Idx < (int)NumElems)
4771       SeenV1 = true;
4772     else
4773       SeenV2 = true;
4774
4775     // Only accept consecutive elements from the same vector
4776     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4777       return false;
4778   }
4779
4780   OpNum = SeenV1 ? 0 : 1;
4781   return true;
4782 }
4783
4784 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4785 /// logical left shift of a vector.
4786 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4787                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4788   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4789   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4790               false /* check zeros from right */, DAG);
4791   unsigned OpSrc;
4792
4793   if (!NumZeros)
4794     return false;
4795
4796   // Considering the elements in the mask that are not consecutive zeros,
4797   // check if they consecutively come from only one of the source vectors.
4798   //
4799   //               V1 = {X, A, B, C}     0
4800   //                         \  \  \    /
4801   //   vector_shuffle V1, V2 <1, 2, 3, X>
4802   //
4803   if (!isShuffleMaskConsecutive(SVOp,
4804             0,                   // Mask Start Index
4805             NumElems-NumZeros,   // Mask End Index(exclusive)
4806             NumZeros,            // Where to start looking in the src vector
4807             NumElems,            // Number of elements in vector
4808             OpSrc))              // Which source operand ?
4809     return false;
4810
4811   isLeft = false;
4812   ShAmt = NumZeros;
4813   ShVal = SVOp->getOperand(OpSrc);
4814   return true;
4815 }
4816
4817 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4818 /// logical left shift of a vector.
4819 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4820                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4821   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4822   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4823               true /* check zeros from left */, DAG);
4824   unsigned OpSrc;
4825
4826   if (!NumZeros)
4827     return false;
4828
4829   // Considering the elements in the mask that are not consecutive zeros,
4830   // check if they consecutively come from only one of the source vectors.
4831   //
4832   //                           0    { A, B, X, X } = V2
4833   //                          / \    /  /
4834   //   vector_shuffle V1, V2 <X, X, 4, 5>
4835   //
4836   if (!isShuffleMaskConsecutive(SVOp,
4837             NumZeros,     // Mask Start Index
4838             NumElems,     // Mask End Index(exclusive)
4839             0,            // Where to start looking in the src vector
4840             NumElems,     // Number of elements in vector
4841             OpSrc))       // Which source operand ?
4842     return false;
4843
4844   isLeft = true;
4845   ShAmt = NumZeros;
4846   ShVal = SVOp->getOperand(OpSrc);
4847   return true;
4848 }
4849
4850 /// isVectorShift - Returns true if the shuffle can be implemented as a
4851 /// logical left or right shift of a vector.
4852 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4853                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4854   // Although the logic below support any bitwidth size, there are no
4855   // shift instructions which handle more than 128-bit vectors.
4856   if (!SVOp->getValueType(0).is128BitVector())
4857     return false;
4858
4859   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4860       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4861     return true;
4862
4863   return false;
4864 }
4865
4866 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4867 ///
4868 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4869                                        unsigned NumNonZero, unsigned NumZero,
4870                                        SelectionDAG &DAG,
4871                                        const X86Subtarget* Subtarget,
4872                                        const TargetLowering &TLI) {
4873   if (NumNonZero > 8)
4874     return SDValue();
4875
4876   DebugLoc dl = Op.getDebugLoc();
4877   SDValue V(0, 0);
4878   bool First = true;
4879   for (unsigned i = 0; i < 16; ++i) {
4880     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4881     if (ThisIsNonZero && First) {
4882       if (NumZero)
4883         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4884       else
4885         V = DAG.getUNDEF(MVT::v8i16);
4886       First = false;
4887     }
4888
4889     if ((i & 1) != 0) {
4890       SDValue ThisElt(0, 0), LastElt(0, 0);
4891       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4892       if (LastIsNonZero) {
4893         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4894                               MVT::i16, Op.getOperand(i-1));
4895       }
4896       if (ThisIsNonZero) {
4897         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4898         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4899                               ThisElt, DAG.getConstant(8, MVT::i8));
4900         if (LastIsNonZero)
4901           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4902       } else
4903         ThisElt = LastElt;
4904
4905       if (ThisElt.getNode())
4906         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4907                         DAG.getIntPtrConstant(i/2));
4908     }
4909   }
4910
4911   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4912 }
4913
4914 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4915 ///
4916 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4917                                      unsigned NumNonZero, unsigned NumZero,
4918                                      SelectionDAG &DAG,
4919                                      const X86Subtarget* Subtarget,
4920                                      const TargetLowering &TLI) {
4921   if (NumNonZero > 4)
4922     return SDValue();
4923
4924   DebugLoc dl = Op.getDebugLoc();
4925   SDValue V(0, 0);
4926   bool First = true;
4927   for (unsigned i = 0; i < 8; ++i) {
4928     bool isNonZero = (NonZeros & (1 << i)) != 0;
4929     if (isNonZero) {
4930       if (First) {
4931         if (NumZero)
4932           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4933         else
4934           V = DAG.getUNDEF(MVT::v8i16);
4935         First = false;
4936       }
4937       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4938                       MVT::v8i16, V, Op.getOperand(i),
4939                       DAG.getIntPtrConstant(i));
4940     }
4941   }
4942
4943   return V;
4944 }
4945
4946 /// getVShift - Return a vector logical shift node.
4947 ///
4948 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4949                          unsigned NumBits, SelectionDAG &DAG,
4950                          const TargetLowering &TLI, DebugLoc dl) {
4951   assert(VT.is128BitVector() && "Unknown type for VShift");
4952   EVT ShVT = MVT::v2i64;
4953   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4954   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4955   return DAG.getNode(ISD::BITCAST, dl, VT,
4956                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4957                              DAG.getConstant(NumBits,
4958                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4959 }
4960
4961 SDValue
4962 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4963                                           SelectionDAG &DAG) const {
4964
4965   // Check if the scalar load can be widened into a vector load. And if
4966   // the address is "base + cst" see if the cst can be "absorbed" into
4967   // the shuffle mask.
4968   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4969     SDValue Ptr = LD->getBasePtr();
4970     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4971       return SDValue();
4972     EVT PVT = LD->getValueType(0);
4973     if (PVT != MVT::i32 && PVT != MVT::f32)
4974       return SDValue();
4975
4976     int FI = -1;
4977     int64_t Offset = 0;
4978     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4979       FI = FINode->getIndex();
4980       Offset = 0;
4981     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4982                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4983       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4984       Offset = Ptr.getConstantOperandVal(1);
4985       Ptr = Ptr.getOperand(0);
4986     } else {
4987       return SDValue();
4988     }
4989
4990     // FIXME: 256-bit vector instructions don't require a strict alignment,
4991     // improve this code to support it better.
4992     unsigned RequiredAlign = VT.getSizeInBits()/8;
4993     SDValue Chain = LD->getChain();
4994     // Make sure the stack object alignment is at least 16 or 32.
4995     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4996     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4997       if (MFI->isFixedObjectIndex(FI)) {
4998         // Can't change the alignment. FIXME: It's possible to compute
4999         // the exact stack offset and reference FI + adjust offset instead.
5000         // If someone *really* cares about this. That's the way to implement it.
5001         return SDValue();
5002       } else {
5003         MFI->setObjectAlignment(FI, RequiredAlign);
5004       }
5005     }
5006
5007     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5008     // Ptr + (Offset & ~15).
5009     if (Offset < 0)
5010       return SDValue();
5011     if ((Offset % RequiredAlign) & 3)
5012       return SDValue();
5013     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5014     if (StartOffset)
5015       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5016                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5017
5018     int EltNo = (Offset - StartOffset) >> 2;
5019     unsigned NumElems = VT.getVectorNumElements();
5020
5021     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5022     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5023                              LD->getPointerInfo().getWithOffset(StartOffset),
5024                              false, false, false, 0);
5025
5026     SmallVector<int, 8> Mask;
5027     for (unsigned i = 0; i != NumElems; ++i)
5028       Mask.push_back(EltNo);
5029
5030     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5031   }
5032
5033   return SDValue();
5034 }
5035
5036 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5037 /// vector of type 'VT', see if the elements can be replaced by a single large
5038 /// load which has the same value as a build_vector whose operands are 'elts'.
5039 ///
5040 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5041 ///
5042 /// FIXME: we'd also like to handle the case where the last elements are zero
5043 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5044 /// There's even a handy isZeroNode for that purpose.
5045 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5046                                         DebugLoc &DL, SelectionDAG &DAG) {
5047   EVT EltVT = VT.getVectorElementType();
5048   unsigned NumElems = Elts.size();
5049
5050   LoadSDNode *LDBase = NULL;
5051   unsigned LastLoadedElt = -1U;
5052
5053   // For each element in the initializer, see if we've found a load or an undef.
5054   // If we don't find an initial load element, or later load elements are
5055   // non-consecutive, bail out.
5056   for (unsigned i = 0; i < NumElems; ++i) {
5057     SDValue Elt = Elts[i];
5058
5059     if (!Elt.getNode() ||
5060         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5061       return SDValue();
5062     if (!LDBase) {
5063       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5064         return SDValue();
5065       LDBase = cast<LoadSDNode>(Elt.getNode());
5066       LastLoadedElt = i;
5067       continue;
5068     }
5069     if (Elt.getOpcode() == ISD::UNDEF)
5070       continue;
5071
5072     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5073     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5074       return SDValue();
5075     LastLoadedElt = i;
5076   }
5077
5078   // If we have found an entire vector of loads and undefs, then return a large
5079   // load of the entire vector width starting at the base pointer.  If we found
5080   // consecutive loads for the low half, generate a vzext_load node.
5081   if (LastLoadedElt == NumElems - 1) {
5082     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5083       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5084                          LDBase->getPointerInfo(),
5085                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5086                          LDBase->isInvariant(), 0);
5087     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5088                        LDBase->getPointerInfo(),
5089                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5090                        LDBase->isInvariant(), LDBase->getAlignment());
5091   }
5092   if (NumElems == 4 && LastLoadedElt == 1 &&
5093       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5094     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5095     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5096     SDValue ResNode =
5097         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5098                                 LDBase->getPointerInfo(),
5099                                 LDBase->getAlignment(),
5100                                 false/*isVolatile*/, true/*ReadMem*/,
5101                                 false/*WriteMem*/);
5102
5103     // Make sure the newly-created LOAD is in the same position as LDBase in
5104     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5105     // update uses of LDBase's output chain to use the TokenFactor.
5106     if (LDBase->hasAnyUseOfValue(1)) {
5107       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5108                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5109       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5110       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5111                              SDValue(ResNode.getNode(), 1));
5112     }
5113
5114     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5115   }
5116   return SDValue();
5117 }
5118
5119 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5120 /// to generate a splat value for the following cases:
5121 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5122 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5123 /// a scalar load, or a constant.
5124 /// The VBROADCAST node is returned when a pattern is found,
5125 /// or SDValue() otherwise.
5126 SDValue
5127 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5128   if (!Subtarget->hasFp256())
5129     return SDValue();
5130
5131   MVT VT = Op.getValueType().getSimpleVT();
5132   DebugLoc dl = Op.getDebugLoc();
5133
5134   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5135          "Unsupported vector type for broadcast.");
5136
5137   SDValue Ld;
5138   bool ConstSplatVal;
5139
5140   switch (Op.getOpcode()) {
5141     default:
5142       // Unknown pattern found.
5143       return SDValue();
5144
5145     case ISD::BUILD_VECTOR: {
5146       // The BUILD_VECTOR node must be a splat.
5147       if (!isSplatVector(Op.getNode()))
5148         return SDValue();
5149
5150       Ld = Op.getOperand(0);
5151       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5152                      Ld.getOpcode() == ISD::ConstantFP);
5153
5154       // The suspected load node has several users. Make sure that all
5155       // of its users are from the BUILD_VECTOR node.
5156       // Constants may have multiple users.
5157       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5158         return SDValue();
5159       break;
5160     }
5161
5162     case ISD::VECTOR_SHUFFLE: {
5163       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5164
5165       // Shuffles must have a splat mask where the first element is
5166       // broadcasted.
5167       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5168         return SDValue();
5169
5170       SDValue Sc = Op.getOperand(0);
5171       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5172           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5173
5174         if (!Subtarget->hasInt256())
5175           return SDValue();
5176
5177         // Use the register form of the broadcast instruction available on AVX2.
5178         if (VT.is256BitVector())
5179           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5180         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5181       }
5182
5183       Ld = Sc.getOperand(0);
5184       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5185                        Ld.getOpcode() == ISD::ConstantFP);
5186
5187       // The scalar_to_vector node and the suspected
5188       // load node must have exactly one user.
5189       // Constants may have multiple users.
5190       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5191         return SDValue();
5192       break;
5193     }
5194   }
5195
5196   bool Is256 = VT.is256BitVector();
5197
5198   // Handle the broadcasting a single constant scalar from the constant pool
5199   // into a vector. On Sandybridge it is still better to load a constant vector
5200   // from the constant pool and not to broadcast it from a scalar.
5201   if (ConstSplatVal && Subtarget->hasInt256()) {
5202     EVT CVT = Ld.getValueType();
5203     assert(!CVT.isVector() && "Must not broadcast a vector type");
5204     unsigned ScalarSize = CVT.getSizeInBits();
5205
5206     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5207       const Constant *C = 0;
5208       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5209         C = CI->getConstantIntValue();
5210       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5211         C = CF->getConstantFPValue();
5212
5213       assert(C && "Invalid constant type");
5214
5215       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5216       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5217       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5218                        MachinePointerInfo::getConstantPool(),
5219                        false, false, false, Alignment);
5220
5221       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5222     }
5223   }
5224
5225   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5226   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5227
5228   // Handle AVX2 in-register broadcasts.
5229   if (!IsLoad && Subtarget->hasInt256() &&
5230       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5231     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5232
5233   // The scalar source must be a normal load.
5234   if (!IsLoad)
5235     return SDValue();
5236
5237   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5238     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5239
5240   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5241   // double since there is no vbroadcastsd xmm
5242   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5243     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5244       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5245   }
5246
5247   // Unsupported broadcast.
5248   return SDValue();
5249 }
5250
5251 SDValue
5252 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5253   EVT VT = Op.getValueType();
5254
5255   // Skip if insert_vec_elt is not supported.
5256   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5257     return SDValue();
5258
5259   DebugLoc DL = Op.getDebugLoc();
5260   unsigned NumElems = Op.getNumOperands();
5261
5262   SDValue VecIn1;
5263   SDValue VecIn2;
5264   SmallVector<unsigned, 4> InsertIndices;
5265   SmallVector<int, 8> Mask(NumElems, -1);
5266
5267   for (unsigned i = 0; i != NumElems; ++i) {
5268     unsigned Opc = Op.getOperand(i).getOpcode();
5269
5270     if (Opc == ISD::UNDEF)
5271       continue;
5272
5273     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5274       // Quit if more than 1 elements need inserting.
5275       if (InsertIndices.size() > 1)
5276         return SDValue();
5277
5278       InsertIndices.push_back(i);
5279       continue;
5280     }
5281
5282     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5283     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5284
5285     // Quit if extracted from vector of different type.
5286     if (ExtractedFromVec.getValueType() != VT)
5287       return SDValue();
5288
5289     // Quit if non-constant index.
5290     if (!isa<ConstantSDNode>(ExtIdx))
5291       return SDValue();
5292
5293     if (VecIn1.getNode() == 0)
5294       VecIn1 = ExtractedFromVec;
5295     else if (VecIn1 != ExtractedFromVec) {
5296       if (VecIn2.getNode() == 0)
5297         VecIn2 = ExtractedFromVec;
5298       else if (VecIn2 != ExtractedFromVec)
5299         // Quit if more than 2 vectors to shuffle
5300         return SDValue();
5301     }
5302
5303     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5304
5305     if (ExtractedFromVec == VecIn1)
5306       Mask[i] = Idx;
5307     else if (ExtractedFromVec == VecIn2)
5308       Mask[i] = Idx + NumElems;
5309   }
5310
5311   if (VecIn1.getNode() == 0)
5312     return SDValue();
5313
5314   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5315   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5316   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5317     unsigned Idx = InsertIndices[i];
5318     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5319                      DAG.getIntPtrConstant(Idx));
5320   }
5321
5322   return NV;
5323 }
5324
5325 SDValue
5326 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5327   DebugLoc dl = Op.getDebugLoc();
5328
5329   MVT VT = Op.getValueType().getSimpleVT();
5330   MVT ExtVT = VT.getVectorElementType();
5331   unsigned NumElems = Op.getNumOperands();
5332
5333   // Vectors containing all zeros can be matched by pxor and xorps later
5334   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5335     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5336     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5337     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5338       return Op;
5339
5340     return getZeroVector(VT, Subtarget, DAG, dl);
5341   }
5342
5343   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5344   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5345   // vpcmpeqd on 256-bit vectors.
5346   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5347     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5348       return Op;
5349
5350     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5351   }
5352
5353   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5354   if (Broadcast.getNode())
5355     return Broadcast;
5356
5357   unsigned EVTBits = ExtVT.getSizeInBits();
5358
5359   unsigned NumZero  = 0;
5360   unsigned NumNonZero = 0;
5361   unsigned NonZeros = 0;
5362   bool IsAllConstants = true;
5363   SmallSet<SDValue, 8> Values;
5364   for (unsigned i = 0; i < NumElems; ++i) {
5365     SDValue Elt = Op.getOperand(i);
5366     if (Elt.getOpcode() == ISD::UNDEF)
5367       continue;
5368     Values.insert(Elt);
5369     if (Elt.getOpcode() != ISD::Constant &&
5370         Elt.getOpcode() != ISD::ConstantFP)
5371       IsAllConstants = false;
5372     if (X86::isZeroNode(Elt))
5373       NumZero++;
5374     else {
5375       NonZeros |= (1 << i);
5376       NumNonZero++;
5377     }
5378   }
5379
5380   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5381   if (NumNonZero == 0)
5382     return DAG.getUNDEF(VT);
5383
5384   // Special case for single non-zero, non-undef, element.
5385   if (NumNonZero == 1) {
5386     unsigned Idx = CountTrailingZeros_32(NonZeros);
5387     SDValue Item = Op.getOperand(Idx);
5388
5389     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5390     // the value are obviously zero, truncate the value to i32 and do the
5391     // insertion that way.  Only do this if the value is non-constant or if the
5392     // value is a constant being inserted into element 0.  It is cheaper to do
5393     // a constant pool load than it is to do a movd + shuffle.
5394     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5395         (!IsAllConstants || Idx == 0)) {
5396       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5397         // Handle SSE only.
5398         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5399         EVT VecVT = MVT::v4i32;
5400         unsigned VecElts = 4;
5401
5402         // Truncate the value (which may itself be a constant) to i32, and
5403         // convert it to a vector with movd (S2V+shuffle to zero extend).
5404         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5405         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5406         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5407
5408         // Now we have our 32-bit value zero extended in the low element of
5409         // a vector.  If Idx != 0, swizzle it into place.
5410         if (Idx != 0) {
5411           SmallVector<int, 4> Mask;
5412           Mask.push_back(Idx);
5413           for (unsigned i = 1; i != VecElts; ++i)
5414             Mask.push_back(i);
5415           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5416                                       &Mask[0]);
5417         }
5418         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5419       }
5420     }
5421
5422     // If we have a constant or non-constant insertion into the low element of
5423     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5424     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5425     // depending on what the source datatype is.
5426     if (Idx == 0) {
5427       if (NumZero == 0)
5428         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5429
5430       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5431           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5432         if (VT.is256BitVector()) {
5433           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5434           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5435                              Item, DAG.getIntPtrConstant(0));
5436         }
5437         assert(VT.is128BitVector() && "Expected an SSE value type!");
5438         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5439         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5440         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5441       }
5442
5443       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5444         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5445         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5446         if (VT.is256BitVector()) {
5447           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5448           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5449         } else {
5450           assert(VT.is128BitVector() && "Expected an SSE value type!");
5451           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5452         }
5453         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5454       }
5455     }
5456
5457     // Is it a vector logical left shift?
5458     if (NumElems == 2 && Idx == 1 &&
5459         X86::isZeroNode(Op.getOperand(0)) &&
5460         !X86::isZeroNode(Op.getOperand(1))) {
5461       unsigned NumBits = VT.getSizeInBits();
5462       return getVShift(true, VT,
5463                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5464                                    VT, Op.getOperand(1)),
5465                        NumBits/2, DAG, *this, dl);
5466     }
5467
5468     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5469       return SDValue();
5470
5471     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5472     // is a non-constant being inserted into an element other than the low one,
5473     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5474     // movd/movss) to move this into the low element, then shuffle it into
5475     // place.
5476     if (EVTBits == 32) {
5477       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5478
5479       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5480       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5481       SmallVector<int, 8> MaskVec;
5482       for (unsigned i = 0; i != NumElems; ++i)
5483         MaskVec.push_back(i == Idx ? 0 : 1);
5484       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5485     }
5486   }
5487
5488   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5489   if (Values.size() == 1) {
5490     if (EVTBits == 32) {
5491       // Instead of a shuffle like this:
5492       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5493       // Check if it's possible to issue this instead.
5494       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5495       unsigned Idx = CountTrailingZeros_32(NonZeros);
5496       SDValue Item = Op.getOperand(Idx);
5497       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5498         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5499     }
5500     return SDValue();
5501   }
5502
5503   // A vector full of immediates; various special cases are already
5504   // handled, so this is best done with a single constant-pool load.
5505   if (IsAllConstants)
5506     return SDValue();
5507
5508   // For AVX-length vectors, build the individual 128-bit pieces and use
5509   // shuffles to put them in place.
5510   if (VT.is256BitVector()) {
5511     SmallVector<SDValue, 32> V;
5512     for (unsigned i = 0; i != NumElems; ++i)
5513       V.push_back(Op.getOperand(i));
5514
5515     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5516
5517     // Build both the lower and upper subvector.
5518     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5519     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5520                                 NumElems/2);
5521
5522     // Recreate the wider vector with the lower and upper part.
5523     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5524   }
5525
5526   // Let legalizer expand 2-wide build_vectors.
5527   if (EVTBits == 64) {
5528     if (NumNonZero == 1) {
5529       // One half is zero or undef.
5530       unsigned Idx = CountTrailingZeros_32(NonZeros);
5531       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5532                                  Op.getOperand(Idx));
5533       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5534     }
5535     return SDValue();
5536   }
5537
5538   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5539   if (EVTBits == 8 && NumElems == 16) {
5540     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5541                                         Subtarget, *this);
5542     if (V.getNode()) return V;
5543   }
5544
5545   if (EVTBits == 16 && NumElems == 8) {
5546     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5547                                       Subtarget, *this);
5548     if (V.getNode()) return V;
5549   }
5550
5551   // If element VT is == 32 bits, turn it into a number of shuffles.
5552   SmallVector<SDValue, 8> V(NumElems);
5553   if (NumElems == 4 && NumZero > 0) {
5554     for (unsigned i = 0; i < 4; ++i) {
5555       bool isZero = !(NonZeros & (1 << i));
5556       if (isZero)
5557         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5558       else
5559         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5560     }
5561
5562     for (unsigned i = 0; i < 2; ++i) {
5563       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5564         default: break;
5565         case 0:
5566           V[i] = V[i*2];  // Must be a zero vector.
5567           break;
5568         case 1:
5569           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5570           break;
5571         case 2:
5572           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5573           break;
5574         case 3:
5575           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5576           break;
5577       }
5578     }
5579
5580     bool Reverse1 = (NonZeros & 0x3) == 2;
5581     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5582     int MaskVec[] = {
5583       Reverse1 ? 1 : 0,
5584       Reverse1 ? 0 : 1,
5585       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5586       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5587     };
5588     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5589   }
5590
5591   if (Values.size() > 1 && VT.is128BitVector()) {
5592     // Check for a build vector of consecutive loads.
5593     for (unsigned i = 0; i < NumElems; ++i)
5594       V[i] = Op.getOperand(i);
5595
5596     // Check for elements which are consecutive loads.
5597     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5598     if (LD.getNode())
5599       return LD;
5600
5601     // Check for a build vector from mostly shuffle plus few inserting.
5602     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5603     if (Sh.getNode())
5604       return Sh;
5605
5606     // For SSE 4.1, use insertps to put the high elements into the low element.
5607     if (getSubtarget()->hasSSE41()) {
5608       SDValue Result;
5609       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5610         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5611       else
5612         Result = DAG.getUNDEF(VT);
5613
5614       for (unsigned i = 1; i < NumElems; ++i) {
5615         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5616         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5617                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5618       }
5619       return Result;
5620     }
5621
5622     // Otherwise, expand into a number of unpckl*, start by extending each of
5623     // our (non-undef) elements to the full vector width with the element in the
5624     // bottom slot of the vector (which generates no code for SSE).
5625     for (unsigned i = 0; i < NumElems; ++i) {
5626       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5627         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5628       else
5629         V[i] = DAG.getUNDEF(VT);
5630     }
5631
5632     // Next, we iteratively mix elements, e.g. for v4f32:
5633     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5634     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5635     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5636     unsigned EltStride = NumElems >> 1;
5637     while (EltStride != 0) {
5638       for (unsigned i = 0; i < EltStride; ++i) {
5639         // If V[i+EltStride] is undef and this is the first round of mixing,
5640         // then it is safe to just drop this shuffle: V[i] is already in the
5641         // right place, the one element (since it's the first round) being
5642         // inserted as undef can be dropped.  This isn't safe for successive
5643         // rounds because they will permute elements within both vectors.
5644         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5645             EltStride == NumElems/2)
5646           continue;
5647
5648         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5649       }
5650       EltStride >>= 1;
5651     }
5652     return V[0];
5653   }
5654   return SDValue();
5655 }
5656
5657 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5658 // to create 256-bit vectors from two other 128-bit ones.
5659 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5660   DebugLoc dl = Op.getDebugLoc();
5661   MVT ResVT = Op.getValueType().getSimpleVT();
5662
5663   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5664
5665   SDValue V1 = Op.getOperand(0);
5666   SDValue V2 = Op.getOperand(1);
5667   unsigned NumElems = ResVT.getVectorNumElements();
5668
5669   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5670 }
5671
5672 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5673   assert(Op.getNumOperands() == 2);
5674
5675   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5676   // from two other 128-bit ones.
5677   return LowerAVXCONCAT_VECTORS(Op, DAG);
5678 }
5679
5680 // Try to lower a shuffle node into a simple blend instruction.
5681 static SDValue
5682 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5683                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5684   SDValue V1 = SVOp->getOperand(0);
5685   SDValue V2 = SVOp->getOperand(1);
5686   DebugLoc dl = SVOp->getDebugLoc();
5687   MVT VT = SVOp->getValueType(0).getSimpleVT();
5688   MVT EltVT = VT.getVectorElementType();
5689   unsigned NumElems = VT.getVectorNumElements();
5690
5691   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5692     return SDValue();
5693   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5694     return SDValue();
5695
5696   // Check the mask for BLEND and build the value.
5697   unsigned MaskValue = 0;
5698   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5699   unsigned NumLanes = (NumElems-1)/8 + 1;
5700   unsigned NumElemsInLane = NumElems / NumLanes;
5701
5702   // Blend for v16i16 should be symetric for the both lanes.
5703   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5704
5705     int SndLaneEltIdx = (NumLanes == 2) ?
5706       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5707     int EltIdx = SVOp->getMaskElt(i);
5708
5709     if ((EltIdx < 0 || EltIdx == (int)i) &&
5710         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5711       continue;
5712
5713     if (((unsigned)EltIdx == (i + NumElems)) &&
5714         (SndLaneEltIdx < 0 ||
5715          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5716       MaskValue |= (1<<i);
5717     else
5718       return SDValue();
5719   }
5720
5721   // Convert i32 vectors to floating point if it is not AVX2.
5722   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5723   MVT BlendVT = VT;
5724   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5725     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5726                                NumElems);
5727     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5728     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5729   }
5730
5731   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5732                             DAG.getConstant(MaskValue, MVT::i32));
5733   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5734 }
5735
5736 // v8i16 shuffles - Prefer shuffles in the following order:
5737 // 1. [all]   pshuflw, pshufhw, optional move
5738 // 2. [ssse3] 1 x pshufb
5739 // 3. [ssse3] 2 x pshufb + 1 x por
5740 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5741 static SDValue
5742 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5743                          SelectionDAG &DAG) {
5744   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5745   SDValue V1 = SVOp->getOperand(0);
5746   SDValue V2 = SVOp->getOperand(1);
5747   DebugLoc dl = SVOp->getDebugLoc();
5748   SmallVector<int, 8> MaskVals;
5749
5750   // Determine if more than 1 of the words in each of the low and high quadwords
5751   // of the result come from the same quadword of one of the two inputs.  Undef
5752   // mask values count as coming from any quadword, for better codegen.
5753   unsigned LoQuad[] = { 0, 0, 0, 0 };
5754   unsigned HiQuad[] = { 0, 0, 0, 0 };
5755   std::bitset<4> InputQuads;
5756   for (unsigned i = 0; i < 8; ++i) {
5757     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5758     int EltIdx = SVOp->getMaskElt(i);
5759     MaskVals.push_back(EltIdx);
5760     if (EltIdx < 0) {
5761       ++Quad[0];
5762       ++Quad[1];
5763       ++Quad[2];
5764       ++Quad[3];
5765       continue;
5766     }
5767     ++Quad[EltIdx / 4];
5768     InputQuads.set(EltIdx / 4);
5769   }
5770
5771   int BestLoQuad = -1;
5772   unsigned MaxQuad = 1;
5773   for (unsigned i = 0; i < 4; ++i) {
5774     if (LoQuad[i] > MaxQuad) {
5775       BestLoQuad = i;
5776       MaxQuad = LoQuad[i];
5777     }
5778   }
5779
5780   int BestHiQuad = -1;
5781   MaxQuad = 1;
5782   for (unsigned i = 0; i < 4; ++i) {
5783     if (HiQuad[i] > MaxQuad) {
5784       BestHiQuad = i;
5785       MaxQuad = HiQuad[i];
5786     }
5787   }
5788
5789   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5790   // of the two input vectors, shuffle them into one input vector so only a
5791   // single pshufb instruction is necessary. If There are more than 2 input
5792   // quads, disable the next transformation since it does not help SSSE3.
5793   bool V1Used = InputQuads[0] || InputQuads[1];
5794   bool V2Used = InputQuads[2] || InputQuads[3];
5795   if (Subtarget->hasSSSE3()) {
5796     if (InputQuads.count() == 2 && V1Used && V2Used) {
5797       BestLoQuad = InputQuads[0] ? 0 : 1;
5798       BestHiQuad = InputQuads[2] ? 2 : 3;
5799     }
5800     if (InputQuads.count() > 2) {
5801       BestLoQuad = -1;
5802       BestHiQuad = -1;
5803     }
5804   }
5805
5806   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5807   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5808   // words from all 4 input quadwords.
5809   SDValue NewV;
5810   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5811     int MaskV[] = {
5812       BestLoQuad < 0 ? 0 : BestLoQuad,
5813       BestHiQuad < 0 ? 1 : BestHiQuad
5814     };
5815     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5816                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5817                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5818     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5819
5820     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5821     // source words for the shuffle, to aid later transformations.
5822     bool AllWordsInNewV = true;
5823     bool InOrder[2] = { true, true };
5824     for (unsigned i = 0; i != 8; ++i) {
5825       int idx = MaskVals[i];
5826       if (idx != (int)i)
5827         InOrder[i/4] = false;
5828       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5829         continue;
5830       AllWordsInNewV = false;
5831       break;
5832     }
5833
5834     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5835     if (AllWordsInNewV) {
5836       for (int i = 0; i != 8; ++i) {
5837         int idx = MaskVals[i];
5838         if (idx < 0)
5839           continue;
5840         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5841         if ((idx != i) && idx < 4)
5842           pshufhw = false;
5843         if ((idx != i) && idx > 3)
5844           pshuflw = false;
5845       }
5846       V1 = NewV;
5847       V2Used = false;
5848       BestLoQuad = 0;
5849       BestHiQuad = 1;
5850     }
5851
5852     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5853     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5854     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5855       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5856       unsigned TargetMask = 0;
5857       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5858                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5859       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5860       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5861                              getShufflePSHUFLWImmediate(SVOp);
5862       V1 = NewV.getOperand(0);
5863       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5864     }
5865   }
5866
5867   // Promote splats to a larger type which usually leads to more efficient code.
5868   // FIXME: Is this true if pshufb is available?
5869   if (SVOp->isSplat())
5870     return PromoteSplat(SVOp, DAG);
5871
5872   // If we have SSSE3, and all words of the result are from 1 input vector,
5873   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5874   // is present, fall back to case 4.
5875   if (Subtarget->hasSSSE3()) {
5876     SmallVector<SDValue,16> pshufbMask;
5877
5878     // If we have elements from both input vectors, set the high bit of the
5879     // shuffle mask element to zero out elements that come from V2 in the V1
5880     // mask, and elements that come from V1 in the V2 mask, so that the two
5881     // results can be OR'd together.
5882     bool TwoInputs = V1Used && V2Used;
5883     for (unsigned i = 0; i != 8; ++i) {
5884       int EltIdx = MaskVals[i] * 2;
5885       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5886       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5887       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5888       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5889     }
5890     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5891     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5892                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5893                                  MVT::v16i8, &pshufbMask[0], 16));
5894     if (!TwoInputs)
5895       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5896
5897     // Calculate the shuffle mask for the second input, shuffle it, and
5898     // OR it with the first shuffled input.
5899     pshufbMask.clear();
5900     for (unsigned i = 0; i != 8; ++i) {
5901       int EltIdx = MaskVals[i] * 2;
5902       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5903       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5904       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5905       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5906     }
5907     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5908     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5909                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5910                                  MVT::v16i8, &pshufbMask[0], 16));
5911     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5912     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5913   }
5914
5915   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5916   // and update MaskVals with new element order.
5917   std::bitset<8> InOrder;
5918   if (BestLoQuad >= 0) {
5919     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5920     for (int i = 0; i != 4; ++i) {
5921       int idx = MaskVals[i];
5922       if (idx < 0) {
5923         InOrder.set(i);
5924       } else if ((idx / 4) == BestLoQuad) {
5925         MaskV[i] = idx & 3;
5926         InOrder.set(i);
5927       }
5928     }
5929     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5930                                 &MaskV[0]);
5931
5932     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5933       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5934       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5935                                   NewV.getOperand(0),
5936                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5937     }
5938   }
5939
5940   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5941   // and update MaskVals with the new element order.
5942   if (BestHiQuad >= 0) {
5943     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5944     for (unsigned i = 4; i != 8; ++i) {
5945       int idx = MaskVals[i];
5946       if (idx < 0) {
5947         InOrder.set(i);
5948       } else if ((idx / 4) == BestHiQuad) {
5949         MaskV[i] = (idx & 3) + 4;
5950         InOrder.set(i);
5951       }
5952     }
5953     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5954                                 &MaskV[0]);
5955
5956     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5957       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5958       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5959                                   NewV.getOperand(0),
5960                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5961     }
5962   }
5963
5964   // In case BestHi & BestLo were both -1, which means each quadword has a word
5965   // from each of the four input quadwords, calculate the InOrder bitvector now
5966   // before falling through to the insert/extract cleanup.
5967   if (BestLoQuad == -1 && BestHiQuad == -1) {
5968     NewV = V1;
5969     for (int i = 0; i != 8; ++i)
5970       if (MaskVals[i] < 0 || MaskVals[i] == i)
5971         InOrder.set(i);
5972   }
5973
5974   // The other elements are put in the right place using pextrw and pinsrw.
5975   for (unsigned i = 0; i != 8; ++i) {
5976     if (InOrder[i])
5977       continue;
5978     int EltIdx = MaskVals[i];
5979     if (EltIdx < 0)
5980       continue;
5981     SDValue ExtOp = (EltIdx < 8) ?
5982       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5983                   DAG.getIntPtrConstant(EltIdx)) :
5984       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5985                   DAG.getIntPtrConstant(EltIdx - 8));
5986     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5987                        DAG.getIntPtrConstant(i));
5988   }
5989   return NewV;
5990 }
5991
5992 // v16i8 shuffles - Prefer shuffles in the following order:
5993 // 1. [ssse3] 1 x pshufb
5994 // 2. [ssse3] 2 x pshufb + 1 x por
5995 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5996 static
5997 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5998                                  SelectionDAG &DAG,
5999                                  const X86TargetLowering &TLI) {
6000   SDValue V1 = SVOp->getOperand(0);
6001   SDValue V2 = SVOp->getOperand(1);
6002   DebugLoc dl = SVOp->getDebugLoc();
6003   ArrayRef<int> MaskVals = SVOp->getMask();
6004
6005   // Promote splats to a larger type which usually leads to more efficient code.
6006   // FIXME: Is this true if pshufb is available?
6007   if (SVOp->isSplat())
6008     return PromoteSplat(SVOp, DAG);
6009
6010   // If we have SSSE3, case 1 is generated when all result bytes come from
6011   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6012   // present, fall back to case 3.
6013
6014   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6015   if (TLI.getSubtarget()->hasSSSE3()) {
6016     SmallVector<SDValue,16> pshufbMask;
6017
6018     // If all result elements are from one input vector, then only translate
6019     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6020     //
6021     // Otherwise, we have elements from both input vectors, and must zero out
6022     // elements that come from V2 in the first mask, and V1 in the second mask
6023     // so that we can OR them together.
6024     for (unsigned i = 0; i != 16; ++i) {
6025       int EltIdx = MaskVals[i];
6026       if (EltIdx < 0 || EltIdx >= 16)
6027         EltIdx = 0x80;
6028       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6029     }
6030     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6031                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6032                                  MVT::v16i8, &pshufbMask[0], 16));
6033
6034     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6035     // the 2nd operand if it's undefined or zero.
6036     if (V2.getOpcode() == ISD::UNDEF ||
6037         ISD::isBuildVectorAllZeros(V2.getNode()))
6038       return V1;
6039
6040     // Calculate the shuffle mask for the second input, shuffle it, and
6041     // OR it with the first shuffled input.
6042     pshufbMask.clear();
6043     for (unsigned i = 0; i != 16; ++i) {
6044       int EltIdx = MaskVals[i];
6045       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6046       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6047     }
6048     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6049                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6050                                  MVT::v16i8, &pshufbMask[0], 16));
6051     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6052   }
6053
6054   // No SSSE3 - Calculate in place words and then fix all out of place words
6055   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6056   // the 16 different words that comprise the two doublequadword input vectors.
6057   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6058   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6059   SDValue NewV = V1;
6060   for (int i = 0; i != 8; ++i) {
6061     int Elt0 = MaskVals[i*2];
6062     int Elt1 = MaskVals[i*2+1];
6063
6064     // This word of the result is all undef, skip it.
6065     if (Elt0 < 0 && Elt1 < 0)
6066       continue;
6067
6068     // This word of the result is already in the correct place, skip it.
6069     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6070       continue;
6071
6072     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6073     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6074     SDValue InsElt;
6075
6076     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6077     // using a single extract together, load it and store it.
6078     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6079       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6080                            DAG.getIntPtrConstant(Elt1 / 2));
6081       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6082                         DAG.getIntPtrConstant(i));
6083       continue;
6084     }
6085
6086     // If Elt1 is defined, extract it from the appropriate source.  If the
6087     // source byte is not also odd, shift the extracted word left 8 bits
6088     // otherwise clear the bottom 8 bits if we need to do an or.
6089     if (Elt1 >= 0) {
6090       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6091                            DAG.getIntPtrConstant(Elt1 / 2));
6092       if ((Elt1 & 1) == 0)
6093         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6094                              DAG.getConstant(8,
6095                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6096       else if (Elt0 >= 0)
6097         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6098                              DAG.getConstant(0xFF00, MVT::i16));
6099     }
6100     // If Elt0 is defined, extract it from the appropriate source.  If the
6101     // source byte is not also even, shift the extracted word right 8 bits. If
6102     // Elt1 was also defined, OR the extracted values together before
6103     // inserting them in the result.
6104     if (Elt0 >= 0) {
6105       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6106                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6107       if ((Elt0 & 1) != 0)
6108         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6109                               DAG.getConstant(8,
6110                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6111       else if (Elt1 >= 0)
6112         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6113                              DAG.getConstant(0x00FF, MVT::i16));
6114       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6115                          : InsElt0;
6116     }
6117     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6118                        DAG.getIntPtrConstant(i));
6119   }
6120   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6121 }
6122
6123 // v32i8 shuffles - Translate to VPSHUFB if possible.
6124 static
6125 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6126                                  const X86Subtarget *Subtarget,
6127                                  SelectionDAG &DAG) {
6128   MVT VT = SVOp->getValueType(0).getSimpleVT();
6129   SDValue V1 = SVOp->getOperand(0);
6130   SDValue V2 = SVOp->getOperand(1);
6131   DebugLoc dl = SVOp->getDebugLoc();
6132   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6133
6134   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6135   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6136   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6137
6138   // VPSHUFB may be generated if
6139   // (1) one of input vector is undefined or zeroinitializer.
6140   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6141   // And (2) the mask indexes don't cross the 128-bit lane.
6142   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6143       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6144     return SDValue();
6145
6146   if (V1IsAllZero && !V2IsAllZero) {
6147     CommuteVectorShuffleMask(MaskVals, 32);
6148     V1 = V2;
6149   }
6150   SmallVector<SDValue, 32> pshufbMask;
6151   for (unsigned i = 0; i != 32; i++) {
6152     int EltIdx = MaskVals[i];
6153     if (EltIdx < 0 || EltIdx >= 32)
6154       EltIdx = 0x80;
6155     else {
6156       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6157         // Cross lane is not allowed.
6158         return SDValue();
6159       EltIdx &= 0xf;
6160     }
6161     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6162   }
6163   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6164                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6165                                   MVT::v32i8, &pshufbMask[0], 32));
6166 }
6167
6168 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6169 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6170 /// done when every pair / quad of shuffle mask elements point to elements in
6171 /// the right sequence. e.g.
6172 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6173 static
6174 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6175                                  SelectionDAG &DAG) {
6176   MVT VT = SVOp->getValueType(0).getSimpleVT();
6177   DebugLoc dl = SVOp->getDebugLoc();
6178   unsigned NumElems = VT.getVectorNumElements();
6179   MVT NewVT;
6180   unsigned Scale;
6181   switch (VT.SimpleTy) {
6182   default: llvm_unreachable("Unexpected!");
6183   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6184   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6185   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6186   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6187   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6188   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6189   }
6190
6191   SmallVector<int, 8> MaskVec;
6192   for (unsigned i = 0; i != NumElems; i += Scale) {
6193     int StartIdx = -1;
6194     for (unsigned j = 0; j != Scale; ++j) {
6195       int EltIdx = SVOp->getMaskElt(i+j);
6196       if (EltIdx < 0)
6197         continue;
6198       if (StartIdx < 0)
6199         StartIdx = (EltIdx / Scale);
6200       if (EltIdx != (int)(StartIdx*Scale + j))
6201         return SDValue();
6202     }
6203     MaskVec.push_back(StartIdx);
6204   }
6205
6206   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6207   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6208   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6209 }
6210
6211 /// getVZextMovL - Return a zero-extending vector move low node.
6212 ///
6213 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6214                             SDValue SrcOp, SelectionDAG &DAG,
6215                             const X86Subtarget *Subtarget, DebugLoc dl) {
6216   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6217     LoadSDNode *LD = NULL;
6218     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6219       LD = dyn_cast<LoadSDNode>(SrcOp);
6220     if (!LD) {
6221       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6222       // instead.
6223       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6224       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6225           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6226           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6227           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6228         // PR2108
6229         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6230         return DAG.getNode(ISD::BITCAST, dl, VT,
6231                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6232                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6233                                                    OpVT,
6234                                                    SrcOp.getOperand(0)
6235                                                           .getOperand(0))));
6236       }
6237     }
6238   }
6239
6240   return DAG.getNode(ISD::BITCAST, dl, VT,
6241                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6242                                  DAG.getNode(ISD::BITCAST, dl,
6243                                              OpVT, SrcOp)));
6244 }
6245
6246 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6247 /// which could not be matched by any known target speficic shuffle
6248 static SDValue
6249 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6250
6251   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6252   if (NewOp.getNode())
6253     return NewOp;
6254
6255   MVT VT = SVOp->getValueType(0).getSimpleVT();
6256
6257   unsigned NumElems = VT.getVectorNumElements();
6258   unsigned NumLaneElems = NumElems / 2;
6259
6260   DebugLoc dl = SVOp->getDebugLoc();
6261   MVT EltVT = VT.getVectorElementType();
6262   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6263   SDValue Output[2];
6264
6265   SmallVector<int, 16> Mask;
6266   for (unsigned l = 0; l < 2; ++l) {
6267     // Build a shuffle mask for the output, discovering on the fly which
6268     // input vectors to use as shuffle operands (recorded in InputUsed).
6269     // If building a suitable shuffle vector proves too hard, then bail
6270     // out with UseBuildVector set.
6271     bool UseBuildVector = false;
6272     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6273     unsigned LaneStart = l * NumLaneElems;
6274     for (unsigned i = 0; i != NumLaneElems; ++i) {
6275       // The mask element.  This indexes into the input.
6276       int Idx = SVOp->getMaskElt(i+LaneStart);
6277       if (Idx < 0) {
6278         // the mask element does not index into any input vector.
6279         Mask.push_back(-1);
6280         continue;
6281       }
6282
6283       // The input vector this mask element indexes into.
6284       int Input = Idx / NumLaneElems;
6285
6286       // Turn the index into an offset from the start of the input vector.
6287       Idx -= Input * NumLaneElems;
6288
6289       // Find or create a shuffle vector operand to hold this input.
6290       unsigned OpNo;
6291       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6292         if (InputUsed[OpNo] == Input)
6293           // This input vector is already an operand.
6294           break;
6295         if (InputUsed[OpNo] < 0) {
6296           // Create a new operand for this input vector.
6297           InputUsed[OpNo] = Input;
6298           break;
6299         }
6300       }
6301
6302       if (OpNo >= array_lengthof(InputUsed)) {
6303         // More than two input vectors used!  Give up on trying to create a
6304         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6305         UseBuildVector = true;
6306         break;
6307       }
6308
6309       // Add the mask index for the new shuffle vector.
6310       Mask.push_back(Idx + OpNo * NumLaneElems);
6311     }
6312
6313     if (UseBuildVector) {
6314       SmallVector<SDValue, 16> SVOps;
6315       for (unsigned i = 0; i != NumLaneElems; ++i) {
6316         // The mask element.  This indexes into the input.
6317         int Idx = SVOp->getMaskElt(i+LaneStart);
6318         if (Idx < 0) {
6319           SVOps.push_back(DAG.getUNDEF(EltVT));
6320           continue;
6321         }
6322
6323         // The input vector this mask element indexes into.
6324         int Input = Idx / NumElems;
6325
6326         // Turn the index into an offset from the start of the input vector.
6327         Idx -= Input * NumElems;
6328
6329         // Extract the vector element by hand.
6330         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6331                                     SVOp->getOperand(Input),
6332                                     DAG.getIntPtrConstant(Idx)));
6333       }
6334
6335       // Construct the output using a BUILD_VECTOR.
6336       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6337                               SVOps.size());
6338     } else if (InputUsed[0] < 0) {
6339       // No input vectors were used! The result is undefined.
6340       Output[l] = DAG.getUNDEF(NVT);
6341     } else {
6342       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6343                                         (InputUsed[0] % 2) * NumLaneElems,
6344                                         DAG, dl);
6345       // If only one input was used, use an undefined vector for the other.
6346       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6347         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6348                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6349       // At least one input vector was used. Create a new shuffle vector.
6350       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6351     }
6352
6353     Mask.clear();
6354   }
6355
6356   // Concatenate the result back
6357   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6358 }
6359
6360 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6361 /// 4 elements, and match them with several different shuffle types.
6362 static SDValue
6363 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6364   SDValue V1 = SVOp->getOperand(0);
6365   SDValue V2 = SVOp->getOperand(1);
6366   DebugLoc dl = SVOp->getDebugLoc();
6367   MVT VT = SVOp->getValueType(0).getSimpleVT();
6368
6369   assert(VT.is128BitVector() && "Unsupported vector size");
6370
6371   std::pair<int, int> Locs[4];
6372   int Mask1[] = { -1, -1, -1, -1 };
6373   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6374
6375   unsigned NumHi = 0;
6376   unsigned NumLo = 0;
6377   for (unsigned i = 0; i != 4; ++i) {
6378     int Idx = PermMask[i];
6379     if (Idx < 0) {
6380       Locs[i] = std::make_pair(-1, -1);
6381     } else {
6382       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6383       if (Idx < 4) {
6384         Locs[i] = std::make_pair(0, NumLo);
6385         Mask1[NumLo] = Idx;
6386         NumLo++;
6387       } else {
6388         Locs[i] = std::make_pair(1, NumHi);
6389         if (2+NumHi < 4)
6390           Mask1[2+NumHi] = Idx;
6391         NumHi++;
6392       }
6393     }
6394   }
6395
6396   if (NumLo <= 2 && NumHi <= 2) {
6397     // If no more than two elements come from either vector. This can be
6398     // implemented with two shuffles. First shuffle gather the elements.
6399     // The second shuffle, which takes the first shuffle as both of its
6400     // vector operands, put the elements into the right order.
6401     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6402
6403     int Mask2[] = { -1, -1, -1, -1 };
6404
6405     for (unsigned i = 0; i != 4; ++i)
6406       if (Locs[i].first != -1) {
6407         unsigned Idx = (i < 2) ? 0 : 4;
6408         Idx += Locs[i].first * 2 + Locs[i].second;
6409         Mask2[i] = Idx;
6410       }
6411
6412     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6413   }
6414
6415   if (NumLo == 3 || NumHi == 3) {
6416     // Otherwise, we must have three elements from one vector, call it X, and
6417     // one element from the other, call it Y.  First, use a shufps to build an
6418     // intermediate vector with the one element from Y and the element from X
6419     // that will be in the same half in the final destination (the indexes don't
6420     // matter). Then, use a shufps to build the final vector, taking the half
6421     // containing the element from Y from the intermediate, and the other half
6422     // from X.
6423     if (NumHi == 3) {
6424       // Normalize it so the 3 elements come from V1.
6425       CommuteVectorShuffleMask(PermMask, 4);
6426       std::swap(V1, V2);
6427     }
6428
6429     // Find the element from V2.
6430     unsigned HiIndex;
6431     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6432       int Val = PermMask[HiIndex];
6433       if (Val < 0)
6434         continue;
6435       if (Val >= 4)
6436         break;
6437     }
6438
6439     Mask1[0] = PermMask[HiIndex];
6440     Mask1[1] = -1;
6441     Mask1[2] = PermMask[HiIndex^1];
6442     Mask1[3] = -1;
6443     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6444
6445     if (HiIndex >= 2) {
6446       Mask1[0] = PermMask[0];
6447       Mask1[1] = PermMask[1];
6448       Mask1[2] = HiIndex & 1 ? 6 : 4;
6449       Mask1[3] = HiIndex & 1 ? 4 : 6;
6450       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6451     }
6452
6453     Mask1[0] = HiIndex & 1 ? 2 : 0;
6454     Mask1[1] = HiIndex & 1 ? 0 : 2;
6455     Mask1[2] = PermMask[2];
6456     Mask1[3] = PermMask[3];
6457     if (Mask1[2] >= 0)
6458       Mask1[2] += 4;
6459     if (Mask1[3] >= 0)
6460       Mask1[3] += 4;
6461     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6462   }
6463
6464   // Break it into (shuffle shuffle_hi, shuffle_lo).
6465   int LoMask[] = { -1, -1, -1, -1 };
6466   int HiMask[] = { -1, -1, -1, -1 };
6467
6468   int *MaskPtr = LoMask;
6469   unsigned MaskIdx = 0;
6470   unsigned LoIdx = 0;
6471   unsigned HiIdx = 2;
6472   for (unsigned i = 0; i != 4; ++i) {
6473     if (i == 2) {
6474       MaskPtr = HiMask;
6475       MaskIdx = 1;
6476       LoIdx = 0;
6477       HiIdx = 2;
6478     }
6479     int Idx = PermMask[i];
6480     if (Idx < 0) {
6481       Locs[i] = std::make_pair(-1, -1);
6482     } else if (Idx < 4) {
6483       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6484       MaskPtr[LoIdx] = Idx;
6485       LoIdx++;
6486     } else {
6487       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6488       MaskPtr[HiIdx] = Idx;
6489       HiIdx++;
6490     }
6491   }
6492
6493   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6494   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6495   int MaskOps[] = { -1, -1, -1, -1 };
6496   for (unsigned i = 0; i != 4; ++i)
6497     if (Locs[i].first != -1)
6498       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6499   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6500 }
6501
6502 static bool MayFoldVectorLoad(SDValue V) {
6503   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6504     V = V.getOperand(0);
6505
6506   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6507     V = V.getOperand(0);
6508   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6509       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6510     // BUILD_VECTOR (load), undef
6511     V = V.getOperand(0);
6512
6513   return MayFoldLoad(V);
6514 }
6515
6516 static
6517 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6518   EVT VT = Op.getValueType();
6519
6520   // Canonizalize to v2f64.
6521   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6522   return DAG.getNode(ISD::BITCAST, dl, VT,
6523                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6524                                           V1, DAG));
6525 }
6526
6527 static
6528 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6529                         bool HasSSE2) {
6530   SDValue V1 = Op.getOperand(0);
6531   SDValue V2 = Op.getOperand(1);
6532   EVT VT = Op.getValueType();
6533
6534   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6535
6536   if (HasSSE2 && VT == MVT::v2f64)
6537     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6538
6539   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6540   return DAG.getNode(ISD::BITCAST, dl, VT,
6541                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6542                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6543                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6544 }
6545
6546 static
6547 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6548   SDValue V1 = Op.getOperand(0);
6549   SDValue V2 = Op.getOperand(1);
6550   EVT VT = Op.getValueType();
6551
6552   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6553          "unsupported shuffle type");
6554
6555   if (V2.getOpcode() == ISD::UNDEF)
6556     V2 = V1;
6557
6558   // v4i32 or v4f32
6559   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6560 }
6561
6562 static
6563 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6564   SDValue V1 = Op.getOperand(0);
6565   SDValue V2 = Op.getOperand(1);
6566   EVT VT = Op.getValueType();
6567   unsigned NumElems = VT.getVectorNumElements();
6568
6569   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6570   // operand of these instructions is only memory, so check if there's a
6571   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6572   // same masks.
6573   bool CanFoldLoad = false;
6574
6575   // Trivial case, when V2 comes from a load.
6576   if (MayFoldVectorLoad(V2))
6577     CanFoldLoad = true;
6578
6579   // When V1 is a load, it can be folded later into a store in isel, example:
6580   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6581   //    turns into:
6582   //  (MOVLPSmr addr:$src1, VR128:$src2)
6583   // So, recognize this potential and also use MOVLPS or MOVLPD
6584   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6585     CanFoldLoad = true;
6586
6587   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6588   if (CanFoldLoad) {
6589     if (HasSSE2 && NumElems == 2)
6590       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6591
6592     if (NumElems == 4)
6593       // If we don't care about the second element, proceed to use movss.
6594       if (SVOp->getMaskElt(1) != -1)
6595         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6596   }
6597
6598   // movl and movlp will both match v2i64, but v2i64 is never matched by
6599   // movl earlier because we make it strict to avoid messing with the movlp load
6600   // folding logic (see the code above getMOVLP call). Match it here then,
6601   // this is horrible, but will stay like this until we move all shuffle
6602   // matching to x86 specific nodes. Note that for the 1st condition all
6603   // types are matched with movsd.
6604   if (HasSSE2) {
6605     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6606     // as to remove this logic from here, as much as possible
6607     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6608       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6609     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6610   }
6611
6612   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6613
6614   // Invert the operand order and use SHUFPS to match it.
6615   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6616                               getShuffleSHUFImmediate(SVOp), DAG);
6617 }
6618
6619 // Reduce a vector shuffle to zext.
6620 SDValue
6621 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6622   // PMOVZX is only available from SSE41.
6623   if (!Subtarget->hasSSE41())
6624     return SDValue();
6625
6626   EVT VT = Op.getValueType();
6627
6628   // Only AVX2 support 256-bit vector integer extending.
6629   if (!Subtarget->hasInt256() && VT.is256BitVector())
6630     return SDValue();
6631
6632   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6633   DebugLoc DL = Op.getDebugLoc();
6634   SDValue V1 = Op.getOperand(0);
6635   SDValue V2 = Op.getOperand(1);
6636   unsigned NumElems = VT.getVectorNumElements();
6637
6638   // Extending is an unary operation and the element type of the source vector
6639   // won't be equal to or larger than i64.
6640   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6641       VT.getVectorElementType() == MVT::i64)
6642     return SDValue();
6643
6644   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6645   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6646   while ((1U << Shift) < NumElems) {
6647     if (SVOp->getMaskElt(1U << Shift) == 1)
6648       break;
6649     Shift += 1;
6650     // The maximal ratio is 8, i.e. from i8 to i64.
6651     if (Shift > 3)
6652       return SDValue();
6653   }
6654
6655   // Check the shuffle mask.
6656   unsigned Mask = (1U << Shift) - 1;
6657   for (unsigned i = 0; i != NumElems; ++i) {
6658     int EltIdx = SVOp->getMaskElt(i);
6659     if ((i & Mask) != 0 && EltIdx != -1)
6660       return SDValue();
6661     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6662       return SDValue();
6663   }
6664
6665   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6666   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6667   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6668
6669   if (!isTypeLegal(NVT))
6670     return SDValue();
6671
6672   // Simplify the operand as it's prepared to be fed into shuffle.
6673   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6674   if (V1.getOpcode() == ISD::BITCAST &&
6675       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6676       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6677       V1.getOperand(0)
6678         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6679     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6680     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6681     ConstantSDNode *CIdx =
6682       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6683     // If it's foldable, i.e. normal load with single use, we will let code
6684     // selection to fold it. Otherwise, we will short the conversion sequence.
6685     if (CIdx && CIdx->getZExtValue() == 0 &&
6686         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6687       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6688   }
6689
6690   return DAG.getNode(ISD::BITCAST, DL, VT,
6691                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6692 }
6693
6694 SDValue
6695 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6696   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6697   MVT VT = Op.getValueType().getSimpleVT();
6698   DebugLoc dl = Op.getDebugLoc();
6699   SDValue V1 = Op.getOperand(0);
6700   SDValue V2 = Op.getOperand(1);
6701
6702   if (isZeroShuffle(SVOp))
6703     return getZeroVector(VT, Subtarget, DAG, dl);
6704
6705   // Handle splat operations
6706   if (SVOp->isSplat()) {
6707     // Use vbroadcast whenever the splat comes from a foldable load
6708     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6709     if (Broadcast.getNode())
6710       return Broadcast;
6711   }
6712
6713   // Check integer expanding shuffles.
6714   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6715   if (NewOp.getNode())
6716     return NewOp;
6717
6718   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6719   // do it!
6720   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6721       VT == MVT::v16i16 || VT == MVT::v32i8) {
6722     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6723     if (NewOp.getNode())
6724       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6725   } else if ((VT == MVT::v4i32 ||
6726              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6727     // FIXME: Figure out a cleaner way to do this.
6728     // Try to make use of movq to zero out the top part.
6729     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6730       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6731       if (NewOp.getNode()) {
6732         MVT NewVT = NewOp.getValueType().getSimpleVT();
6733         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6734                                NewVT, true, false))
6735           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6736                               DAG, Subtarget, dl);
6737       }
6738     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6739       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6740       if (NewOp.getNode()) {
6741         MVT NewVT = NewOp.getValueType().getSimpleVT();
6742         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6743           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6744                               DAG, Subtarget, dl);
6745       }
6746     }
6747   }
6748   return SDValue();
6749 }
6750
6751 SDValue
6752 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6753   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6754   SDValue V1 = Op.getOperand(0);
6755   SDValue V2 = Op.getOperand(1);
6756   MVT VT = Op.getValueType().getSimpleVT();
6757   DebugLoc dl = Op.getDebugLoc();
6758   unsigned NumElems = VT.getVectorNumElements();
6759   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6760   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6761   bool V1IsSplat = false;
6762   bool V2IsSplat = false;
6763   bool HasSSE2 = Subtarget->hasSSE2();
6764   bool HasFp256    = Subtarget->hasFp256();
6765   bool HasInt256   = Subtarget->hasInt256();
6766   MachineFunction &MF = DAG.getMachineFunction();
6767   bool OptForSize = MF.getFunction()->getAttributes().
6768     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6769
6770   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6771
6772   if (V1IsUndef && V2IsUndef)
6773     return DAG.getUNDEF(VT);
6774
6775   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6776
6777   // Vector shuffle lowering takes 3 steps:
6778   //
6779   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6780   //    narrowing and commutation of operands should be handled.
6781   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6782   //    shuffle nodes.
6783   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6784   //    so the shuffle can be broken into other shuffles and the legalizer can
6785   //    try the lowering again.
6786   //
6787   // The general idea is that no vector_shuffle operation should be left to
6788   // be matched during isel, all of them must be converted to a target specific
6789   // node here.
6790
6791   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6792   // narrowing and commutation of operands should be handled. The actual code
6793   // doesn't include all of those, work in progress...
6794   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6795   if (NewOp.getNode())
6796     return NewOp;
6797
6798   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6799
6800   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6801   // unpckh_undef). Only use pshufd if speed is more important than size.
6802   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6803     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6804   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6805     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6806
6807   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6808       V2IsUndef && MayFoldVectorLoad(V1))
6809     return getMOVDDup(Op, dl, V1, DAG);
6810
6811   if (isMOVHLPS_v_undef_Mask(M, VT))
6812     return getMOVHighToLow(Op, dl, DAG);
6813
6814   // Use to match splats
6815   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6816       (VT == MVT::v2f64 || VT == MVT::v2i64))
6817     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6818
6819   if (isPSHUFDMask(M, VT)) {
6820     // The actual implementation will match the mask in the if above and then
6821     // during isel it can match several different instructions, not only pshufd
6822     // as its name says, sad but true, emulate the behavior for now...
6823     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6824       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6825
6826     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6827
6828     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6829       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6830
6831     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6832       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6833                                   DAG);
6834
6835     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6836                                 TargetMask, DAG);
6837   }
6838
6839   // Check if this can be converted into a logical shift.
6840   bool isLeft = false;
6841   unsigned ShAmt = 0;
6842   SDValue ShVal;
6843   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6844   if (isShift && ShVal.hasOneUse()) {
6845     // If the shifted value has multiple uses, it may be cheaper to use
6846     // v_set0 + movlhps or movhlps, etc.
6847     MVT EltVT = VT.getVectorElementType();
6848     ShAmt *= EltVT.getSizeInBits();
6849     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6850   }
6851
6852   if (isMOVLMask(M, VT)) {
6853     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6854       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6855     if (!isMOVLPMask(M, VT)) {
6856       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6857         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6858
6859       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6860         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6861     }
6862   }
6863
6864   // FIXME: fold these into legal mask.
6865   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6866     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6867
6868   if (isMOVHLPSMask(M, VT))
6869     return getMOVHighToLow(Op, dl, DAG);
6870
6871   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6872     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6873
6874   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6875     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6876
6877   if (isMOVLPMask(M, VT))
6878     return getMOVLP(Op, dl, DAG, HasSSE2);
6879
6880   if (ShouldXformToMOVHLPS(M, VT) ||
6881       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6882     return CommuteVectorShuffle(SVOp, DAG);
6883
6884   if (isShift) {
6885     // No better options. Use a vshldq / vsrldq.
6886     MVT EltVT = VT.getVectorElementType();
6887     ShAmt *= EltVT.getSizeInBits();
6888     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6889   }
6890
6891   bool Commuted = false;
6892   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6893   // 1,1,1,1 -> v8i16 though.
6894   V1IsSplat = isSplatVector(V1.getNode());
6895   V2IsSplat = isSplatVector(V2.getNode());
6896
6897   // Canonicalize the splat or undef, if present, to be on the RHS.
6898   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6899     CommuteVectorShuffleMask(M, NumElems);
6900     std::swap(V1, V2);
6901     std::swap(V1IsSplat, V2IsSplat);
6902     Commuted = true;
6903   }
6904
6905   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6906     // Shuffling low element of v1 into undef, just return v1.
6907     if (V2IsUndef)
6908       return V1;
6909     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6910     // the instruction selector will not match, so get a canonical MOVL with
6911     // swapped operands to undo the commute.
6912     return getMOVL(DAG, dl, VT, V2, V1);
6913   }
6914
6915   if (isUNPCKLMask(M, VT, HasInt256))
6916     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6917
6918   if (isUNPCKHMask(M, VT, HasInt256))
6919     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6920
6921   if (V2IsSplat) {
6922     // Normalize mask so all entries that point to V2 points to its first
6923     // element then try to match unpck{h|l} again. If match, return a
6924     // new vector_shuffle with the corrected mask.p
6925     SmallVector<int, 8> NewMask(M.begin(), M.end());
6926     NormalizeMask(NewMask, NumElems);
6927     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6928       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6929     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6930       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6931   }
6932
6933   if (Commuted) {
6934     // Commute is back and try unpck* again.
6935     // FIXME: this seems wrong.
6936     CommuteVectorShuffleMask(M, NumElems);
6937     std::swap(V1, V2);
6938     std::swap(V1IsSplat, V2IsSplat);
6939     Commuted = false;
6940
6941     if (isUNPCKLMask(M, VT, HasInt256))
6942       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6943
6944     if (isUNPCKHMask(M, VT, HasInt256))
6945       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6946   }
6947
6948   // Normalize the node to match x86 shuffle ops if needed
6949   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6950     return CommuteVectorShuffle(SVOp, DAG);
6951
6952   // The checks below are all present in isShuffleMaskLegal, but they are
6953   // inlined here right now to enable us to directly emit target specific
6954   // nodes, and remove one by one until they don't return Op anymore.
6955
6956   if (isPALIGNRMask(M, VT, Subtarget))
6957     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6958                                 getShufflePALIGNRImmediate(SVOp),
6959                                 DAG);
6960
6961   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6962       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6963     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6964       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6965   }
6966
6967   if (isPSHUFHWMask(M, VT, HasInt256))
6968     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6969                                 getShufflePSHUFHWImmediate(SVOp),
6970                                 DAG);
6971
6972   if (isPSHUFLWMask(M, VT, HasInt256))
6973     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6974                                 getShufflePSHUFLWImmediate(SVOp),
6975                                 DAG);
6976
6977   if (isSHUFPMask(M, VT, HasFp256))
6978     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6979                                 getShuffleSHUFImmediate(SVOp), DAG);
6980
6981   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6982     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6983   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6984     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6985
6986   //===--------------------------------------------------------------------===//
6987   // Generate target specific nodes for 128 or 256-bit shuffles only
6988   // supported in the AVX instruction set.
6989   //
6990
6991   // Handle VMOVDDUPY permutations
6992   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6993     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6994
6995   // Handle VPERMILPS/D* permutations
6996   if (isVPERMILPMask(M, VT, HasFp256)) {
6997     if (HasInt256 && VT == MVT::v8i32)
6998       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6999                                   getShuffleSHUFImmediate(SVOp), DAG);
7000     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7001                                 getShuffleSHUFImmediate(SVOp), DAG);
7002   }
7003
7004   // Handle VPERM2F128/VPERM2I128 permutations
7005   if (isVPERM2X128Mask(M, VT, HasFp256))
7006     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7007                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7008
7009   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7010   if (BlendOp.getNode())
7011     return BlendOp;
7012
7013   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7014     SmallVector<SDValue, 8> permclMask;
7015     for (unsigned i = 0; i != 8; ++i) {
7016       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7017     }
7018     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7019                                &permclMask[0], 8);
7020     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7021     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7022                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7023   }
7024
7025   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7026     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7027                                 getShuffleCLImmediate(SVOp), DAG);
7028
7029   //===--------------------------------------------------------------------===//
7030   // Since no target specific shuffle was selected for this generic one,
7031   // lower it into other known shuffles. FIXME: this isn't true yet, but
7032   // this is the plan.
7033   //
7034
7035   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7036   if (VT == MVT::v8i16) {
7037     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7038     if (NewOp.getNode())
7039       return NewOp;
7040   }
7041
7042   if (VT == MVT::v16i8) {
7043     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7044     if (NewOp.getNode())
7045       return NewOp;
7046   }
7047
7048   if (VT == MVT::v32i8) {
7049     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7050     if (NewOp.getNode())
7051       return NewOp;
7052   }
7053
7054   // Handle all 128-bit wide vectors with 4 elements, and match them with
7055   // several different shuffle types.
7056   if (NumElems == 4 && VT.is128BitVector())
7057     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7058
7059   // Handle general 256-bit shuffles
7060   if (VT.is256BitVector())
7061     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7062
7063   return SDValue();
7064 }
7065
7066 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7067   MVT VT = Op.getValueType().getSimpleVT();
7068   DebugLoc dl = Op.getDebugLoc();
7069
7070   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7071     return SDValue();
7072
7073   if (VT.getSizeInBits() == 8) {
7074     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7075                                   Op.getOperand(0), Op.getOperand(1));
7076     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7077                                   DAG.getValueType(VT));
7078     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7079   }
7080
7081   if (VT.getSizeInBits() == 16) {
7082     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7083     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7084     if (Idx == 0)
7085       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7086                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7087                                      DAG.getNode(ISD::BITCAST, dl,
7088                                                  MVT::v4i32,
7089                                                  Op.getOperand(0)),
7090                                      Op.getOperand(1)));
7091     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7092                                   Op.getOperand(0), Op.getOperand(1));
7093     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7094                                   DAG.getValueType(VT));
7095     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7096   }
7097
7098   if (VT == MVT::f32) {
7099     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7100     // the result back to FR32 register. It's only worth matching if the
7101     // result has a single use which is a store or a bitcast to i32.  And in
7102     // the case of a store, it's not worth it if the index is a constant 0,
7103     // because a MOVSSmr can be used instead, which is smaller and faster.
7104     if (!Op.hasOneUse())
7105       return SDValue();
7106     SDNode *User = *Op.getNode()->use_begin();
7107     if ((User->getOpcode() != ISD::STORE ||
7108          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7109           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7110         (User->getOpcode() != ISD::BITCAST ||
7111          User->getValueType(0) != MVT::i32))
7112       return SDValue();
7113     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7114                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7115                                               Op.getOperand(0)),
7116                                               Op.getOperand(1));
7117     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7118   }
7119
7120   if (VT == MVT::i32 || VT == MVT::i64) {
7121     // ExtractPS/pextrq works with constant index.
7122     if (isa<ConstantSDNode>(Op.getOperand(1)))
7123       return Op;
7124   }
7125   return SDValue();
7126 }
7127
7128 SDValue
7129 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7130                                            SelectionDAG &DAG) const {
7131   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7132     return SDValue();
7133
7134   SDValue Vec = Op.getOperand(0);
7135   MVT VecVT = Vec.getValueType().getSimpleVT();
7136
7137   // If this is a 256-bit vector result, first extract the 128-bit vector and
7138   // then extract the element from the 128-bit vector.
7139   if (VecVT.is256BitVector()) {
7140     DebugLoc dl = Op.getNode()->getDebugLoc();
7141     unsigned NumElems = VecVT.getVectorNumElements();
7142     SDValue Idx = Op.getOperand(1);
7143     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7144
7145     // Get the 128-bit vector.
7146     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7147
7148     if (IdxVal >= NumElems/2)
7149       IdxVal -= NumElems/2;
7150     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7151                        DAG.getConstant(IdxVal, MVT::i32));
7152   }
7153
7154   assert(VecVT.is128BitVector() && "Unexpected vector length");
7155
7156   if (Subtarget->hasSSE41()) {
7157     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7158     if (Res.getNode())
7159       return Res;
7160   }
7161
7162   MVT VT = Op.getValueType().getSimpleVT();
7163   DebugLoc dl = Op.getDebugLoc();
7164   // TODO: handle v16i8.
7165   if (VT.getSizeInBits() == 16) {
7166     SDValue Vec = Op.getOperand(0);
7167     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7168     if (Idx == 0)
7169       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7170                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7171                                      DAG.getNode(ISD::BITCAST, dl,
7172                                                  MVT::v4i32, Vec),
7173                                      Op.getOperand(1)));
7174     // Transform it so it match pextrw which produces a 32-bit result.
7175     MVT EltVT = MVT::i32;
7176     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7177                                   Op.getOperand(0), Op.getOperand(1));
7178     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7179                                   DAG.getValueType(VT));
7180     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7181   }
7182
7183   if (VT.getSizeInBits() == 32) {
7184     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7185     if (Idx == 0)
7186       return Op;
7187
7188     // SHUFPS the element to the lowest double word, then movss.
7189     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7190     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7191     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7192                                        DAG.getUNDEF(VVT), Mask);
7193     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7194                        DAG.getIntPtrConstant(0));
7195   }
7196
7197   if (VT.getSizeInBits() == 64) {
7198     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7199     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7200     //        to match extract_elt for f64.
7201     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7202     if (Idx == 0)
7203       return Op;
7204
7205     // UNPCKHPD the element to the lowest double word, then movsd.
7206     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7207     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7208     int Mask[2] = { 1, -1 };
7209     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7210     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7211                                        DAG.getUNDEF(VVT), Mask);
7212     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7213                        DAG.getIntPtrConstant(0));
7214   }
7215
7216   return SDValue();
7217 }
7218
7219 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7220   MVT VT = Op.getValueType().getSimpleVT();
7221   MVT EltVT = VT.getVectorElementType();
7222   DebugLoc dl = Op.getDebugLoc();
7223
7224   SDValue N0 = Op.getOperand(0);
7225   SDValue N1 = Op.getOperand(1);
7226   SDValue N2 = Op.getOperand(2);
7227
7228   if (!VT.is128BitVector())
7229     return SDValue();
7230
7231   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7232       isa<ConstantSDNode>(N2)) {
7233     unsigned Opc;
7234     if (VT == MVT::v8i16)
7235       Opc = X86ISD::PINSRW;
7236     else if (VT == MVT::v16i8)
7237       Opc = X86ISD::PINSRB;
7238     else
7239       Opc = X86ISD::PINSRB;
7240
7241     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7242     // argument.
7243     if (N1.getValueType() != MVT::i32)
7244       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7245     if (N2.getValueType() != MVT::i32)
7246       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7247     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7248   }
7249
7250   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7251     // Bits [7:6] of the constant are the source select.  This will always be
7252     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7253     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7254     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7255     // Bits [5:4] of the constant are the destination select.  This is the
7256     //  value of the incoming immediate.
7257     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7258     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7259     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7260     // Create this as a scalar to vector..
7261     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7262     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7263   }
7264
7265   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7266     // PINSR* works with constant index.
7267     return Op;
7268   }
7269   return SDValue();
7270 }
7271
7272 SDValue
7273 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7274   MVT VT = Op.getValueType().getSimpleVT();
7275   MVT EltVT = VT.getVectorElementType();
7276
7277   DebugLoc dl = Op.getDebugLoc();
7278   SDValue N0 = Op.getOperand(0);
7279   SDValue N1 = Op.getOperand(1);
7280   SDValue N2 = Op.getOperand(2);
7281
7282   // If this is a 256-bit vector result, first extract the 128-bit vector,
7283   // insert the element into the extracted half and then place it back.
7284   if (VT.is256BitVector()) {
7285     if (!isa<ConstantSDNode>(N2))
7286       return SDValue();
7287
7288     // Get the desired 128-bit vector half.
7289     unsigned NumElems = VT.getVectorNumElements();
7290     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7291     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7292
7293     // Insert the element into the desired half.
7294     bool Upper = IdxVal >= NumElems/2;
7295     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7296                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7297
7298     // Insert the changed part back to the 256-bit vector
7299     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7300   }
7301
7302   if (Subtarget->hasSSE41())
7303     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7304
7305   if (EltVT == MVT::i8)
7306     return SDValue();
7307
7308   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7309     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7310     // as its second argument.
7311     if (N1.getValueType() != MVT::i32)
7312       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7313     if (N2.getValueType() != MVT::i32)
7314       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7315     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7316   }
7317   return SDValue();
7318 }
7319
7320 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7321   LLVMContext *Context = DAG.getContext();
7322   DebugLoc dl = Op.getDebugLoc();
7323   MVT OpVT = Op.getValueType().getSimpleVT();
7324
7325   // If this is a 256-bit vector result, first insert into a 128-bit
7326   // vector and then insert into the 256-bit vector.
7327   if (!OpVT.is128BitVector()) {
7328     // Insert into a 128-bit vector.
7329     EVT VT128 = EVT::getVectorVT(*Context,
7330                                  OpVT.getVectorElementType(),
7331                                  OpVT.getVectorNumElements() / 2);
7332
7333     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7334
7335     // Insert the 128-bit vector.
7336     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7337   }
7338
7339   if (OpVT == MVT::v1i64 &&
7340       Op.getOperand(0).getValueType() == MVT::i64)
7341     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7342
7343   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7344   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7345   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7346                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7347 }
7348
7349 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7350 // a simple subregister reference or explicit instructions to grab
7351 // upper bits of a vector.
7352 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7353                                       SelectionDAG &DAG) {
7354   if (Subtarget->hasFp256()) {
7355     DebugLoc dl = Op.getNode()->getDebugLoc();
7356     SDValue Vec = Op.getNode()->getOperand(0);
7357     SDValue Idx = Op.getNode()->getOperand(1);
7358
7359     if (Op.getNode()->getValueType(0).is128BitVector() &&
7360         Vec.getNode()->getValueType(0).is256BitVector() &&
7361         isa<ConstantSDNode>(Idx)) {
7362       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7363       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7364     }
7365   }
7366   return SDValue();
7367 }
7368
7369 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7370 // simple superregister reference or explicit instructions to insert
7371 // the upper bits of a vector.
7372 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7373                                      SelectionDAG &DAG) {
7374   if (Subtarget->hasFp256()) {
7375     DebugLoc dl = Op.getNode()->getDebugLoc();
7376     SDValue Vec = Op.getNode()->getOperand(0);
7377     SDValue SubVec = Op.getNode()->getOperand(1);
7378     SDValue Idx = Op.getNode()->getOperand(2);
7379
7380     if (Op.getNode()->getValueType(0).is256BitVector() &&
7381         SubVec.getNode()->getValueType(0).is128BitVector() &&
7382         isa<ConstantSDNode>(Idx)) {
7383       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7384       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7385     }
7386   }
7387   return SDValue();
7388 }
7389
7390 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7391 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7392 // one of the above mentioned nodes. It has to be wrapped because otherwise
7393 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7394 // be used to form addressing mode. These wrapped nodes will be selected
7395 // into MOV32ri.
7396 SDValue
7397 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7398   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(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.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7415                                              CP->getAlignment(),
7416                                              CP->getOffset(), OpFlag);
7417   DebugLoc DL = CP->getDebugLoc();
7418   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
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
7427   return Result;
7428 }
7429
7430 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7431   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
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     WrapperKind = X86ISD::WrapperRIP;
7442   else if (Subtarget->isPICStyleGOT())
7443     OpFlag = X86II::MO_GOTOFF;
7444   else if (Subtarget->isPICStyleStubPIC())
7445     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7446
7447   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7448                                           OpFlag);
7449   DebugLoc DL = JT->getDebugLoc();
7450   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7451
7452   // With PIC, the address is actually $g + Offset.
7453   if (OpFlag)
7454     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7455                          DAG.getNode(X86ISD::GlobalBaseReg,
7456                                      DebugLoc(), getPointerTy()),
7457                          Result);
7458
7459   return Result;
7460 }
7461
7462 SDValue
7463 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7464   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7465
7466   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7467   // global base reg.
7468   unsigned char OpFlag = 0;
7469   unsigned WrapperKind = X86ISD::Wrapper;
7470   CodeModel::Model M = getTargetMachine().getCodeModel();
7471
7472   if (Subtarget->isPICStyleRIPRel() &&
7473       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7474     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7475       OpFlag = X86II::MO_GOTPCREL;
7476     WrapperKind = X86ISD::WrapperRIP;
7477   } else if (Subtarget->isPICStyleGOT()) {
7478     OpFlag = X86II::MO_GOT;
7479   } else if (Subtarget->isPICStyleStubPIC()) {
7480     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7481   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7482     OpFlag = X86II::MO_DARWIN_NONLAZY;
7483   }
7484
7485   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7486
7487   DebugLoc DL = Op.getDebugLoc();
7488   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7489
7490   // With PIC, the address is actually $g + Offset.
7491   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7492       !Subtarget->is64Bit()) {
7493     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7494                          DAG.getNode(X86ISD::GlobalBaseReg,
7495                                      DebugLoc(), getPointerTy()),
7496                          Result);
7497   }
7498
7499   // For symbols that require a load from a stub to get the address, emit the
7500   // load.
7501   if (isGlobalStubReference(OpFlag))
7502     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7503                          MachinePointerInfo::getGOT(), false, false, false, 0);
7504
7505   return Result;
7506 }
7507
7508 SDValue
7509 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7510   // Create the TargetBlockAddressAddress node.
7511   unsigned char OpFlags =
7512     Subtarget->ClassifyBlockAddressReference();
7513   CodeModel::Model M = getTargetMachine().getCodeModel();
7514   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7515   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7516   DebugLoc dl = Op.getDebugLoc();
7517   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7518                                              OpFlags);
7519
7520   if (Subtarget->isPICStyleRIPRel() &&
7521       (M == CodeModel::Small || M == CodeModel::Kernel))
7522     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7523   else
7524     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7525
7526   // With PIC, the address is actually $g + Offset.
7527   if (isGlobalRelativeToPICBase(OpFlags)) {
7528     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7529                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7530                          Result);
7531   }
7532
7533   return Result;
7534 }
7535
7536 SDValue
7537 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7538                                       int64_t Offset, SelectionDAG &DAG) const {
7539   // Create the TargetGlobalAddress node, folding in the constant
7540   // offset if it is legal.
7541   unsigned char OpFlags =
7542     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7543   CodeModel::Model M = getTargetMachine().getCodeModel();
7544   SDValue Result;
7545   if (OpFlags == X86II::MO_NO_FLAG &&
7546       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7547     // A direct static reference to a global.
7548     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7549     Offset = 0;
7550   } else {
7551     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7552   }
7553
7554   if (Subtarget->isPICStyleRIPRel() &&
7555       (M == CodeModel::Small || M == CodeModel::Kernel))
7556     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7557   else
7558     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7559
7560   // With PIC, the address is actually $g + Offset.
7561   if (isGlobalRelativeToPICBase(OpFlags)) {
7562     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7563                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7564                          Result);
7565   }
7566
7567   // For globals that require a load from a stub to get the address, emit the
7568   // load.
7569   if (isGlobalStubReference(OpFlags))
7570     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7571                          MachinePointerInfo::getGOT(), false, false, false, 0);
7572
7573   // If there was a non-zero offset that we didn't fold, create an explicit
7574   // addition for it.
7575   if (Offset != 0)
7576     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7577                          DAG.getConstant(Offset, getPointerTy()));
7578
7579   return Result;
7580 }
7581
7582 SDValue
7583 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7584   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7585   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7586   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7587 }
7588
7589 static SDValue
7590 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7591            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7592            unsigned char OperandFlags, bool LocalDynamic = false) {
7593   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7594   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7595   DebugLoc dl = GA->getDebugLoc();
7596   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7597                                            GA->getValueType(0),
7598                                            GA->getOffset(),
7599                                            OperandFlags);
7600
7601   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7602                                            : X86ISD::TLSADDR;
7603
7604   if (InFlag) {
7605     SDValue Ops[] = { Chain,  TGA, *InFlag };
7606     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7607   } else {
7608     SDValue Ops[]  = { Chain, TGA };
7609     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7610   }
7611
7612   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7613   MFI->setAdjustsStack(true);
7614
7615   SDValue Flag = Chain.getValue(1);
7616   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7617 }
7618
7619 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7620 static SDValue
7621 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7622                                 const EVT PtrVT) {
7623   SDValue InFlag;
7624   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7625   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7626                                    DAG.getNode(X86ISD::GlobalBaseReg,
7627                                                DebugLoc(), PtrVT), InFlag);
7628   InFlag = Chain.getValue(1);
7629
7630   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7631 }
7632
7633 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7634 static SDValue
7635 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7636                                 const EVT PtrVT) {
7637   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7638                     X86::RAX, X86II::MO_TLSGD);
7639 }
7640
7641 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7642                                            SelectionDAG &DAG,
7643                                            const EVT PtrVT,
7644                                            bool is64Bit) {
7645   DebugLoc dl = GA->getDebugLoc();
7646
7647   // Get the start address of the TLS block for this module.
7648   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7649       .getInfo<X86MachineFunctionInfo>();
7650   MFI->incNumLocalDynamicTLSAccesses();
7651
7652   SDValue Base;
7653   if (is64Bit) {
7654     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7655                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7656   } else {
7657     SDValue InFlag;
7658     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7659         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7660     InFlag = Chain.getValue(1);
7661     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7662                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7663   }
7664
7665   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7666   // of Base.
7667
7668   // Build x@dtpoff.
7669   unsigned char OperandFlags = X86II::MO_DTPOFF;
7670   unsigned WrapperKind = X86ISD::Wrapper;
7671   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7672                                            GA->getValueType(0),
7673                                            GA->getOffset(), OperandFlags);
7674   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7675
7676   // Add x@dtpoff with the base.
7677   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7678 }
7679
7680 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7681 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7682                                    const EVT PtrVT, TLSModel::Model model,
7683                                    bool is64Bit, bool isPIC) {
7684   DebugLoc dl = GA->getDebugLoc();
7685
7686   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7687   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7688                                                          is64Bit ? 257 : 256));
7689
7690   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7691                                       DAG.getIntPtrConstant(0),
7692                                       MachinePointerInfo(Ptr),
7693                                       false, false, false, 0);
7694
7695   unsigned char OperandFlags = 0;
7696   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7697   // initialexec.
7698   unsigned WrapperKind = X86ISD::Wrapper;
7699   if (model == TLSModel::LocalExec) {
7700     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7701   } else if (model == TLSModel::InitialExec) {
7702     if (is64Bit) {
7703       OperandFlags = X86II::MO_GOTTPOFF;
7704       WrapperKind = X86ISD::WrapperRIP;
7705     } else {
7706       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7707     }
7708   } else {
7709     llvm_unreachable("Unexpected model");
7710   }
7711
7712   // emit "addl x@ntpoff,%eax" (local exec)
7713   // or "addl x@indntpoff,%eax" (initial exec)
7714   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7715   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7716                                            GA->getValueType(0),
7717                                            GA->getOffset(), OperandFlags);
7718   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7719
7720   if (model == TLSModel::InitialExec) {
7721     if (isPIC && !is64Bit) {
7722       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7723                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7724                            Offset);
7725     }
7726
7727     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7728                          MachinePointerInfo::getGOT(), false, false, false,
7729                          0);
7730   }
7731
7732   // The address of the thread local variable is the add of the thread
7733   // pointer with the offset of the variable.
7734   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7735 }
7736
7737 SDValue
7738 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7739
7740   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7741   const GlobalValue *GV = GA->getGlobal();
7742
7743   if (Subtarget->isTargetELF()) {
7744     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7745
7746     switch (model) {
7747       case TLSModel::GeneralDynamic:
7748         if (Subtarget->is64Bit())
7749           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7750         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7751       case TLSModel::LocalDynamic:
7752         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7753                                            Subtarget->is64Bit());
7754       case TLSModel::InitialExec:
7755       case TLSModel::LocalExec:
7756         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7757                                    Subtarget->is64Bit(),
7758                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7759     }
7760     llvm_unreachable("Unknown TLS model.");
7761   }
7762
7763   if (Subtarget->isTargetDarwin()) {
7764     // Darwin only has one model of TLS.  Lower to that.
7765     unsigned char OpFlag = 0;
7766     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7767                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7768
7769     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7770     // global base reg.
7771     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7772                   !Subtarget->is64Bit();
7773     if (PIC32)
7774       OpFlag = X86II::MO_TLVP_PIC_BASE;
7775     else
7776       OpFlag = X86II::MO_TLVP;
7777     DebugLoc DL = Op.getDebugLoc();
7778     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7779                                                 GA->getValueType(0),
7780                                                 GA->getOffset(), OpFlag);
7781     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7782
7783     // With PIC32, the address is actually $g + Offset.
7784     if (PIC32)
7785       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7786                            DAG.getNode(X86ISD::GlobalBaseReg,
7787                                        DebugLoc(), getPointerTy()),
7788                            Offset);
7789
7790     // Lowering the machine isd will make sure everything is in the right
7791     // location.
7792     SDValue Chain = DAG.getEntryNode();
7793     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7794     SDValue Args[] = { Chain, Offset };
7795     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7796
7797     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7798     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7799     MFI->setAdjustsStack(true);
7800
7801     // And our return value (tls address) is in the standard call return value
7802     // location.
7803     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7804     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7805                               Chain.getValue(1));
7806   }
7807
7808   if (Subtarget->isTargetWindows()) {
7809     // Just use the implicit TLS architecture
7810     // Need to generate someting similar to:
7811     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7812     //                                  ; from TEB
7813     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7814     //   mov     rcx, qword [rdx+rcx*8]
7815     //   mov     eax, .tls$:tlsvar
7816     //   [rax+rcx] contains the address
7817     // Windows 64bit: gs:0x58
7818     // Windows 32bit: fs:__tls_array
7819
7820     // If GV is an alias then use the aliasee for determining
7821     // thread-localness.
7822     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7823       GV = GA->resolveAliasedGlobal(false);
7824     DebugLoc dl = GA->getDebugLoc();
7825     SDValue Chain = DAG.getEntryNode();
7826
7827     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7828     // %gs:0x58 (64-bit).
7829     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7830                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7831                                                              256)
7832                                         : Type::getInt32PtrTy(*DAG.getContext(),
7833                                                               257));
7834
7835     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7836                                         Subtarget->is64Bit()
7837                                         ? DAG.getIntPtrConstant(0x58)
7838                                         : DAG.getExternalSymbol("_tls_array",
7839                                                                 getPointerTy()),
7840                                         MachinePointerInfo(Ptr),
7841                                         false, false, false, 0);
7842
7843     // Load the _tls_index variable
7844     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7845     if (Subtarget->is64Bit())
7846       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7847                            IDX, MachinePointerInfo(), MVT::i32,
7848                            false, false, 0);
7849     else
7850       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7851                         false, false, false, 0);
7852
7853     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7854                                     getPointerTy());
7855     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7856
7857     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7858     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7859                       false, false, false, 0);
7860
7861     // Get the offset of start of .tls section
7862     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7863                                              GA->getValueType(0),
7864                                              GA->getOffset(), X86II::MO_SECREL);
7865     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7866
7867     // The address of the thread local variable is the add of the thread
7868     // pointer with the offset of the variable.
7869     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7870   }
7871
7872   llvm_unreachable("TLS not implemented for this target.");
7873 }
7874
7875 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7876 /// and take a 2 x i32 value to shift plus a shift amount.
7877 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7878   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7879   EVT VT = Op.getValueType();
7880   unsigned VTBits = VT.getSizeInBits();
7881   DebugLoc dl = Op.getDebugLoc();
7882   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7883   SDValue ShOpLo = Op.getOperand(0);
7884   SDValue ShOpHi = Op.getOperand(1);
7885   SDValue ShAmt  = Op.getOperand(2);
7886   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7887                                      DAG.getConstant(VTBits - 1, MVT::i8))
7888                        : DAG.getConstant(0, VT);
7889
7890   SDValue Tmp2, Tmp3;
7891   if (Op.getOpcode() == ISD::SHL_PARTS) {
7892     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7893     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7894   } else {
7895     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7896     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7897   }
7898
7899   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7900                                 DAG.getConstant(VTBits, MVT::i8));
7901   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7902                              AndNode, DAG.getConstant(0, MVT::i8));
7903
7904   SDValue Hi, Lo;
7905   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7906   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7907   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7908
7909   if (Op.getOpcode() == ISD::SHL_PARTS) {
7910     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7911     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7912   } else {
7913     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7914     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7915   }
7916
7917   SDValue Ops[2] = { Lo, Hi };
7918   return DAG.getMergeValues(Ops, 2, dl);
7919 }
7920
7921 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7922                                            SelectionDAG &DAG) const {
7923   EVT SrcVT = Op.getOperand(0).getValueType();
7924
7925   if (SrcVT.isVector())
7926     return SDValue();
7927
7928   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7929          "Unknown SINT_TO_FP to lower!");
7930
7931   // These are really Legal; return the operand so the caller accepts it as
7932   // Legal.
7933   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7934     return Op;
7935   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7936       Subtarget->is64Bit()) {
7937     return Op;
7938   }
7939
7940   DebugLoc dl = Op.getDebugLoc();
7941   unsigned Size = SrcVT.getSizeInBits()/8;
7942   MachineFunction &MF = DAG.getMachineFunction();
7943   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7944   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7945   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7946                                StackSlot,
7947                                MachinePointerInfo::getFixedStack(SSFI),
7948                                false, false, 0);
7949   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7950 }
7951
7952 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7953                                      SDValue StackSlot,
7954                                      SelectionDAG &DAG) const {
7955   // Build the FILD
7956   DebugLoc DL = Op.getDebugLoc();
7957   SDVTList Tys;
7958   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7959   if (useSSE)
7960     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7961   else
7962     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7963
7964   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7965
7966   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7967   MachineMemOperand *MMO;
7968   if (FI) {
7969     int SSFI = FI->getIndex();
7970     MMO =
7971       DAG.getMachineFunction()
7972       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7973                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7974   } else {
7975     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7976     StackSlot = StackSlot.getOperand(1);
7977   }
7978   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7979   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7980                                            X86ISD::FILD, DL,
7981                                            Tys, Ops, array_lengthof(Ops),
7982                                            SrcVT, MMO);
7983
7984   if (useSSE) {
7985     Chain = Result.getValue(1);
7986     SDValue InFlag = Result.getValue(2);
7987
7988     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7989     // shouldn't be necessary except that RFP cannot be live across
7990     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7991     MachineFunction &MF = DAG.getMachineFunction();
7992     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7993     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7994     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7995     Tys = DAG.getVTList(MVT::Other);
7996     SDValue Ops[] = {
7997       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7998     };
7999     MachineMemOperand *MMO =
8000       DAG.getMachineFunction()
8001       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8002                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8003
8004     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8005                                     Ops, array_lengthof(Ops),
8006                                     Op.getValueType(), MMO);
8007     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8008                          MachinePointerInfo::getFixedStack(SSFI),
8009                          false, false, false, 0);
8010   }
8011
8012   return Result;
8013 }
8014
8015 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8016 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8017                                                SelectionDAG &DAG) const {
8018   // This algorithm is not obvious. Here it is what we're trying to output:
8019   /*
8020      movq       %rax,  %xmm0
8021      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8022      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8023      #ifdef __SSE3__
8024        haddpd   %xmm0, %xmm0
8025      #else
8026        pshufd   $0x4e, %xmm0, %xmm1
8027        addpd    %xmm1, %xmm0
8028      #endif
8029   */
8030
8031   DebugLoc dl = Op.getDebugLoc();
8032   LLVMContext *Context = DAG.getContext();
8033
8034   // Build some magic constants.
8035   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8036   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8037   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8038
8039   SmallVector<Constant*,2> CV1;
8040   CV1.push_back(
8041     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8042                                       APInt(64, 0x4330000000000000ULL))));
8043   CV1.push_back(
8044     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8045                                       APInt(64, 0x4530000000000000ULL))));
8046   Constant *C1 = ConstantVector::get(CV1);
8047   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8048
8049   // Load the 64-bit value into an XMM register.
8050   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8051                             Op.getOperand(0));
8052   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8053                               MachinePointerInfo::getConstantPool(),
8054                               false, false, false, 16);
8055   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8056                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8057                               CLod0);
8058
8059   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8060                               MachinePointerInfo::getConstantPool(),
8061                               false, false, false, 16);
8062   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8063   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8064   SDValue Result;
8065
8066   if (Subtarget->hasSSE3()) {
8067     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8068     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8069   } else {
8070     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8071     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8072                                            S2F, 0x4E, DAG);
8073     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8074                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8075                          Sub);
8076   }
8077
8078   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8079                      DAG.getIntPtrConstant(0));
8080 }
8081
8082 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8083 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8084                                                SelectionDAG &DAG) const {
8085   DebugLoc dl = Op.getDebugLoc();
8086   // FP constant to bias correct the final result.
8087   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8088                                    MVT::f64);
8089
8090   // Load the 32-bit value into an XMM register.
8091   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8092                              Op.getOperand(0));
8093
8094   // Zero out the upper parts of the register.
8095   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8096
8097   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8098                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8099                      DAG.getIntPtrConstant(0));
8100
8101   // Or the load with the bias.
8102   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8103                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8104                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8105                                                    MVT::v2f64, Load)),
8106                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8107                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8108                                                    MVT::v2f64, Bias)));
8109   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8110                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8111                    DAG.getIntPtrConstant(0));
8112
8113   // Subtract the bias.
8114   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8115
8116   // Handle final rounding.
8117   EVT DestVT = Op.getValueType();
8118
8119   if (DestVT.bitsLT(MVT::f64))
8120     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8121                        DAG.getIntPtrConstant(0));
8122   if (DestVT.bitsGT(MVT::f64))
8123     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8124
8125   // Handle final rounding.
8126   return Sub;
8127 }
8128
8129 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8130                                                SelectionDAG &DAG) const {
8131   SDValue N0 = Op.getOperand(0);
8132   EVT SVT = N0.getValueType();
8133   DebugLoc dl = Op.getDebugLoc();
8134
8135   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8136           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8137          "Custom UINT_TO_FP is not supported!");
8138
8139   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8140                              SVT.getVectorNumElements());
8141   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8142                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8143 }
8144
8145 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8146                                            SelectionDAG &DAG) const {
8147   SDValue N0 = Op.getOperand(0);
8148   DebugLoc dl = Op.getDebugLoc();
8149
8150   if (Op.getValueType().isVector())
8151     return lowerUINT_TO_FP_vec(Op, DAG);
8152
8153   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8154   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8155   // the optimization here.
8156   if (DAG.SignBitIsZero(N0))
8157     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8158
8159   EVT SrcVT = N0.getValueType();
8160   EVT DstVT = Op.getValueType();
8161   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8162     return LowerUINT_TO_FP_i64(Op, DAG);
8163   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8164     return LowerUINT_TO_FP_i32(Op, DAG);
8165   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8166     return SDValue();
8167
8168   // Make a 64-bit buffer, and use it to build an FILD.
8169   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8170   if (SrcVT == MVT::i32) {
8171     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8172     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8173                                      getPointerTy(), StackSlot, WordOff);
8174     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8175                                   StackSlot, MachinePointerInfo(),
8176                                   false, false, 0);
8177     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8178                                   OffsetSlot, MachinePointerInfo(),
8179                                   false, false, 0);
8180     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8181     return Fild;
8182   }
8183
8184   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8185   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8186                                StackSlot, MachinePointerInfo(),
8187                                false, false, 0);
8188   // For i64 source, we need to add the appropriate power of 2 if the input
8189   // was negative.  This is the same as the optimization in
8190   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8191   // we must be careful to do the computation in x87 extended precision, not
8192   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8193   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8194   MachineMemOperand *MMO =
8195     DAG.getMachineFunction()
8196     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8197                           MachineMemOperand::MOLoad, 8, 8);
8198
8199   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8200   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8201   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8202                                          MVT::i64, MMO);
8203
8204   APInt FF(32, 0x5F800000ULL);
8205
8206   // Check whether the sign bit is set.
8207   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8208                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8209                                  ISD::SETLT);
8210
8211   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8212   SDValue FudgePtr = DAG.getConstantPool(
8213                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8214                                          getPointerTy());
8215
8216   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8217   SDValue Zero = DAG.getIntPtrConstant(0);
8218   SDValue Four = DAG.getIntPtrConstant(4);
8219   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8220                                Zero, Four);
8221   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8222
8223   // Load the value out, extending it from f32 to f80.
8224   // FIXME: Avoid the extend by constructing the right constant pool?
8225   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8226                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8227                                  MVT::f32, false, false, 4);
8228   // Extend everything to 80 bits to force it to be done on x87.
8229   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8230   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8231 }
8232
8233 std::pair<SDValue,SDValue>
8234 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8235                                     bool IsSigned, bool IsReplace) const {
8236   DebugLoc DL = Op.getDebugLoc();
8237
8238   EVT DstTy = Op.getValueType();
8239
8240   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8241     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8242     DstTy = MVT::i64;
8243   }
8244
8245   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8246          DstTy.getSimpleVT() >= MVT::i16 &&
8247          "Unknown FP_TO_INT to lower!");
8248
8249   // These are really Legal.
8250   if (DstTy == MVT::i32 &&
8251       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8252     return std::make_pair(SDValue(), SDValue());
8253   if (Subtarget->is64Bit() &&
8254       DstTy == MVT::i64 &&
8255       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8256     return std::make_pair(SDValue(), SDValue());
8257
8258   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8259   // stack slot, or into the FTOL runtime function.
8260   MachineFunction &MF = DAG.getMachineFunction();
8261   unsigned MemSize = DstTy.getSizeInBits()/8;
8262   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8263   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8264
8265   unsigned Opc;
8266   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8267     Opc = X86ISD::WIN_FTOL;
8268   else
8269     switch (DstTy.getSimpleVT().SimpleTy) {
8270     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8271     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8272     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8273     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8274     }
8275
8276   SDValue Chain = DAG.getEntryNode();
8277   SDValue Value = Op.getOperand(0);
8278   EVT TheVT = Op.getOperand(0).getValueType();
8279   // FIXME This causes a redundant load/store if the SSE-class value is already
8280   // in memory, such as if it is on the callstack.
8281   if (isScalarFPTypeInSSEReg(TheVT)) {
8282     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8283     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8284                          MachinePointerInfo::getFixedStack(SSFI),
8285                          false, false, 0);
8286     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8287     SDValue Ops[] = {
8288       Chain, StackSlot, DAG.getValueType(TheVT)
8289     };
8290
8291     MachineMemOperand *MMO =
8292       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8293                               MachineMemOperand::MOLoad, MemSize, MemSize);
8294     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8295                                     DstTy, MMO);
8296     Chain = Value.getValue(1);
8297     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8298     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8299   }
8300
8301   MachineMemOperand *MMO =
8302     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8303                             MachineMemOperand::MOStore, MemSize, MemSize);
8304
8305   if (Opc != X86ISD::WIN_FTOL) {
8306     // Build the FP_TO_INT*_IN_MEM
8307     SDValue Ops[] = { Chain, Value, StackSlot };
8308     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8309                                            Ops, 3, DstTy, MMO);
8310     return std::make_pair(FIST, StackSlot);
8311   } else {
8312     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8313       DAG.getVTList(MVT::Other, MVT::Glue),
8314       Chain, Value);
8315     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8316       MVT::i32, ftol.getValue(1));
8317     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8318       MVT::i32, eax.getValue(2));
8319     SDValue Ops[] = { eax, edx };
8320     SDValue pair = IsReplace
8321       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8322       : DAG.getMergeValues(Ops, 2, DL);
8323     return std::make_pair(pair, SDValue());
8324   }
8325 }
8326
8327 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8328                               const X86Subtarget *Subtarget) {
8329   MVT VT = Op->getValueType(0).getSimpleVT();
8330   SDValue In = Op->getOperand(0);
8331   MVT InVT = In.getValueType().getSimpleVT();
8332   DebugLoc dl = Op->getDebugLoc();
8333
8334   // Optimize vectors in AVX mode:
8335   //
8336   //   v8i16 -> v8i32
8337   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8338   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8339   //   Concat upper and lower parts.
8340   //
8341   //   v4i32 -> v4i64
8342   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8343   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8344   //   Concat upper and lower parts.
8345   //
8346
8347   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8348       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8349     return SDValue();
8350
8351   if (Subtarget->hasInt256())
8352     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8353
8354   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8355   SDValue Undef = DAG.getUNDEF(InVT);
8356   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8357   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8358   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8359
8360   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8361                              VT.getVectorNumElements()/2);
8362
8363   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8364   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8365
8366   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8367 }
8368
8369 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8370                                            SelectionDAG &DAG) const {
8371   if (Subtarget->hasFp256()) {
8372     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8373     if (Res.getNode())
8374       return Res;
8375   }
8376
8377   return SDValue();
8378 }
8379 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8380                                             SelectionDAG &DAG) const {
8381   DebugLoc DL = Op.getDebugLoc();
8382   MVT VT = Op.getValueType().getSimpleVT();
8383   SDValue In = Op.getOperand(0);
8384   MVT SVT = In.getValueType().getSimpleVT();
8385
8386   if (Subtarget->hasFp256()) {
8387     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8388     if (Res.getNode())
8389       return Res;
8390   }
8391
8392   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8393       VT.getVectorNumElements() != SVT.getVectorNumElements())
8394     return SDValue();
8395
8396   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8397
8398   // AVX2 has better support of integer extending.
8399   if (Subtarget->hasInt256())
8400     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8401
8402   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8403   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8404   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8405                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8406                                                 DAG.getUNDEF(MVT::v8i16),
8407                                                 &Mask[0]));
8408
8409   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8410 }
8411
8412 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8413   DebugLoc DL = Op.getDebugLoc();
8414   MVT VT = Op.getValueType().getSimpleVT();
8415   SDValue In = Op.getOperand(0);
8416   MVT SVT = In.getValueType().getSimpleVT();
8417
8418   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8419     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8420     if (Subtarget->hasInt256()) {
8421       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8422       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8423       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8424                                 ShufMask);
8425       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8426                          DAG.getIntPtrConstant(0));
8427     }
8428
8429     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8430     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8431                                DAG.getIntPtrConstant(0));
8432     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8433                                DAG.getIntPtrConstant(2));
8434
8435     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8436     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8437
8438     // The PSHUFD mask:
8439     static const int ShufMask1[] = {0, 2, 0, 0};
8440     SDValue Undef = DAG.getUNDEF(VT);
8441     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8442     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8443
8444     // The MOVLHPS mask:
8445     static const int ShufMask2[] = {0, 1, 4, 5};
8446     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8447   }
8448
8449   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8450     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8451     if (Subtarget->hasInt256()) {
8452       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8453
8454       SmallVector<SDValue,32> pshufbMask;
8455       for (unsigned i = 0; i < 2; ++i) {
8456         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8457         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8458         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8459         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8460         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8461         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8462         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8463         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8464         for (unsigned j = 0; j < 8; ++j)
8465           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8466       }
8467       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8468                                &pshufbMask[0], 32);
8469       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8470       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8471
8472       static const int ShufMask[] = {0,  2,  -1,  -1};
8473       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8474                                 &ShufMask[0]);
8475       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8476                        DAG.getIntPtrConstant(0));
8477       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8478     }
8479
8480     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8481                                DAG.getIntPtrConstant(0));
8482
8483     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8484                                DAG.getIntPtrConstant(4));
8485
8486     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8487     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8488
8489     // The PSHUFB mask:
8490     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8491                                    -1, -1, -1, -1, -1, -1, -1, -1};
8492
8493     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8494     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8495     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8496
8497     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8498     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8499
8500     // The MOVLHPS Mask:
8501     static const int ShufMask2[] = {0, 1, 4, 5};
8502     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8503     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8504   }
8505
8506   // Handle truncation of V256 to V128 using shuffles.
8507   if (!VT.is128BitVector() || !SVT.is256BitVector())
8508     return SDValue();
8509
8510   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8511          "Invalid op");
8512   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8513
8514   unsigned NumElems = VT.getVectorNumElements();
8515   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8516                              NumElems * 2);
8517
8518   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8519   // Prepare truncation shuffle mask
8520   for (unsigned i = 0; i != NumElems; ++i)
8521     MaskVec[i] = i * 2;
8522   SDValue V = DAG.getVectorShuffle(NVT, DL,
8523                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8524                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8525   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8526                      DAG.getIntPtrConstant(0));
8527 }
8528
8529 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8530                                            SelectionDAG &DAG) const {
8531   MVT VT = Op.getValueType().getSimpleVT();
8532   if (VT.isVector()) {
8533     if (VT == MVT::v8i16)
8534       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8535                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8536                                      MVT::v8i32, Op.getOperand(0)));
8537     return SDValue();
8538   }
8539
8540   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8541     /*IsSigned=*/ true, /*IsReplace=*/ false);
8542   SDValue FIST = Vals.first, StackSlot = Vals.second;
8543   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8544   if (FIST.getNode() == 0) return Op;
8545
8546   if (StackSlot.getNode())
8547     // Load the result.
8548     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8549                        FIST, StackSlot, MachinePointerInfo(),
8550                        false, false, false, 0);
8551
8552   // The node is the result.
8553   return FIST;
8554 }
8555
8556 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8557                                            SelectionDAG &DAG) const {
8558   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8559     /*IsSigned=*/ false, /*IsReplace=*/ false);
8560   SDValue FIST = Vals.first, StackSlot = Vals.second;
8561   assert(FIST.getNode() && "Unexpected failure");
8562
8563   if (StackSlot.getNode())
8564     // Load the result.
8565     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8566                        FIST, StackSlot, MachinePointerInfo(),
8567                        false, false, false, 0);
8568
8569   // The node is the result.
8570   return FIST;
8571 }
8572
8573 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8574   DebugLoc DL = Op.getDebugLoc();
8575   MVT VT = Op.getValueType().getSimpleVT();
8576   SDValue In = Op.getOperand(0);
8577   MVT SVT = In.getValueType().getSimpleVT();
8578
8579   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8580
8581   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8582                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8583                                  In, DAG.getUNDEF(SVT)));
8584 }
8585
8586 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8587   LLVMContext *Context = DAG.getContext();
8588   DebugLoc dl = Op.getDebugLoc();
8589   MVT VT = Op.getValueType().getSimpleVT();
8590   MVT EltVT = VT;
8591   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8592   if (VT.isVector()) {
8593     EltVT = VT.getVectorElementType();
8594     NumElts = VT.getVectorNumElements();
8595   }
8596   Constant *C;
8597   if (EltVT == MVT::f64)
8598     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8599                                           APInt(64, ~(1ULL << 63))));
8600   else
8601     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8602                                           APInt(32, ~(1U << 31))));
8603   C = ConstantVector::getSplat(NumElts, C);
8604   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8605   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8606   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8607                              MachinePointerInfo::getConstantPool(),
8608                              false, false, false, Alignment);
8609   if (VT.isVector()) {
8610     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8611     return DAG.getNode(ISD::BITCAST, dl, VT,
8612                        DAG.getNode(ISD::AND, dl, ANDVT,
8613                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8614                                                Op.getOperand(0)),
8615                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8616   }
8617   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8618 }
8619
8620 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8621   LLVMContext *Context = DAG.getContext();
8622   DebugLoc dl = Op.getDebugLoc();
8623   MVT VT = Op.getValueType().getSimpleVT();
8624   MVT EltVT = VT;
8625   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8626   if (VT.isVector()) {
8627     EltVT = VT.getVectorElementType();
8628     NumElts = VT.getVectorNumElements();
8629   }
8630   Constant *C;
8631   if (EltVT == MVT::f64)
8632     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8633                                           APInt(64, 1ULL << 63)));
8634   else
8635     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8636                                           APInt(32, 1U << 31)));
8637   C = ConstantVector::getSplat(NumElts, C);
8638   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8639   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8640   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8641                              MachinePointerInfo::getConstantPool(),
8642                              false, false, false, Alignment);
8643   if (VT.isVector()) {
8644     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8645     return DAG.getNode(ISD::BITCAST, dl, VT,
8646                        DAG.getNode(ISD::XOR, dl, XORVT,
8647                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8648                                                Op.getOperand(0)),
8649                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8650   }
8651
8652   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8653 }
8654
8655 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8656   LLVMContext *Context = DAG.getContext();
8657   SDValue Op0 = Op.getOperand(0);
8658   SDValue Op1 = Op.getOperand(1);
8659   DebugLoc dl = Op.getDebugLoc();
8660   MVT VT = Op.getValueType().getSimpleVT();
8661   MVT SrcVT = Op1.getValueType().getSimpleVT();
8662
8663   // If second operand is smaller, extend it first.
8664   if (SrcVT.bitsLT(VT)) {
8665     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8666     SrcVT = VT;
8667   }
8668   // And if it is bigger, shrink it first.
8669   if (SrcVT.bitsGT(VT)) {
8670     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8671     SrcVT = VT;
8672   }
8673
8674   // At this point the operands and the result should have the same
8675   // type, and that won't be f80 since that is not custom lowered.
8676
8677   // First get the sign bit of second operand.
8678   SmallVector<Constant*,4> CV;
8679   if (SrcVT == MVT::f64) {
8680     const fltSemantics &Sem = APFloat::IEEEdouble;
8681     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8682     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8683   } else {
8684     const fltSemantics &Sem = APFloat::IEEEsingle;
8685     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8686     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8687     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8688     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8689   }
8690   Constant *C = ConstantVector::get(CV);
8691   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8692   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8693                               MachinePointerInfo::getConstantPool(),
8694                               false, false, false, 16);
8695   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8696
8697   // Shift sign bit right or left if the two operands have different types.
8698   if (SrcVT.bitsGT(VT)) {
8699     // Op0 is MVT::f32, Op1 is MVT::f64.
8700     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8701     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8702                           DAG.getConstant(32, MVT::i32));
8703     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8704     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8705                           DAG.getIntPtrConstant(0));
8706   }
8707
8708   // Clear first operand sign bit.
8709   CV.clear();
8710   if (VT == MVT::f64) {
8711     const fltSemantics &Sem = APFloat::IEEEdouble;
8712     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8713                                                    APInt(64, ~(1ULL << 63)))));
8714     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8715   } else {
8716     const fltSemantics &Sem = APFloat::IEEEsingle;
8717     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8718                                                    APInt(32, ~(1U << 31)))));
8719     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8720     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8721     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8722   }
8723   C = ConstantVector::get(CV);
8724   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8725   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8726                               MachinePointerInfo::getConstantPool(),
8727                               false, false, false, 16);
8728   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8729
8730   // Or the value with the sign bit.
8731   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8732 }
8733
8734 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8735   SDValue N0 = Op.getOperand(0);
8736   DebugLoc dl = Op.getDebugLoc();
8737   MVT VT = Op.getValueType().getSimpleVT();
8738
8739   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8740   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8741                                   DAG.getConstant(1, VT));
8742   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8743 }
8744
8745 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8746 //
8747 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8748                                                   SelectionDAG &DAG) const {
8749   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8750
8751   if (!Subtarget->hasSSE41())
8752     return SDValue();
8753
8754   if (!Op->hasOneUse())
8755     return SDValue();
8756
8757   SDNode *N = Op.getNode();
8758   DebugLoc DL = N->getDebugLoc();
8759
8760   SmallVector<SDValue, 8> Opnds;
8761   DenseMap<SDValue, unsigned> VecInMap;
8762   EVT VT = MVT::Other;
8763
8764   // Recognize a special case where a vector is casted into wide integer to
8765   // test all 0s.
8766   Opnds.push_back(N->getOperand(0));
8767   Opnds.push_back(N->getOperand(1));
8768
8769   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8770     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8771     // BFS traverse all OR'd operands.
8772     if (I->getOpcode() == ISD::OR) {
8773       Opnds.push_back(I->getOperand(0));
8774       Opnds.push_back(I->getOperand(1));
8775       // Re-evaluate the number of nodes to be traversed.
8776       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8777       continue;
8778     }
8779
8780     // Quit if a non-EXTRACT_VECTOR_ELT
8781     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8782       return SDValue();
8783
8784     // Quit if without a constant index.
8785     SDValue Idx = I->getOperand(1);
8786     if (!isa<ConstantSDNode>(Idx))
8787       return SDValue();
8788
8789     SDValue ExtractedFromVec = I->getOperand(0);
8790     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8791     if (M == VecInMap.end()) {
8792       VT = ExtractedFromVec.getValueType();
8793       // Quit if not 128/256-bit vector.
8794       if (!VT.is128BitVector() && !VT.is256BitVector())
8795         return SDValue();
8796       // Quit if not the same type.
8797       if (VecInMap.begin() != VecInMap.end() &&
8798           VT != VecInMap.begin()->first.getValueType())
8799         return SDValue();
8800       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8801     }
8802     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8803   }
8804
8805   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8806          "Not extracted from 128-/256-bit vector.");
8807
8808   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8809   SmallVector<SDValue, 8> VecIns;
8810
8811   for (DenseMap<SDValue, unsigned>::const_iterator
8812         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8813     // Quit if not all elements are used.
8814     if (I->second != FullMask)
8815       return SDValue();
8816     VecIns.push_back(I->first);
8817   }
8818
8819   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8820
8821   // Cast all vectors into TestVT for PTEST.
8822   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8823     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8824
8825   // If more than one full vectors are evaluated, OR them first before PTEST.
8826   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8827     // Each iteration will OR 2 nodes and append the result until there is only
8828     // 1 node left, i.e. the final OR'd value of all vectors.
8829     SDValue LHS = VecIns[Slot];
8830     SDValue RHS = VecIns[Slot + 1];
8831     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8832   }
8833
8834   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8835                      VecIns.back(), VecIns.back());
8836 }
8837
8838 /// Emit nodes that will be selected as "test Op0,Op0", or something
8839 /// equivalent.
8840 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8841                                     SelectionDAG &DAG) const {
8842   DebugLoc dl = Op.getDebugLoc();
8843
8844   // CF and OF aren't always set the way we want. Determine which
8845   // of these we need.
8846   bool NeedCF = false;
8847   bool NeedOF = false;
8848   switch (X86CC) {
8849   default: break;
8850   case X86::COND_A: case X86::COND_AE:
8851   case X86::COND_B: case X86::COND_BE:
8852     NeedCF = true;
8853     break;
8854   case X86::COND_G: case X86::COND_GE:
8855   case X86::COND_L: case X86::COND_LE:
8856   case X86::COND_O: case X86::COND_NO:
8857     NeedOF = true;
8858     break;
8859   }
8860
8861   // See if we can use the EFLAGS value from the operand instead of
8862   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8863   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8864   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8865     // Emit a CMP with 0, which is the TEST pattern.
8866     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8867                        DAG.getConstant(0, Op.getValueType()));
8868
8869   unsigned Opcode = 0;
8870   unsigned NumOperands = 0;
8871
8872   // Truncate operations may prevent the merge of the SETCC instruction
8873   // and the arithmetic intruction before it. Attempt to truncate the operands
8874   // of the arithmetic instruction and use a reduced bit-width instruction.
8875   bool NeedTruncation = false;
8876   SDValue ArithOp = Op;
8877   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8878     SDValue Arith = Op->getOperand(0);
8879     // Both the trunc and the arithmetic op need to have one user each.
8880     if (Arith->hasOneUse())
8881       switch (Arith.getOpcode()) {
8882         default: break;
8883         case ISD::ADD:
8884         case ISD::SUB:
8885         case ISD::AND:
8886         case ISD::OR:
8887         case ISD::XOR: {
8888           NeedTruncation = true;
8889           ArithOp = Arith;
8890         }
8891       }
8892   }
8893
8894   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8895   // which may be the result of a CAST.  We use the variable 'Op', which is the
8896   // non-casted variable when we check for possible users.
8897   switch (ArithOp.getOpcode()) {
8898   case ISD::ADD:
8899     // Due to an isel shortcoming, be conservative if this add is likely to be
8900     // selected as part of a load-modify-store instruction. When the root node
8901     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8902     // uses of other nodes in the match, such as the ADD in this case. This
8903     // leads to the ADD being left around and reselected, with the result being
8904     // two adds in the output.  Alas, even if none our users are stores, that
8905     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8906     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8907     // climbing the DAG back to the root, and it doesn't seem to be worth the
8908     // effort.
8909     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8910          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8911       if (UI->getOpcode() != ISD::CopyToReg &&
8912           UI->getOpcode() != ISD::SETCC &&
8913           UI->getOpcode() != ISD::STORE)
8914         goto default_case;
8915
8916     if (ConstantSDNode *C =
8917         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8918       // An add of one will be selected as an INC.
8919       if (C->getAPIntValue() == 1) {
8920         Opcode = X86ISD::INC;
8921         NumOperands = 1;
8922         break;
8923       }
8924
8925       // An add of negative one (subtract of one) will be selected as a DEC.
8926       if (C->getAPIntValue().isAllOnesValue()) {
8927         Opcode = X86ISD::DEC;
8928         NumOperands = 1;
8929         break;
8930       }
8931     }
8932
8933     // Otherwise use a regular EFLAGS-setting add.
8934     Opcode = X86ISD::ADD;
8935     NumOperands = 2;
8936     break;
8937   case ISD::AND: {
8938     // If the primary and result isn't used, don't bother using X86ISD::AND,
8939     // because a TEST instruction will be better.
8940     bool NonFlagUse = false;
8941     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8942            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8943       SDNode *User = *UI;
8944       unsigned UOpNo = UI.getOperandNo();
8945       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8946         // Look pass truncate.
8947         UOpNo = User->use_begin().getOperandNo();
8948         User = *User->use_begin();
8949       }
8950
8951       if (User->getOpcode() != ISD::BRCOND &&
8952           User->getOpcode() != ISD::SETCC &&
8953           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8954         NonFlagUse = true;
8955         break;
8956       }
8957     }
8958
8959     if (!NonFlagUse)
8960       break;
8961   }
8962     // FALL THROUGH
8963   case ISD::SUB:
8964   case ISD::OR:
8965   case ISD::XOR:
8966     // Due to the ISEL shortcoming noted above, be conservative if this op is
8967     // likely to be selected as part of a load-modify-store instruction.
8968     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8969            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8970       if (UI->getOpcode() == ISD::STORE)
8971         goto default_case;
8972
8973     // Otherwise use a regular EFLAGS-setting instruction.
8974     switch (ArithOp.getOpcode()) {
8975     default: llvm_unreachable("unexpected operator!");
8976     case ISD::SUB: Opcode = X86ISD::SUB; break;
8977     case ISD::XOR: Opcode = X86ISD::XOR; break;
8978     case ISD::AND: Opcode = X86ISD::AND; break;
8979     case ISD::OR: {
8980       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8981         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8982         if (EFLAGS.getNode())
8983           return EFLAGS;
8984       }
8985       Opcode = X86ISD::OR;
8986       break;
8987     }
8988     }
8989
8990     NumOperands = 2;
8991     break;
8992   case X86ISD::ADD:
8993   case X86ISD::SUB:
8994   case X86ISD::INC:
8995   case X86ISD::DEC:
8996   case X86ISD::OR:
8997   case X86ISD::XOR:
8998   case X86ISD::AND:
8999     return SDValue(Op.getNode(), 1);
9000   default:
9001   default_case:
9002     break;
9003   }
9004
9005   // If we found that truncation is beneficial, perform the truncation and
9006   // update 'Op'.
9007   if (NeedTruncation) {
9008     EVT VT = Op.getValueType();
9009     SDValue WideVal = Op->getOperand(0);
9010     EVT WideVT = WideVal.getValueType();
9011     unsigned ConvertedOp = 0;
9012     // Use a target machine opcode to prevent further DAGCombine
9013     // optimizations that may separate the arithmetic operations
9014     // from the setcc node.
9015     switch (WideVal.getOpcode()) {
9016       default: break;
9017       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9018       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9019       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9020       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9021       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9022     }
9023
9024     if (ConvertedOp) {
9025       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9026       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9027         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9028         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9029         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9030       }
9031     }
9032   }
9033
9034   if (Opcode == 0)
9035     // Emit a CMP with 0, which is the TEST pattern.
9036     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9037                        DAG.getConstant(0, Op.getValueType()));
9038
9039   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9040   SmallVector<SDValue, 4> Ops;
9041   for (unsigned i = 0; i != NumOperands; ++i)
9042     Ops.push_back(Op.getOperand(i));
9043
9044   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9045   DAG.ReplaceAllUsesWith(Op, New);
9046   return SDValue(New.getNode(), 1);
9047 }
9048
9049 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9050 /// equivalent.
9051 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9052                                    SelectionDAG &DAG) const {
9053   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9054     if (C->getAPIntValue() == 0)
9055       return EmitTest(Op0, X86CC, DAG);
9056
9057   DebugLoc dl = Op0.getDebugLoc();
9058   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9059        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9060     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9061     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9062     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9063                               Op0, Op1);
9064     return SDValue(Sub.getNode(), 1);
9065   }
9066   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9067 }
9068
9069 /// Convert a comparison if required by the subtarget.
9070 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9071                                                  SelectionDAG &DAG) const {
9072   // If the subtarget does not support the FUCOMI instruction, floating-point
9073   // comparisons have to be converted.
9074   if (Subtarget->hasCMov() ||
9075       Cmp.getOpcode() != X86ISD::CMP ||
9076       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9077       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9078     return Cmp;
9079
9080   // The instruction selector will select an FUCOM instruction instead of
9081   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9082   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9083   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9084   DebugLoc dl = Cmp.getDebugLoc();
9085   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9086   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9087   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9088                             DAG.getConstant(8, MVT::i8));
9089   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9090   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9091 }
9092
9093 static bool isAllOnes(SDValue V) {
9094   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9095   return C && C->isAllOnesValue();
9096 }
9097
9098 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9099 /// if it's possible.
9100 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9101                                      DebugLoc dl, SelectionDAG &DAG) const {
9102   SDValue Op0 = And.getOperand(0);
9103   SDValue Op1 = And.getOperand(1);
9104   if (Op0.getOpcode() == ISD::TRUNCATE)
9105     Op0 = Op0.getOperand(0);
9106   if (Op1.getOpcode() == ISD::TRUNCATE)
9107     Op1 = Op1.getOperand(0);
9108
9109   SDValue LHS, RHS;
9110   if (Op1.getOpcode() == ISD::SHL)
9111     std::swap(Op0, Op1);
9112   if (Op0.getOpcode() == ISD::SHL) {
9113     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9114       if (And00C->getZExtValue() == 1) {
9115         // If we looked past a truncate, check that it's only truncating away
9116         // known zeros.
9117         unsigned BitWidth = Op0.getValueSizeInBits();
9118         unsigned AndBitWidth = And.getValueSizeInBits();
9119         if (BitWidth > AndBitWidth) {
9120           APInt Zeros, Ones;
9121           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9122           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9123             return SDValue();
9124         }
9125         LHS = Op1;
9126         RHS = Op0.getOperand(1);
9127       }
9128   } else if (Op1.getOpcode() == ISD::Constant) {
9129     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9130     uint64_t AndRHSVal = AndRHS->getZExtValue();
9131     SDValue AndLHS = Op0;
9132
9133     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9134       LHS = AndLHS.getOperand(0);
9135       RHS = AndLHS.getOperand(1);
9136     }
9137
9138     // Use BT if the immediate can't be encoded in a TEST instruction.
9139     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9140       LHS = AndLHS;
9141       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9142     }
9143   }
9144
9145   if (LHS.getNode()) {
9146     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9147     // the condition code later.
9148     bool Invert = false;
9149     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9150       Invert = true;
9151       LHS = LHS.getOperand(0);
9152     }
9153
9154     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9155     // instruction.  Since the shift amount is in-range-or-undefined, we know
9156     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9157     // the encoding for the i16 version is larger than the i32 version.
9158     // Also promote i16 to i32 for performance / code size reason.
9159     if (LHS.getValueType() == MVT::i8 ||
9160         LHS.getValueType() == MVT::i16)
9161       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9162
9163     // If the operand types disagree, extend the shift amount to match.  Since
9164     // BT ignores high bits (like shifts) we can use anyextend.
9165     if (LHS.getValueType() != RHS.getValueType())
9166       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9167
9168     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9169     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9170     // Flip the condition if the LHS was a not instruction
9171     if (Invert)
9172       Cond = X86::GetOppositeBranchCondition(Cond);
9173     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9174                        DAG.getConstant(Cond, MVT::i8), BT);
9175   }
9176
9177   return SDValue();
9178 }
9179
9180 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9181 // ones, and then concatenate the result back.
9182 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9183   MVT VT = Op.getValueType().getSimpleVT();
9184
9185   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9186          "Unsupported value type for operation");
9187
9188   unsigned NumElems = VT.getVectorNumElements();
9189   DebugLoc dl = Op.getDebugLoc();
9190   SDValue CC = Op.getOperand(2);
9191
9192   // Extract the LHS vectors
9193   SDValue LHS = Op.getOperand(0);
9194   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9195   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9196
9197   // Extract the RHS vectors
9198   SDValue RHS = Op.getOperand(1);
9199   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9200   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9201
9202   // Issue the operation on the smaller types and concatenate the result back
9203   MVT EltVT = VT.getVectorElementType();
9204   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9205   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9206                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9207                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9208 }
9209
9210 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9211                            SelectionDAG &DAG) {
9212   SDValue Cond;
9213   SDValue Op0 = Op.getOperand(0);
9214   SDValue Op1 = Op.getOperand(1);
9215   SDValue CC = Op.getOperand(2);
9216   MVT VT = Op.getValueType().getSimpleVT();
9217   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9218   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9219   DebugLoc dl = Op.getDebugLoc();
9220
9221   if (isFP) {
9222 #ifndef NDEBUG
9223     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9224     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9225 #endif
9226
9227     unsigned SSECC;
9228     bool Swap = false;
9229
9230     // SSE Condition code mapping:
9231     //  0 - EQ
9232     //  1 - LT
9233     //  2 - LE
9234     //  3 - UNORD
9235     //  4 - NEQ
9236     //  5 - NLT
9237     //  6 - NLE
9238     //  7 - ORD
9239     switch (SetCCOpcode) {
9240     default: llvm_unreachable("Unexpected SETCC condition");
9241     case ISD::SETOEQ:
9242     case ISD::SETEQ:  SSECC = 0; break;
9243     case ISD::SETOGT:
9244     case ISD::SETGT: Swap = true; // Fallthrough
9245     case ISD::SETLT:
9246     case ISD::SETOLT: SSECC = 1; break;
9247     case ISD::SETOGE:
9248     case ISD::SETGE: Swap = true; // Fallthrough
9249     case ISD::SETLE:
9250     case ISD::SETOLE: SSECC = 2; break;
9251     case ISD::SETUO:  SSECC = 3; break;
9252     case ISD::SETUNE:
9253     case ISD::SETNE:  SSECC = 4; break;
9254     case ISD::SETULE: Swap = true; // Fallthrough
9255     case ISD::SETUGE: SSECC = 5; break;
9256     case ISD::SETULT: Swap = true; // Fallthrough
9257     case ISD::SETUGT: SSECC = 6; break;
9258     case ISD::SETO:   SSECC = 7; break;
9259     case ISD::SETUEQ:
9260     case ISD::SETONE: SSECC = 8; break;
9261     }
9262     if (Swap)
9263       std::swap(Op0, Op1);
9264
9265     // In the two special cases we can't handle, emit two comparisons.
9266     if (SSECC == 8) {
9267       unsigned CC0, CC1;
9268       unsigned CombineOpc;
9269       if (SetCCOpcode == ISD::SETUEQ) {
9270         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9271       } else {
9272         assert(SetCCOpcode == ISD::SETONE);
9273         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9274       }
9275
9276       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9277                                  DAG.getConstant(CC0, MVT::i8));
9278       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9279                                  DAG.getConstant(CC1, MVT::i8));
9280       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9281     }
9282     // Handle all other FP comparisons here.
9283     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9284                        DAG.getConstant(SSECC, MVT::i8));
9285   }
9286
9287   // Break 256-bit integer vector compare into smaller ones.
9288   if (VT.is256BitVector() && !Subtarget->hasInt256())
9289     return Lower256IntVSETCC(Op, DAG);
9290
9291   // We are handling one of the integer comparisons here.  Since SSE only has
9292   // GT and EQ comparisons for integer, swapping operands and multiple
9293   // operations may be required for some comparisons.
9294   unsigned Opc;
9295   bool Swap = false, Invert = false, FlipSigns = false;
9296
9297   switch (SetCCOpcode) {
9298   default: llvm_unreachable("Unexpected SETCC condition");
9299   case ISD::SETNE:  Invert = true;
9300   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9301   case ISD::SETLT:  Swap = true;
9302   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9303   case ISD::SETGE:  Swap = true;
9304   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9305   case ISD::SETULT: Swap = true;
9306   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9307   case ISD::SETUGE: Swap = true;
9308   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9309   }
9310   if (Swap)
9311     std::swap(Op0, Op1);
9312
9313   // Check that the operation in question is available (most are plain SSE2,
9314   // but PCMPGTQ and PCMPEQQ have different requirements).
9315   if (VT == MVT::v2i64) {
9316     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9317       return SDValue();
9318     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9319       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9320       // pcmpeqd + pshufd + pand.
9321       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9322
9323       // First cast everything to the right type,
9324       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9325       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9326
9327       // Do the compare.
9328       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9329
9330       // Make sure the lower and upper halves are both all-ones.
9331       const int Mask[] = { 1, 0, 3, 2 };
9332       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9333       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9334
9335       if (Invert)
9336         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9337
9338       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9339     }
9340   }
9341
9342   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9343   // bits of the inputs before performing those operations.
9344   if (FlipSigns) {
9345     EVT EltVT = VT.getVectorElementType();
9346     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9347                                       EltVT);
9348     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9349     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9350                                     SignBits.size());
9351     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9352     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9353   }
9354
9355   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9356
9357   // If the logical-not of the result is required, perform that now.
9358   if (Invert)
9359     Result = DAG.getNOT(dl, Result, VT);
9360
9361   return Result;
9362 }
9363
9364 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9365
9366   MVT VT = Op.getValueType().getSimpleVT();
9367
9368   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9369
9370   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9371   SDValue Op0 = Op.getOperand(0);
9372   SDValue Op1 = Op.getOperand(1);
9373   DebugLoc dl = Op.getDebugLoc();
9374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9375
9376   // Optimize to BT if possible.
9377   // Lower (X & (1 << N)) == 0 to BT(X, N).
9378   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9379   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9380   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9381       Op1.getOpcode() == ISD::Constant &&
9382       cast<ConstantSDNode>(Op1)->isNullValue() &&
9383       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9384     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9385     if (NewSetCC.getNode())
9386       return NewSetCC;
9387   }
9388
9389   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9390   // these.
9391   if (Op1.getOpcode() == ISD::Constant &&
9392       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9393        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9394       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9395
9396     // If the input is a setcc, then reuse the input setcc or use a new one with
9397     // the inverted condition.
9398     if (Op0.getOpcode() == X86ISD::SETCC) {
9399       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9400       bool Invert = (CC == ISD::SETNE) ^
9401         cast<ConstantSDNode>(Op1)->isNullValue();
9402       if (!Invert) return Op0;
9403
9404       CCode = X86::GetOppositeBranchCondition(CCode);
9405       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9406                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9407     }
9408   }
9409
9410   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9411   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9412   if (X86CC == X86::COND_INVALID)
9413     return SDValue();
9414
9415   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9416   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9417   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9418                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9419 }
9420
9421 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9422 static bool isX86LogicalCmp(SDValue Op) {
9423   unsigned Opc = Op.getNode()->getOpcode();
9424   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9425       Opc == X86ISD::SAHF)
9426     return true;
9427   if (Op.getResNo() == 1 &&
9428       (Opc == X86ISD::ADD ||
9429        Opc == X86ISD::SUB ||
9430        Opc == X86ISD::ADC ||
9431        Opc == X86ISD::SBB ||
9432        Opc == X86ISD::SMUL ||
9433        Opc == X86ISD::UMUL ||
9434        Opc == X86ISD::INC ||
9435        Opc == X86ISD::DEC ||
9436        Opc == X86ISD::OR ||
9437        Opc == X86ISD::XOR ||
9438        Opc == X86ISD::AND))
9439     return true;
9440
9441   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9442     return true;
9443
9444   return false;
9445 }
9446
9447 static bool isZero(SDValue V) {
9448   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9449   return C && C->isNullValue();
9450 }
9451
9452 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9453   if (V.getOpcode() != ISD::TRUNCATE)
9454     return false;
9455
9456   SDValue VOp0 = V.getOperand(0);
9457   unsigned InBits = VOp0.getValueSizeInBits();
9458   unsigned Bits = V.getValueSizeInBits();
9459   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9460 }
9461
9462 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9463   bool addTest = true;
9464   SDValue Cond  = Op.getOperand(0);
9465   SDValue Op1 = Op.getOperand(1);
9466   SDValue Op2 = Op.getOperand(2);
9467   DebugLoc DL = Op.getDebugLoc();
9468   SDValue CC;
9469
9470   if (Cond.getOpcode() == ISD::SETCC) {
9471     SDValue NewCond = LowerSETCC(Cond, DAG);
9472     if (NewCond.getNode())
9473       Cond = NewCond;
9474   }
9475
9476   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9477   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9478   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9479   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9480   if (Cond.getOpcode() == X86ISD::SETCC &&
9481       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9482       isZero(Cond.getOperand(1).getOperand(1))) {
9483     SDValue Cmp = Cond.getOperand(1);
9484
9485     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9486
9487     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9488         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9489       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9490
9491       SDValue CmpOp0 = Cmp.getOperand(0);
9492       // Apply further optimizations for special cases
9493       // (select (x != 0), -1, 0) -> neg & sbb
9494       // (select (x == 0), 0, -1) -> neg & sbb
9495       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9496         if (YC->isNullValue() &&
9497             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9498           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9499           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9500                                     DAG.getConstant(0, CmpOp0.getValueType()),
9501                                     CmpOp0);
9502           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9503                                     DAG.getConstant(X86::COND_B, MVT::i8),
9504                                     SDValue(Neg.getNode(), 1));
9505           return Res;
9506         }
9507
9508       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9509                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9510       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9511
9512       SDValue Res =   // Res = 0 or -1.
9513         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9514                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9515
9516       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9517         Res = DAG.getNOT(DL, Res, Res.getValueType());
9518
9519       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9520       if (N2C == 0 || !N2C->isNullValue())
9521         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9522       return Res;
9523     }
9524   }
9525
9526   // Look past (and (setcc_carry (cmp ...)), 1).
9527   if (Cond.getOpcode() == ISD::AND &&
9528       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9529     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9530     if (C && C->getAPIntValue() == 1)
9531       Cond = Cond.getOperand(0);
9532   }
9533
9534   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9535   // setting operand in place of the X86ISD::SETCC.
9536   unsigned CondOpcode = Cond.getOpcode();
9537   if (CondOpcode == X86ISD::SETCC ||
9538       CondOpcode == X86ISD::SETCC_CARRY) {
9539     CC = Cond.getOperand(0);
9540
9541     SDValue Cmp = Cond.getOperand(1);
9542     unsigned Opc = Cmp.getOpcode();
9543     MVT VT = Op.getValueType().getSimpleVT();
9544
9545     bool IllegalFPCMov = false;
9546     if (VT.isFloatingPoint() && !VT.isVector() &&
9547         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9548       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9549
9550     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9551         Opc == X86ISD::BT) { // FIXME
9552       Cond = Cmp;
9553       addTest = false;
9554     }
9555   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9556              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9557              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9558               Cond.getOperand(0).getValueType() != MVT::i8)) {
9559     SDValue LHS = Cond.getOperand(0);
9560     SDValue RHS = Cond.getOperand(1);
9561     unsigned X86Opcode;
9562     unsigned X86Cond;
9563     SDVTList VTs;
9564     switch (CondOpcode) {
9565     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9566     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9567     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9568     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9569     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9570     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9571     default: llvm_unreachable("unexpected overflowing operator");
9572     }
9573     if (CondOpcode == ISD::UMULO)
9574       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9575                           MVT::i32);
9576     else
9577       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9578
9579     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9580
9581     if (CondOpcode == ISD::UMULO)
9582       Cond = X86Op.getValue(2);
9583     else
9584       Cond = X86Op.getValue(1);
9585
9586     CC = DAG.getConstant(X86Cond, MVT::i8);
9587     addTest = false;
9588   }
9589
9590   if (addTest) {
9591     // Look pass the truncate if the high bits are known zero.
9592     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9593         Cond = Cond.getOperand(0);
9594
9595     // We know the result of AND is compared against zero. Try to match
9596     // it to BT.
9597     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9598       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9599       if (NewSetCC.getNode()) {
9600         CC = NewSetCC.getOperand(0);
9601         Cond = NewSetCC.getOperand(1);
9602         addTest = false;
9603       }
9604     }
9605   }
9606
9607   if (addTest) {
9608     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9609     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9610   }
9611
9612   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9613   // a <  b ?  0 : -1 -> RES = setcc_carry
9614   // a >= b ? -1 :  0 -> RES = setcc_carry
9615   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9616   if (Cond.getOpcode() == X86ISD::SUB) {
9617     Cond = ConvertCmpIfNecessary(Cond, DAG);
9618     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9619
9620     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9621         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9622       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9623                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9624       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9625         return DAG.getNOT(DL, Res, Res.getValueType());
9626       return Res;
9627     }
9628   }
9629
9630   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9631   // widen the cmov and push the truncate through. This avoids introducing a new
9632   // branch during isel and doesn't add any extensions.
9633   if (Op.getValueType() == MVT::i8 &&
9634       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9635     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9636     if (T1.getValueType() == T2.getValueType() &&
9637         // Blacklist CopyFromReg to avoid partial register stalls.
9638         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9639       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9640       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9641       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9642     }
9643   }
9644
9645   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9646   // condition is true.
9647   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9648   SDValue Ops[] = { Op2, Op1, CC, Cond };
9649   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9650 }
9651
9652 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9653                                             SelectionDAG &DAG) const {
9654   MVT VT = Op->getValueType(0).getSimpleVT();
9655   SDValue In = Op->getOperand(0);
9656   MVT InVT = In.getValueType().getSimpleVT();
9657   DebugLoc dl = Op->getDebugLoc();
9658
9659   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9660       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9661     return SDValue();
9662
9663   if (Subtarget->hasInt256())
9664     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9665
9666   // Optimize vectors in AVX mode
9667   // Sign extend  v8i16 to v8i32 and
9668   //              v4i32 to v4i64
9669   //
9670   // Divide input vector into two parts
9671   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9672   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9673   // concat the vectors to original VT
9674
9675   unsigned NumElems = InVT.getVectorNumElements();
9676   SDValue Undef = DAG.getUNDEF(InVT);
9677
9678   SmallVector<int,8> ShufMask1(NumElems, -1);
9679   for (unsigned i = 0; i != NumElems/2; ++i)
9680     ShufMask1[i] = i;
9681
9682   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9683
9684   SmallVector<int,8> ShufMask2(NumElems, -1);
9685   for (unsigned i = 0; i != NumElems/2; ++i)
9686     ShufMask2[i] = i + NumElems/2;
9687
9688   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9689
9690   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9691                                 VT.getVectorNumElements()/2);
9692
9693   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9694   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9695
9696   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9697 }
9698
9699 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9700 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9701 // from the AND / OR.
9702 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9703   Opc = Op.getOpcode();
9704   if (Opc != ISD::OR && Opc != ISD::AND)
9705     return false;
9706   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9707           Op.getOperand(0).hasOneUse() &&
9708           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9709           Op.getOperand(1).hasOneUse());
9710 }
9711
9712 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9713 // 1 and that the SETCC node has a single use.
9714 static bool isXor1OfSetCC(SDValue Op) {
9715   if (Op.getOpcode() != ISD::XOR)
9716     return false;
9717   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9718   if (N1C && N1C->getAPIntValue() == 1) {
9719     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9720       Op.getOperand(0).hasOneUse();
9721   }
9722   return false;
9723 }
9724
9725 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9726   bool addTest = true;
9727   SDValue Chain = Op.getOperand(0);
9728   SDValue Cond  = Op.getOperand(1);
9729   SDValue Dest  = Op.getOperand(2);
9730   DebugLoc dl = Op.getDebugLoc();
9731   SDValue CC;
9732   bool Inverted = false;
9733
9734   if (Cond.getOpcode() == ISD::SETCC) {
9735     // Check for setcc([su]{add,sub,mul}o == 0).
9736     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9737         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9738         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9739         Cond.getOperand(0).getResNo() == 1 &&
9740         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9741          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9742          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9743          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9744          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9745          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9746       Inverted = true;
9747       Cond = Cond.getOperand(0);
9748     } else {
9749       SDValue NewCond = LowerSETCC(Cond, DAG);
9750       if (NewCond.getNode())
9751         Cond = NewCond;
9752     }
9753   }
9754 #if 0
9755   // FIXME: LowerXALUO doesn't handle these!!
9756   else if (Cond.getOpcode() == X86ISD::ADD  ||
9757            Cond.getOpcode() == X86ISD::SUB  ||
9758            Cond.getOpcode() == X86ISD::SMUL ||
9759            Cond.getOpcode() == X86ISD::UMUL)
9760     Cond = LowerXALUO(Cond, DAG);
9761 #endif
9762
9763   // Look pass (and (setcc_carry (cmp ...)), 1).
9764   if (Cond.getOpcode() == ISD::AND &&
9765       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9766     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9767     if (C && C->getAPIntValue() == 1)
9768       Cond = Cond.getOperand(0);
9769   }
9770
9771   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9772   // setting operand in place of the X86ISD::SETCC.
9773   unsigned CondOpcode = Cond.getOpcode();
9774   if (CondOpcode == X86ISD::SETCC ||
9775       CondOpcode == X86ISD::SETCC_CARRY) {
9776     CC = Cond.getOperand(0);
9777
9778     SDValue Cmp = Cond.getOperand(1);
9779     unsigned Opc = Cmp.getOpcode();
9780     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9781     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9782       Cond = Cmp;
9783       addTest = false;
9784     } else {
9785       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9786       default: break;
9787       case X86::COND_O:
9788       case X86::COND_B:
9789         // These can only come from an arithmetic instruction with overflow,
9790         // e.g. SADDO, UADDO.
9791         Cond = Cond.getNode()->getOperand(1);
9792         addTest = false;
9793         break;
9794       }
9795     }
9796   }
9797   CondOpcode = Cond.getOpcode();
9798   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9799       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9800       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9801        Cond.getOperand(0).getValueType() != MVT::i8)) {
9802     SDValue LHS = Cond.getOperand(0);
9803     SDValue RHS = Cond.getOperand(1);
9804     unsigned X86Opcode;
9805     unsigned X86Cond;
9806     SDVTList VTs;
9807     switch (CondOpcode) {
9808     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9809     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9810     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9811     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9812     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9813     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9814     default: llvm_unreachable("unexpected overflowing operator");
9815     }
9816     if (Inverted)
9817       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9818     if (CondOpcode == ISD::UMULO)
9819       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9820                           MVT::i32);
9821     else
9822       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9823
9824     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9825
9826     if (CondOpcode == ISD::UMULO)
9827       Cond = X86Op.getValue(2);
9828     else
9829       Cond = X86Op.getValue(1);
9830
9831     CC = DAG.getConstant(X86Cond, MVT::i8);
9832     addTest = false;
9833   } else {
9834     unsigned CondOpc;
9835     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9836       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9837       if (CondOpc == ISD::OR) {
9838         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9839         // two branches instead of an explicit OR instruction with a
9840         // separate test.
9841         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9842             isX86LogicalCmp(Cmp)) {
9843           CC = Cond.getOperand(0).getOperand(0);
9844           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9845                               Chain, Dest, CC, Cmp);
9846           CC = Cond.getOperand(1).getOperand(0);
9847           Cond = Cmp;
9848           addTest = false;
9849         }
9850       } else { // ISD::AND
9851         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9852         // two branches instead of an explicit AND instruction with a
9853         // separate test. However, we only do this if this block doesn't
9854         // have a fall-through edge, because this requires an explicit
9855         // jmp when the condition is false.
9856         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9857             isX86LogicalCmp(Cmp) &&
9858             Op.getNode()->hasOneUse()) {
9859           X86::CondCode CCode =
9860             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9861           CCode = X86::GetOppositeBranchCondition(CCode);
9862           CC = DAG.getConstant(CCode, MVT::i8);
9863           SDNode *User = *Op.getNode()->use_begin();
9864           // Look for an unconditional branch following this conditional branch.
9865           // We need this because we need to reverse the successors in order
9866           // to implement FCMP_OEQ.
9867           if (User->getOpcode() == ISD::BR) {
9868             SDValue FalseBB = User->getOperand(1);
9869             SDNode *NewBR =
9870               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9871             assert(NewBR == User);
9872             (void)NewBR;
9873             Dest = FalseBB;
9874
9875             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9876                                 Chain, Dest, CC, Cmp);
9877             X86::CondCode CCode =
9878               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9879             CCode = X86::GetOppositeBranchCondition(CCode);
9880             CC = DAG.getConstant(CCode, MVT::i8);
9881             Cond = Cmp;
9882             addTest = false;
9883           }
9884         }
9885       }
9886     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9887       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9888       // It should be transformed during dag combiner except when the condition
9889       // is set by a arithmetics with overflow node.
9890       X86::CondCode CCode =
9891         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9892       CCode = X86::GetOppositeBranchCondition(CCode);
9893       CC = DAG.getConstant(CCode, MVT::i8);
9894       Cond = Cond.getOperand(0).getOperand(1);
9895       addTest = false;
9896     } else if (Cond.getOpcode() == ISD::SETCC &&
9897                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9898       // For FCMP_OEQ, we can emit
9899       // two branches instead of an explicit AND instruction with a
9900       // separate test. However, we only do this if this block doesn't
9901       // have a fall-through edge, because this requires an explicit
9902       // jmp when the condition is false.
9903       if (Op.getNode()->hasOneUse()) {
9904         SDNode *User = *Op.getNode()->use_begin();
9905         // Look for an unconditional branch following this conditional branch.
9906         // We need this because we need to reverse the successors in order
9907         // to implement FCMP_OEQ.
9908         if (User->getOpcode() == ISD::BR) {
9909           SDValue FalseBB = User->getOperand(1);
9910           SDNode *NewBR =
9911             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9912           assert(NewBR == User);
9913           (void)NewBR;
9914           Dest = FalseBB;
9915
9916           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9917                                     Cond.getOperand(0), Cond.getOperand(1));
9918           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9919           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9920           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9921                               Chain, Dest, CC, Cmp);
9922           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9923           Cond = Cmp;
9924           addTest = false;
9925         }
9926       }
9927     } else if (Cond.getOpcode() == ISD::SETCC &&
9928                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9929       // For FCMP_UNE, we can emit
9930       // two branches instead of an explicit AND instruction with a
9931       // separate test. However, we only do this if this block doesn't
9932       // have a fall-through edge, because this requires an explicit
9933       // jmp when the condition is false.
9934       if (Op.getNode()->hasOneUse()) {
9935         SDNode *User = *Op.getNode()->use_begin();
9936         // Look for an unconditional branch following this conditional branch.
9937         // We need this because we need to reverse the successors in order
9938         // to implement FCMP_UNE.
9939         if (User->getOpcode() == ISD::BR) {
9940           SDValue FalseBB = User->getOperand(1);
9941           SDNode *NewBR =
9942             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9943           assert(NewBR == User);
9944           (void)NewBR;
9945
9946           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9947                                     Cond.getOperand(0), Cond.getOperand(1));
9948           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9949           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9950           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9951                               Chain, Dest, CC, Cmp);
9952           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9953           Cond = Cmp;
9954           addTest = false;
9955           Dest = FalseBB;
9956         }
9957       }
9958     }
9959   }
9960
9961   if (addTest) {
9962     // Look pass the truncate if the high bits are known zero.
9963     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9964         Cond = Cond.getOperand(0);
9965
9966     // We know the result of AND is compared against zero. Try to match
9967     // it to BT.
9968     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9969       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9970       if (NewSetCC.getNode()) {
9971         CC = NewSetCC.getOperand(0);
9972         Cond = NewSetCC.getOperand(1);
9973         addTest = false;
9974       }
9975     }
9976   }
9977
9978   if (addTest) {
9979     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9980     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9981   }
9982   Cond = ConvertCmpIfNecessary(Cond, DAG);
9983   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9984                      Chain, Dest, CC, Cond);
9985 }
9986
9987 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9988 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9989 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9990 // that the guard pages used by the OS virtual memory manager are allocated in
9991 // correct sequence.
9992 SDValue
9993 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9994                                            SelectionDAG &DAG) const {
9995   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9996           getTargetMachine().Options.EnableSegmentedStacks) &&
9997          "This should be used only on Windows targets or when segmented stacks "
9998          "are being used");
9999   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10000   DebugLoc dl = Op.getDebugLoc();
10001
10002   // Get the inputs.
10003   SDValue Chain = Op.getOperand(0);
10004   SDValue Size  = Op.getOperand(1);
10005   // FIXME: Ensure alignment here
10006
10007   bool Is64Bit = Subtarget->is64Bit();
10008   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10009
10010   if (getTargetMachine().Options.EnableSegmentedStacks) {
10011     MachineFunction &MF = DAG.getMachineFunction();
10012     MachineRegisterInfo &MRI = MF.getRegInfo();
10013
10014     if (Is64Bit) {
10015       // The 64 bit implementation of segmented stacks needs to clobber both r10
10016       // r11. This makes it impossible to use it along with nested parameters.
10017       const Function *F = MF.getFunction();
10018
10019       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10020            I != E; ++I)
10021         if (I->hasNestAttr())
10022           report_fatal_error("Cannot use segmented stacks with functions that "
10023                              "have nested arguments.");
10024     }
10025
10026     const TargetRegisterClass *AddrRegClass =
10027       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10028     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10029     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10030     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10031                                 DAG.getRegister(Vreg, SPTy));
10032     SDValue Ops1[2] = { Value, Chain };
10033     return DAG.getMergeValues(Ops1, 2, dl);
10034   } else {
10035     SDValue Flag;
10036     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10037
10038     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10039     Flag = Chain.getValue(1);
10040     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10041
10042     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10043     Flag = Chain.getValue(1);
10044
10045     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10046                                SPTy).getValue(1);
10047
10048     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10049     return DAG.getMergeValues(Ops1, 2, dl);
10050   }
10051 }
10052
10053 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10054   MachineFunction &MF = DAG.getMachineFunction();
10055   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10056
10057   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10058   DebugLoc DL = Op.getDebugLoc();
10059
10060   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10061     // vastart just stores the address of the VarArgsFrameIndex slot into the
10062     // memory location argument.
10063     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10064                                    getPointerTy());
10065     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10066                         MachinePointerInfo(SV), false, false, 0);
10067   }
10068
10069   // __va_list_tag:
10070   //   gp_offset         (0 - 6 * 8)
10071   //   fp_offset         (48 - 48 + 8 * 16)
10072   //   overflow_arg_area (point to parameters coming in memory).
10073   //   reg_save_area
10074   SmallVector<SDValue, 8> MemOps;
10075   SDValue FIN = Op.getOperand(1);
10076   // Store gp_offset
10077   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10078                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10079                                                MVT::i32),
10080                                FIN, MachinePointerInfo(SV), false, false, 0);
10081   MemOps.push_back(Store);
10082
10083   // Store fp_offset
10084   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10085                     FIN, DAG.getIntPtrConstant(4));
10086   Store = DAG.getStore(Op.getOperand(0), DL,
10087                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10088                                        MVT::i32),
10089                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10090   MemOps.push_back(Store);
10091
10092   // Store ptr to overflow_arg_area
10093   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10094                     FIN, DAG.getIntPtrConstant(4));
10095   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10096                                     getPointerTy());
10097   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10098                        MachinePointerInfo(SV, 8),
10099                        false, false, 0);
10100   MemOps.push_back(Store);
10101
10102   // Store ptr to reg_save_area.
10103   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10104                     FIN, DAG.getIntPtrConstant(8));
10105   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10106                                     getPointerTy());
10107   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10108                        MachinePointerInfo(SV, 16), false, false, 0);
10109   MemOps.push_back(Store);
10110   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10111                      &MemOps[0], MemOps.size());
10112 }
10113
10114 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10115   assert(Subtarget->is64Bit() &&
10116          "LowerVAARG only handles 64-bit va_arg!");
10117   assert((Subtarget->isTargetLinux() ||
10118           Subtarget->isTargetDarwin()) &&
10119           "Unhandled target in LowerVAARG");
10120   assert(Op.getNode()->getNumOperands() == 4);
10121   SDValue Chain = Op.getOperand(0);
10122   SDValue SrcPtr = Op.getOperand(1);
10123   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10124   unsigned Align = Op.getConstantOperandVal(3);
10125   DebugLoc dl = Op.getDebugLoc();
10126
10127   EVT ArgVT = Op.getNode()->getValueType(0);
10128   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10129   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10130   uint8_t ArgMode;
10131
10132   // Decide which area this value should be read from.
10133   // TODO: Implement the AMD64 ABI in its entirety. This simple
10134   // selection mechanism works only for the basic types.
10135   if (ArgVT == MVT::f80) {
10136     llvm_unreachable("va_arg for f80 not yet implemented");
10137   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10138     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10139   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10140     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10141   } else {
10142     llvm_unreachable("Unhandled argument type in LowerVAARG");
10143   }
10144
10145   if (ArgMode == 2) {
10146     // Sanity Check: Make sure using fp_offset makes sense.
10147     assert(!getTargetMachine().Options.UseSoftFloat &&
10148            !(DAG.getMachineFunction()
10149                 .getFunction()->getAttributes()
10150                 .hasAttribute(AttributeSet::FunctionIndex,
10151                               Attribute::NoImplicitFloat)) &&
10152            Subtarget->hasSSE1());
10153   }
10154
10155   // Insert VAARG_64 node into the DAG
10156   // VAARG_64 returns two values: Variable Argument Address, Chain
10157   SmallVector<SDValue, 11> InstOps;
10158   InstOps.push_back(Chain);
10159   InstOps.push_back(SrcPtr);
10160   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10161   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10162   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10163   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10164   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10165                                           VTs, &InstOps[0], InstOps.size(),
10166                                           MVT::i64,
10167                                           MachinePointerInfo(SV),
10168                                           /*Align=*/0,
10169                                           /*Volatile=*/false,
10170                                           /*ReadMem=*/true,
10171                                           /*WriteMem=*/true);
10172   Chain = VAARG.getValue(1);
10173
10174   // Load the next argument and return it
10175   return DAG.getLoad(ArgVT, dl,
10176                      Chain,
10177                      VAARG,
10178                      MachinePointerInfo(),
10179                      false, false, false, 0);
10180 }
10181
10182 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10183                            SelectionDAG &DAG) {
10184   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10185   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10186   SDValue Chain = Op.getOperand(0);
10187   SDValue DstPtr = Op.getOperand(1);
10188   SDValue SrcPtr = Op.getOperand(2);
10189   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10190   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10191   DebugLoc DL = Op.getDebugLoc();
10192
10193   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10194                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10195                        false,
10196                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10197 }
10198
10199 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10200 // may or may not be a constant. Takes immediate version of shift as input.
10201 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10202                                    SDValue SrcOp, SDValue ShAmt,
10203                                    SelectionDAG &DAG) {
10204   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10205
10206   if (isa<ConstantSDNode>(ShAmt)) {
10207     // Constant may be a TargetConstant. Use a regular constant.
10208     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10209     switch (Opc) {
10210       default: llvm_unreachable("Unknown target vector shift node");
10211       case X86ISD::VSHLI:
10212       case X86ISD::VSRLI:
10213       case X86ISD::VSRAI:
10214         return DAG.getNode(Opc, dl, VT, SrcOp,
10215                            DAG.getConstant(ShiftAmt, MVT::i32));
10216     }
10217   }
10218
10219   // Change opcode to non-immediate version
10220   switch (Opc) {
10221     default: llvm_unreachable("Unknown target vector shift node");
10222     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10223     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10224     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10225   }
10226
10227   // Need to build a vector containing shift amount
10228   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10229   SDValue ShOps[4];
10230   ShOps[0] = ShAmt;
10231   ShOps[1] = DAG.getConstant(0, MVT::i32);
10232   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10233   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10234
10235   // The return type has to be a 128-bit type with the same element
10236   // type as the input type.
10237   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10238   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10239
10240   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10241   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10242 }
10243
10244 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10245   DebugLoc dl = Op.getDebugLoc();
10246   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10247   switch (IntNo) {
10248   default: return SDValue();    // Don't custom lower most intrinsics.
10249   // Comparison intrinsics.
10250   case Intrinsic::x86_sse_comieq_ss:
10251   case Intrinsic::x86_sse_comilt_ss:
10252   case Intrinsic::x86_sse_comile_ss:
10253   case Intrinsic::x86_sse_comigt_ss:
10254   case Intrinsic::x86_sse_comige_ss:
10255   case Intrinsic::x86_sse_comineq_ss:
10256   case Intrinsic::x86_sse_ucomieq_ss:
10257   case Intrinsic::x86_sse_ucomilt_ss:
10258   case Intrinsic::x86_sse_ucomile_ss:
10259   case Intrinsic::x86_sse_ucomigt_ss:
10260   case Intrinsic::x86_sse_ucomige_ss:
10261   case Intrinsic::x86_sse_ucomineq_ss:
10262   case Intrinsic::x86_sse2_comieq_sd:
10263   case Intrinsic::x86_sse2_comilt_sd:
10264   case Intrinsic::x86_sse2_comile_sd:
10265   case Intrinsic::x86_sse2_comigt_sd:
10266   case Intrinsic::x86_sse2_comige_sd:
10267   case Intrinsic::x86_sse2_comineq_sd:
10268   case Intrinsic::x86_sse2_ucomieq_sd:
10269   case Intrinsic::x86_sse2_ucomilt_sd:
10270   case Intrinsic::x86_sse2_ucomile_sd:
10271   case Intrinsic::x86_sse2_ucomigt_sd:
10272   case Intrinsic::x86_sse2_ucomige_sd:
10273   case Intrinsic::x86_sse2_ucomineq_sd: {
10274     unsigned Opc;
10275     ISD::CondCode CC;
10276     switch (IntNo) {
10277     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10278     case Intrinsic::x86_sse_comieq_ss:
10279     case Intrinsic::x86_sse2_comieq_sd:
10280       Opc = X86ISD::COMI;
10281       CC = ISD::SETEQ;
10282       break;
10283     case Intrinsic::x86_sse_comilt_ss:
10284     case Intrinsic::x86_sse2_comilt_sd:
10285       Opc = X86ISD::COMI;
10286       CC = ISD::SETLT;
10287       break;
10288     case Intrinsic::x86_sse_comile_ss:
10289     case Intrinsic::x86_sse2_comile_sd:
10290       Opc = X86ISD::COMI;
10291       CC = ISD::SETLE;
10292       break;
10293     case Intrinsic::x86_sse_comigt_ss:
10294     case Intrinsic::x86_sse2_comigt_sd:
10295       Opc = X86ISD::COMI;
10296       CC = ISD::SETGT;
10297       break;
10298     case Intrinsic::x86_sse_comige_ss:
10299     case Intrinsic::x86_sse2_comige_sd:
10300       Opc = X86ISD::COMI;
10301       CC = ISD::SETGE;
10302       break;
10303     case Intrinsic::x86_sse_comineq_ss:
10304     case Intrinsic::x86_sse2_comineq_sd:
10305       Opc = X86ISD::COMI;
10306       CC = ISD::SETNE;
10307       break;
10308     case Intrinsic::x86_sse_ucomieq_ss:
10309     case Intrinsic::x86_sse2_ucomieq_sd:
10310       Opc = X86ISD::UCOMI;
10311       CC = ISD::SETEQ;
10312       break;
10313     case Intrinsic::x86_sse_ucomilt_ss:
10314     case Intrinsic::x86_sse2_ucomilt_sd:
10315       Opc = X86ISD::UCOMI;
10316       CC = ISD::SETLT;
10317       break;
10318     case Intrinsic::x86_sse_ucomile_ss:
10319     case Intrinsic::x86_sse2_ucomile_sd:
10320       Opc = X86ISD::UCOMI;
10321       CC = ISD::SETLE;
10322       break;
10323     case Intrinsic::x86_sse_ucomigt_ss:
10324     case Intrinsic::x86_sse2_ucomigt_sd:
10325       Opc = X86ISD::UCOMI;
10326       CC = ISD::SETGT;
10327       break;
10328     case Intrinsic::x86_sse_ucomige_ss:
10329     case Intrinsic::x86_sse2_ucomige_sd:
10330       Opc = X86ISD::UCOMI;
10331       CC = ISD::SETGE;
10332       break;
10333     case Intrinsic::x86_sse_ucomineq_ss:
10334     case Intrinsic::x86_sse2_ucomineq_sd:
10335       Opc = X86ISD::UCOMI;
10336       CC = ISD::SETNE;
10337       break;
10338     }
10339
10340     SDValue LHS = Op.getOperand(1);
10341     SDValue RHS = Op.getOperand(2);
10342     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10343     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10344     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10345     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10346                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10347     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10348   }
10349
10350   // Arithmetic intrinsics.
10351   case Intrinsic::x86_sse2_pmulu_dq:
10352   case Intrinsic::x86_avx2_pmulu_dq:
10353     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10354                        Op.getOperand(1), Op.getOperand(2));
10355
10356   // SSE2/AVX2 sub with unsigned saturation intrinsics
10357   case Intrinsic::x86_sse2_psubus_b:
10358   case Intrinsic::x86_sse2_psubus_w:
10359   case Intrinsic::x86_avx2_psubus_b:
10360   case Intrinsic::x86_avx2_psubus_w:
10361     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10362                        Op.getOperand(1), Op.getOperand(2));
10363
10364   // SSE3/AVX horizontal add/sub intrinsics
10365   case Intrinsic::x86_sse3_hadd_ps:
10366   case Intrinsic::x86_sse3_hadd_pd:
10367   case Intrinsic::x86_avx_hadd_ps_256:
10368   case Intrinsic::x86_avx_hadd_pd_256:
10369   case Intrinsic::x86_sse3_hsub_ps:
10370   case Intrinsic::x86_sse3_hsub_pd:
10371   case Intrinsic::x86_avx_hsub_ps_256:
10372   case Intrinsic::x86_avx_hsub_pd_256:
10373   case Intrinsic::x86_ssse3_phadd_w_128:
10374   case Intrinsic::x86_ssse3_phadd_d_128:
10375   case Intrinsic::x86_avx2_phadd_w:
10376   case Intrinsic::x86_avx2_phadd_d:
10377   case Intrinsic::x86_ssse3_phsub_w_128:
10378   case Intrinsic::x86_ssse3_phsub_d_128:
10379   case Intrinsic::x86_avx2_phsub_w:
10380   case Intrinsic::x86_avx2_phsub_d: {
10381     unsigned Opcode;
10382     switch (IntNo) {
10383     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10384     case Intrinsic::x86_sse3_hadd_ps:
10385     case Intrinsic::x86_sse3_hadd_pd:
10386     case Intrinsic::x86_avx_hadd_ps_256:
10387     case Intrinsic::x86_avx_hadd_pd_256:
10388       Opcode = X86ISD::FHADD;
10389       break;
10390     case Intrinsic::x86_sse3_hsub_ps:
10391     case Intrinsic::x86_sse3_hsub_pd:
10392     case Intrinsic::x86_avx_hsub_ps_256:
10393     case Intrinsic::x86_avx_hsub_pd_256:
10394       Opcode = X86ISD::FHSUB;
10395       break;
10396     case Intrinsic::x86_ssse3_phadd_w_128:
10397     case Intrinsic::x86_ssse3_phadd_d_128:
10398     case Intrinsic::x86_avx2_phadd_w:
10399     case Intrinsic::x86_avx2_phadd_d:
10400       Opcode = X86ISD::HADD;
10401       break;
10402     case Intrinsic::x86_ssse3_phsub_w_128:
10403     case Intrinsic::x86_ssse3_phsub_d_128:
10404     case Intrinsic::x86_avx2_phsub_w:
10405     case Intrinsic::x86_avx2_phsub_d:
10406       Opcode = X86ISD::HSUB;
10407       break;
10408     }
10409     return DAG.getNode(Opcode, dl, Op.getValueType(),
10410                        Op.getOperand(1), Op.getOperand(2));
10411   }
10412
10413   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10414   case Intrinsic::x86_sse2_pmaxu_b:
10415   case Intrinsic::x86_sse41_pmaxuw:
10416   case Intrinsic::x86_sse41_pmaxud:
10417   case Intrinsic::x86_avx2_pmaxu_b:
10418   case Intrinsic::x86_avx2_pmaxu_w:
10419   case Intrinsic::x86_avx2_pmaxu_d:
10420   case Intrinsic::x86_sse2_pminu_b:
10421   case Intrinsic::x86_sse41_pminuw:
10422   case Intrinsic::x86_sse41_pminud:
10423   case Intrinsic::x86_avx2_pminu_b:
10424   case Intrinsic::x86_avx2_pminu_w:
10425   case Intrinsic::x86_avx2_pminu_d:
10426   case Intrinsic::x86_sse41_pmaxsb:
10427   case Intrinsic::x86_sse2_pmaxs_w:
10428   case Intrinsic::x86_sse41_pmaxsd:
10429   case Intrinsic::x86_avx2_pmaxs_b:
10430   case Intrinsic::x86_avx2_pmaxs_w:
10431   case Intrinsic::x86_avx2_pmaxs_d:
10432   case Intrinsic::x86_sse41_pminsb:
10433   case Intrinsic::x86_sse2_pmins_w:
10434   case Intrinsic::x86_sse41_pminsd:
10435   case Intrinsic::x86_avx2_pmins_b:
10436   case Intrinsic::x86_avx2_pmins_w:
10437   case Intrinsic::x86_avx2_pmins_d: {
10438     unsigned Opcode;
10439     switch (IntNo) {
10440     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10441     case Intrinsic::x86_sse2_pmaxu_b:
10442     case Intrinsic::x86_sse41_pmaxuw:
10443     case Intrinsic::x86_sse41_pmaxud:
10444     case Intrinsic::x86_avx2_pmaxu_b:
10445     case Intrinsic::x86_avx2_pmaxu_w:
10446     case Intrinsic::x86_avx2_pmaxu_d:
10447       Opcode = X86ISD::UMAX;
10448       break;
10449     case Intrinsic::x86_sse2_pminu_b:
10450     case Intrinsic::x86_sse41_pminuw:
10451     case Intrinsic::x86_sse41_pminud:
10452     case Intrinsic::x86_avx2_pminu_b:
10453     case Intrinsic::x86_avx2_pminu_w:
10454     case Intrinsic::x86_avx2_pminu_d:
10455       Opcode = X86ISD::UMIN;
10456       break;
10457     case Intrinsic::x86_sse41_pmaxsb:
10458     case Intrinsic::x86_sse2_pmaxs_w:
10459     case Intrinsic::x86_sse41_pmaxsd:
10460     case Intrinsic::x86_avx2_pmaxs_b:
10461     case Intrinsic::x86_avx2_pmaxs_w:
10462     case Intrinsic::x86_avx2_pmaxs_d:
10463       Opcode = X86ISD::SMAX;
10464       break;
10465     case Intrinsic::x86_sse41_pminsb:
10466     case Intrinsic::x86_sse2_pmins_w:
10467     case Intrinsic::x86_sse41_pminsd:
10468     case Intrinsic::x86_avx2_pmins_b:
10469     case Intrinsic::x86_avx2_pmins_w:
10470     case Intrinsic::x86_avx2_pmins_d:
10471       Opcode = X86ISD::SMIN;
10472       break;
10473     }
10474     return DAG.getNode(Opcode, dl, Op.getValueType(),
10475                        Op.getOperand(1), Op.getOperand(2));
10476   }
10477
10478   // SSE/SSE2/AVX floating point max/min intrinsics.
10479   case Intrinsic::x86_sse_max_ps:
10480   case Intrinsic::x86_sse2_max_pd:
10481   case Intrinsic::x86_avx_max_ps_256:
10482   case Intrinsic::x86_avx_max_pd_256:
10483   case Intrinsic::x86_sse_min_ps:
10484   case Intrinsic::x86_sse2_min_pd:
10485   case Intrinsic::x86_avx_min_ps_256:
10486   case Intrinsic::x86_avx_min_pd_256: {
10487     unsigned Opcode;
10488     switch (IntNo) {
10489     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10490     case Intrinsic::x86_sse_max_ps:
10491     case Intrinsic::x86_sse2_max_pd:
10492     case Intrinsic::x86_avx_max_ps_256:
10493     case Intrinsic::x86_avx_max_pd_256:
10494       Opcode = X86ISD::FMAX;
10495       break;
10496     case Intrinsic::x86_sse_min_ps:
10497     case Intrinsic::x86_sse2_min_pd:
10498     case Intrinsic::x86_avx_min_ps_256:
10499     case Intrinsic::x86_avx_min_pd_256:
10500       Opcode = X86ISD::FMIN;
10501       break;
10502     }
10503     return DAG.getNode(Opcode, dl, Op.getValueType(),
10504                        Op.getOperand(1), Op.getOperand(2));
10505   }
10506
10507   // AVX2 variable shift intrinsics
10508   case Intrinsic::x86_avx2_psllv_d:
10509   case Intrinsic::x86_avx2_psllv_q:
10510   case Intrinsic::x86_avx2_psllv_d_256:
10511   case Intrinsic::x86_avx2_psllv_q_256:
10512   case Intrinsic::x86_avx2_psrlv_d:
10513   case Intrinsic::x86_avx2_psrlv_q:
10514   case Intrinsic::x86_avx2_psrlv_d_256:
10515   case Intrinsic::x86_avx2_psrlv_q_256:
10516   case Intrinsic::x86_avx2_psrav_d:
10517   case Intrinsic::x86_avx2_psrav_d_256: {
10518     unsigned Opcode;
10519     switch (IntNo) {
10520     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10521     case Intrinsic::x86_avx2_psllv_d:
10522     case Intrinsic::x86_avx2_psllv_q:
10523     case Intrinsic::x86_avx2_psllv_d_256:
10524     case Intrinsic::x86_avx2_psllv_q_256:
10525       Opcode = ISD::SHL;
10526       break;
10527     case Intrinsic::x86_avx2_psrlv_d:
10528     case Intrinsic::x86_avx2_psrlv_q:
10529     case Intrinsic::x86_avx2_psrlv_d_256:
10530     case Intrinsic::x86_avx2_psrlv_q_256:
10531       Opcode = ISD::SRL;
10532       break;
10533     case Intrinsic::x86_avx2_psrav_d:
10534     case Intrinsic::x86_avx2_psrav_d_256:
10535       Opcode = ISD::SRA;
10536       break;
10537     }
10538     return DAG.getNode(Opcode, dl, Op.getValueType(),
10539                        Op.getOperand(1), Op.getOperand(2));
10540   }
10541
10542   case Intrinsic::x86_ssse3_pshuf_b_128:
10543   case Intrinsic::x86_avx2_pshuf_b:
10544     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10545                        Op.getOperand(1), Op.getOperand(2));
10546
10547   case Intrinsic::x86_ssse3_psign_b_128:
10548   case Intrinsic::x86_ssse3_psign_w_128:
10549   case Intrinsic::x86_ssse3_psign_d_128:
10550   case Intrinsic::x86_avx2_psign_b:
10551   case Intrinsic::x86_avx2_psign_w:
10552   case Intrinsic::x86_avx2_psign_d:
10553     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10554                        Op.getOperand(1), Op.getOperand(2));
10555
10556   case Intrinsic::x86_sse41_insertps:
10557     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10558                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10559
10560   case Intrinsic::x86_avx_vperm2f128_ps_256:
10561   case Intrinsic::x86_avx_vperm2f128_pd_256:
10562   case Intrinsic::x86_avx_vperm2f128_si_256:
10563   case Intrinsic::x86_avx2_vperm2i128:
10564     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10565                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10566
10567   case Intrinsic::x86_avx2_permd:
10568   case Intrinsic::x86_avx2_permps:
10569     // Operands intentionally swapped. Mask is last operand to intrinsic,
10570     // but second operand for node/intruction.
10571     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10572                        Op.getOperand(2), Op.getOperand(1));
10573
10574   case Intrinsic::x86_sse_sqrt_ps:
10575   case Intrinsic::x86_sse2_sqrt_pd:
10576   case Intrinsic::x86_avx_sqrt_ps_256:
10577   case Intrinsic::x86_avx_sqrt_pd_256:
10578     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10579
10580   // ptest and testp intrinsics. The intrinsic these come from are designed to
10581   // return an integer value, not just an instruction so lower it to the ptest
10582   // or testp pattern and a setcc for the result.
10583   case Intrinsic::x86_sse41_ptestz:
10584   case Intrinsic::x86_sse41_ptestc:
10585   case Intrinsic::x86_sse41_ptestnzc:
10586   case Intrinsic::x86_avx_ptestz_256:
10587   case Intrinsic::x86_avx_ptestc_256:
10588   case Intrinsic::x86_avx_ptestnzc_256:
10589   case Intrinsic::x86_avx_vtestz_ps:
10590   case Intrinsic::x86_avx_vtestc_ps:
10591   case Intrinsic::x86_avx_vtestnzc_ps:
10592   case Intrinsic::x86_avx_vtestz_pd:
10593   case Intrinsic::x86_avx_vtestc_pd:
10594   case Intrinsic::x86_avx_vtestnzc_pd:
10595   case Intrinsic::x86_avx_vtestz_ps_256:
10596   case Intrinsic::x86_avx_vtestc_ps_256:
10597   case Intrinsic::x86_avx_vtestnzc_ps_256:
10598   case Intrinsic::x86_avx_vtestz_pd_256:
10599   case Intrinsic::x86_avx_vtestc_pd_256:
10600   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10601     bool IsTestPacked = false;
10602     unsigned X86CC;
10603     switch (IntNo) {
10604     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10605     case Intrinsic::x86_avx_vtestz_ps:
10606     case Intrinsic::x86_avx_vtestz_pd:
10607     case Intrinsic::x86_avx_vtestz_ps_256:
10608     case Intrinsic::x86_avx_vtestz_pd_256:
10609       IsTestPacked = true; // Fallthrough
10610     case Intrinsic::x86_sse41_ptestz:
10611     case Intrinsic::x86_avx_ptestz_256:
10612       // ZF = 1
10613       X86CC = X86::COND_E;
10614       break;
10615     case Intrinsic::x86_avx_vtestc_ps:
10616     case Intrinsic::x86_avx_vtestc_pd:
10617     case Intrinsic::x86_avx_vtestc_ps_256:
10618     case Intrinsic::x86_avx_vtestc_pd_256:
10619       IsTestPacked = true; // Fallthrough
10620     case Intrinsic::x86_sse41_ptestc:
10621     case Intrinsic::x86_avx_ptestc_256:
10622       // CF = 1
10623       X86CC = X86::COND_B;
10624       break;
10625     case Intrinsic::x86_avx_vtestnzc_ps:
10626     case Intrinsic::x86_avx_vtestnzc_pd:
10627     case Intrinsic::x86_avx_vtestnzc_ps_256:
10628     case Intrinsic::x86_avx_vtestnzc_pd_256:
10629       IsTestPacked = true; // Fallthrough
10630     case Intrinsic::x86_sse41_ptestnzc:
10631     case Intrinsic::x86_avx_ptestnzc_256:
10632       // ZF and CF = 0
10633       X86CC = X86::COND_A;
10634       break;
10635     }
10636
10637     SDValue LHS = Op.getOperand(1);
10638     SDValue RHS = Op.getOperand(2);
10639     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10640     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10641     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10642     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10643     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10644   }
10645
10646   // SSE/AVX shift intrinsics
10647   case Intrinsic::x86_sse2_psll_w:
10648   case Intrinsic::x86_sse2_psll_d:
10649   case Intrinsic::x86_sse2_psll_q:
10650   case Intrinsic::x86_avx2_psll_w:
10651   case Intrinsic::x86_avx2_psll_d:
10652   case Intrinsic::x86_avx2_psll_q:
10653   case Intrinsic::x86_sse2_psrl_w:
10654   case Intrinsic::x86_sse2_psrl_d:
10655   case Intrinsic::x86_sse2_psrl_q:
10656   case Intrinsic::x86_avx2_psrl_w:
10657   case Intrinsic::x86_avx2_psrl_d:
10658   case Intrinsic::x86_avx2_psrl_q:
10659   case Intrinsic::x86_sse2_psra_w:
10660   case Intrinsic::x86_sse2_psra_d:
10661   case Intrinsic::x86_avx2_psra_w:
10662   case Intrinsic::x86_avx2_psra_d: {
10663     unsigned Opcode;
10664     switch (IntNo) {
10665     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10666     case Intrinsic::x86_sse2_psll_w:
10667     case Intrinsic::x86_sse2_psll_d:
10668     case Intrinsic::x86_sse2_psll_q:
10669     case Intrinsic::x86_avx2_psll_w:
10670     case Intrinsic::x86_avx2_psll_d:
10671     case Intrinsic::x86_avx2_psll_q:
10672       Opcode = X86ISD::VSHL;
10673       break;
10674     case Intrinsic::x86_sse2_psrl_w:
10675     case Intrinsic::x86_sse2_psrl_d:
10676     case Intrinsic::x86_sse2_psrl_q:
10677     case Intrinsic::x86_avx2_psrl_w:
10678     case Intrinsic::x86_avx2_psrl_d:
10679     case Intrinsic::x86_avx2_psrl_q:
10680       Opcode = X86ISD::VSRL;
10681       break;
10682     case Intrinsic::x86_sse2_psra_w:
10683     case Intrinsic::x86_sse2_psra_d:
10684     case Intrinsic::x86_avx2_psra_w:
10685     case Intrinsic::x86_avx2_psra_d:
10686       Opcode = X86ISD::VSRA;
10687       break;
10688     }
10689     return DAG.getNode(Opcode, dl, Op.getValueType(),
10690                        Op.getOperand(1), Op.getOperand(2));
10691   }
10692
10693   // SSE/AVX immediate shift intrinsics
10694   case Intrinsic::x86_sse2_pslli_w:
10695   case Intrinsic::x86_sse2_pslli_d:
10696   case Intrinsic::x86_sse2_pslli_q:
10697   case Intrinsic::x86_avx2_pslli_w:
10698   case Intrinsic::x86_avx2_pslli_d:
10699   case Intrinsic::x86_avx2_pslli_q:
10700   case Intrinsic::x86_sse2_psrli_w:
10701   case Intrinsic::x86_sse2_psrli_d:
10702   case Intrinsic::x86_sse2_psrli_q:
10703   case Intrinsic::x86_avx2_psrli_w:
10704   case Intrinsic::x86_avx2_psrli_d:
10705   case Intrinsic::x86_avx2_psrli_q:
10706   case Intrinsic::x86_sse2_psrai_w:
10707   case Intrinsic::x86_sse2_psrai_d:
10708   case Intrinsic::x86_avx2_psrai_w:
10709   case Intrinsic::x86_avx2_psrai_d: {
10710     unsigned Opcode;
10711     switch (IntNo) {
10712     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10713     case Intrinsic::x86_sse2_pslli_w:
10714     case Intrinsic::x86_sse2_pslli_d:
10715     case Intrinsic::x86_sse2_pslli_q:
10716     case Intrinsic::x86_avx2_pslli_w:
10717     case Intrinsic::x86_avx2_pslli_d:
10718     case Intrinsic::x86_avx2_pslli_q:
10719       Opcode = X86ISD::VSHLI;
10720       break;
10721     case Intrinsic::x86_sse2_psrli_w:
10722     case Intrinsic::x86_sse2_psrli_d:
10723     case Intrinsic::x86_sse2_psrli_q:
10724     case Intrinsic::x86_avx2_psrli_w:
10725     case Intrinsic::x86_avx2_psrli_d:
10726     case Intrinsic::x86_avx2_psrli_q:
10727       Opcode = X86ISD::VSRLI;
10728       break;
10729     case Intrinsic::x86_sse2_psrai_w:
10730     case Intrinsic::x86_sse2_psrai_d:
10731     case Intrinsic::x86_avx2_psrai_w:
10732     case Intrinsic::x86_avx2_psrai_d:
10733       Opcode = X86ISD::VSRAI;
10734       break;
10735     }
10736     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10737                                Op.getOperand(1), Op.getOperand(2), DAG);
10738   }
10739
10740   case Intrinsic::x86_sse42_pcmpistria128:
10741   case Intrinsic::x86_sse42_pcmpestria128:
10742   case Intrinsic::x86_sse42_pcmpistric128:
10743   case Intrinsic::x86_sse42_pcmpestric128:
10744   case Intrinsic::x86_sse42_pcmpistrio128:
10745   case Intrinsic::x86_sse42_pcmpestrio128:
10746   case Intrinsic::x86_sse42_pcmpistris128:
10747   case Intrinsic::x86_sse42_pcmpestris128:
10748   case Intrinsic::x86_sse42_pcmpistriz128:
10749   case Intrinsic::x86_sse42_pcmpestriz128: {
10750     unsigned Opcode;
10751     unsigned X86CC;
10752     switch (IntNo) {
10753     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10754     case Intrinsic::x86_sse42_pcmpistria128:
10755       Opcode = X86ISD::PCMPISTRI;
10756       X86CC = X86::COND_A;
10757       break;
10758     case Intrinsic::x86_sse42_pcmpestria128:
10759       Opcode = X86ISD::PCMPESTRI;
10760       X86CC = X86::COND_A;
10761       break;
10762     case Intrinsic::x86_sse42_pcmpistric128:
10763       Opcode = X86ISD::PCMPISTRI;
10764       X86CC = X86::COND_B;
10765       break;
10766     case Intrinsic::x86_sse42_pcmpestric128:
10767       Opcode = X86ISD::PCMPESTRI;
10768       X86CC = X86::COND_B;
10769       break;
10770     case Intrinsic::x86_sse42_pcmpistrio128:
10771       Opcode = X86ISD::PCMPISTRI;
10772       X86CC = X86::COND_O;
10773       break;
10774     case Intrinsic::x86_sse42_pcmpestrio128:
10775       Opcode = X86ISD::PCMPESTRI;
10776       X86CC = X86::COND_O;
10777       break;
10778     case Intrinsic::x86_sse42_pcmpistris128:
10779       Opcode = X86ISD::PCMPISTRI;
10780       X86CC = X86::COND_S;
10781       break;
10782     case Intrinsic::x86_sse42_pcmpestris128:
10783       Opcode = X86ISD::PCMPESTRI;
10784       X86CC = X86::COND_S;
10785       break;
10786     case Intrinsic::x86_sse42_pcmpistriz128:
10787       Opcode = X86ISD::PCMPISTRI;
10788       X86CC = X86::COND_E;
10789       break;
10790     case Intrinsic::x86_sse42_pcmpestriz128:
10791       Opcode = X86ISD::PCMPESTRI;
10792       X86CC = X86::COND_E;
10793       break;
10794     }
10795     SmallVector<SDValue, 5> NewOps;
10796     NewOps.append(Op->op_begin()+1, Op->op_end());
10797     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10798     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10799     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10800                                 DAG.getConstant(X86CC, MVT::i8),
10801                                 SDValue(PCMP.getNode(), 1));
10802     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10803   }
10804
10805   case Intrinsic::x86_sse42_pcmpistri128:
10806   case Intrinsic::x86_sse42_pcmpestri128: {
10807     unsigned Opcode;
10808     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10809       Opcode = X86ISD::PCMPISTRI;
10810     else
10811       Opcode = X86ISD::PCMPESTRI;
10812
10813     SmallVector<SDValue, 5> NewOps;
10814     NewOps.append(Op->op_begin()+1, Op->op_end());
10815     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10816     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10817   }
10818   case Intrinsic::x86_fma_vfmadd_ps:
10819   case Intrinsic::x86_fma_vfmadd_pd:
10820   case Intrinsic::x86_fma_vfmsub_ps:
10821   case Intrinsic::x86_fma_vfmsub_pd:
10822   case Intrinsic::x86_fma_vfnmadd_ps:
10823   case Intrinsic::x86_fma_vfnmadd_pd:
10824   case Intrinsic::x86_fma_vfnmsub_ps:
10825   case Intrinsic::x86_fma_vfnmsub_pd:
10826   case Intrinsic::x86_fma_vfmaddsub_ps:
10827   case Intrinsic::x86_fma_vfmaddsub_pd:
10828   case Intrinsic::x86_fma_vfmsubadd_ps:
10829   case Intrinsic::x86_fma_vfmsubadd_pd:
10830   case Intrinsic::x86_fma_vfmadd_ps_256:
10831   case Intrinsic::x86_fma_vfmadd_pd_256:
10832   case Intrinsic::x86_fma_vfmsub_ps_256:
10833   case Intrinsic::x86_fma_vfmsub_pd_256:
10834   case Intrinsic::x86_fma_vfnmadd_ps_256:
10835   case Intrinsic::x86_fma_vfnmadd_pd_256:
10836   case Intrinsic::x86_fma_vfnmsub_ps_256:
10837   case Intrinsic::x86_fma_vfnmsub_pd_256:
10838   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10839   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10840   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10841   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10842     unsigned Opc;
10843     switch (IntNo) {
10844     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10845     case Intrinsic::x86_fma_vfmadd_ps:
10846     case Intrinsic::x86_fma_vfmadd_pd:
10847     case Intrinsic::x86_fma_vfmadd_ps_256:
10848     case Intrinsic::x86_fma_vfmadd_pd_256:
10849       Opc = X86ISD::FMADD;
10850       break;
10851     case Intrinsic::x86_fma_vfmsub_ps:
10852     case Intrinsic::x86_fma_vfmsub_pd:
10853     case Intrinsic::x86_fma_vfmsub_ps_256:
10854     case Intrinsic::x86_fma_vfmsub_pd_256:
10855       Opc = X86ISD::FMSUB;
10856       break;
10857     case Intrinsic::x86_fma_vfnmadd_ps:
10858     case Intrinsic::x86_fma_vfnmadd_pd:
10859     case Intrinsic::x86_fma_vfnmadd_ps_256:
10860     case Intrinsic::x86_fma_vfnmadd_pd_256:
10861       Opc = X86ISD::FNMADD;
10862       break;
10863     case Intrinsic::x86_fma_vfnmsub_ps:
10864     case Intrinsic::x86_fma_vfnmsub_pd:
10865     case Intrinsic::x86_fma_vfnmsub_ps_256:
10866     case Intrinsic::x86_fma_vfnmsub_pd_256:
10867       Opc = X86ISD::FNMSUB;
10868       break;
10869     case Intrinsic::x86_fma_vfmaddsub_ps:
10870     case Intrinsic::x86_fma_vfmaddsub_pd:
10871     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10872     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10873       Opc = X86ISD::FMADDSUB;
10874       break;
10875     case Intrinsic::x86_fma_vfmsubadd_ps:
10876     case Intrinsic::x86_fma_vfmsubadd_pd:
10877     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10878     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10879       Opc = X86ISD::FMSUBADD;
10880       break;
10881     }
10882
10883     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10884                        Op.getOperand(2), Op.getOperand(3));
10885   }
10886   }
10887 }
10888
10889 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10890   DebugLoc dl = Op.getDebugLoc();
10891   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10892   switch (IntNo) {
10893   default: return SDValue();    // Don't custom lower most intrinsics.
10894
10895   // RDRAND intrinsics.
10896   case Intrinsic::x86_rdrand_16:
10897   case Intrinsic::x86_rdrand_32:
10898   case Intrinsic::x86_rdrand_64: {
10899     // Emit the node with the right value type.
10900     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10901     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10902
10903     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10904     // return the value from Rand, which is always 0, casted to i32.
10905     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10906                       DAG.getConstant(1, Op->getValueType(1)),
10907                       DAG.getConstant(X86::COND_B, MVT::i32),
10908                       SDValue(Result.getNode(), 1) };
10909     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10910                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10911                                   Ops, 4);
10912
10913     // Return { result, isValid, chain }.
10914     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10915                        SDValue(Result.getNode(), 2));
10916   }
10917   }
10918 }
10919
10920 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10921                                            SelectionDAG &DAG) const {
10922   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10923   MFI->setReturnAddressIsTaken(true);
10924
10925   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10926   DebugLoc dl = Op.getDebugLoc();
10927   EVT PtrVT = getPointerTy();
10928
10929   if (Depth > 0) {
10930     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10931     SDValue Offset =
10932       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10933     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10934                        DAG.getNode(ISD::ADD, dl, PtrVT,
10935                                    FrameAddr, Offset),
10936                        MachinePointerInfo(), false, false, false, 0);
10937   }
10938
10939   // Just load the return address.
10940   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10941   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10942                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10943 }
10944
10945 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10946   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10947   MFI->setFrameAddressIsTaken(true);
10948
10949   EVT VT = Op.getValueType();
10950   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10951   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10952   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10953   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10954   while (Depth--)
10955     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10956                             MachinePointerInfo(),
10957                             false, false, false, 0);
10958   return FrameAddr;
10959 }
10960
10961 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10962                                                      SelectionDAG &DAG) const {
10963   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10964 }
10965
10966 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10967   SDValue Chain     = Op.getOperand(0);
10968   SDValue Offset    = Op.getOperand(1);
10969   SDValue Handler   = Op.getOperand(2);
10970   DebugLoc dl       = Op.getDebugLoc();
10971
10972   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10973                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10974                                      getPointerTy());
10975   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10976
10977   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10978                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10979   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10980   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10981                        false, false, 0);
10982   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10983
10984   return DAG.getNode(X86ISD::EH_RETURN, dl,
10985                      MVT::Other,
10986                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10987 }
10988
10989 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10990                                                SelectionDAG &DAG) const {
10991   DebugLoc DL = Op.getDebugLoc();
10992   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10993                      DAG.getVTList(MVT::i32, MVT::Other),
10994                      Op.getOperand(0), Op.getOperand(1));
10995 }
10996
10997 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10998                                                 SelectionDAG &DAG) const {
10999   DebugLoc DL = Op.getDebugLoc();
11000   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11001                      Op.getOperand(0), Op.getOperand(1));
11002 }
11003
11004 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11005   return Op.getOperand(0);
11006 }
11007
11008 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11009                                                 SelectionDAG &DAG) const {
11010   SDValue Root = Op.getOperand(0);
11011   SDValue Trmp = Op.getOperand(1); // trampoline
11012   SDValue FPtr = Op.getOperand(2); // nested function
11013   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11014   DebugLoc dl  = Op.getDebugLoc();
11015
11016   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11017   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11018
11019   if (Subtarget->is64Bit()) {
11020     SDValue OutChains[6];
11021
11022     // Large code-model.
11023     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11024     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11025
11026     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11027     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11028
11029     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11030
11031     // Load the pointer to the nested function into R11.
11032     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11033     SDValue Addr = Trmp;
11034     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11035                                 Addr, MachinePointerInfo(TrmpAddr),
11036                                 false, false, 0);
11037
11038     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11039                        DAG.getConstant(2, MVT::i64));
11040     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11041                                 MachinePointerInfo(TrmpAddr, 2),
11042                                 false, false, 2);
11043
11044     // Load the 'nest' parameter value into R10.
11045     // R10 is specified in X86CallingConv.td
11046     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11047     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11048                        DAG.getConstant(10, MVT::i64));
11049     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11050                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11051                                 false, false, 0);
11052
11053     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11054                        DAG.getConstant(12, MVT::i64));
11055     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11056                                 MachinePointerInfo(TrmpAddr, 12),
11057                                 false, false, 2);
11058
11059     // Jump to the nested function.
11060     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11061     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11062                        DAG.getConstant(20, MVT::i64));
11063     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11064                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11065                                 false, false, 0);
11066
11067     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11068     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11069                        DAG.getConstant(22, MVT::i64));
11070     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11071                                 MachinePointerInfo(TrmpAddr, 22),
11072                                 false, false, 0);
11073
11074     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11075   } else {
11076     const Function *Func =
11077       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11078     CallingConv::ID CC = Func->getCallingConv();
11079     unsigned NestReg;
11080
11081     switch (CC) {
11082     default:
11083       llvm_unreachable("Unsupported calling convention");
11084     case CallingConv::C:
11085     case CallingConv::X86_StdCall: {
11086       // Pass 'nest' parameter in ECX.
11087       // Must be kept in sync with X86CallingConv.td
11088       NestReg = X86::ECX;
11089
11090       // Check that ECX wasn't needed by an 'inreg' parameter.
11091       FunctionType *FTy = Func->getFunctionType();
11092       const AttributeSet &Attrs = Func->getAttributes();
11093
11094       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11095         unsigned InRegCount = 0;
11096         unsigned Idx = 1;
11097
11098         for (FunctionType::param_iterator I = FTy->param_begin(),
11099              E = FTy->param_end(); I != E; ++I, ++Idx)
11100           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11101             // FIXME: should only count parameters that are lowered to integers.
11102             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11103
11104         if (InRegCount > 2) {
11105           report_fatal_error("Nest register in use - reduce number of inreg"
11106                              " parameters!");
11107         }
11108       }
11109       break;
11110     }
11111     case CallingConv::X86_FastCall:
11112     case CallingConv::X86_ThisCall:
11113     case CallingConv::Fast:
11114       // Pass 'nest' parameter in EAX.
11115       // Must be kept in sync with X86CallingConv.td
11116       NestReg = X86::EAX;
11117       break;
11118     }
11119
11120     SDValue OutChains[4];
11121     SDValue Addr, Disp;
11122
11123     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11124                        DAG.getConstant(10, MVT::i32));
11125     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11126
11127     // This is storing the opcode for MOV32ri.
11128     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11129     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11130     OutChains[0] = DAG.getStore(Root, dl,
11131                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11132                                 Trmp, MachinePointerInfo(TrmpAddr),
11133                                 false, false, 0);
11134
11135     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11136                        DAG.getConstant(1, MVT::i32));
11137     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11138                                 MachinePointerInfo(TrmpAddr, 1),
11139                                 false, false, 1);
11140
11141     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11142     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11143                        DAG.getConstant(5, MVT::i32));
11144     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11145                                 MachinePointerInfo(TrmpAddr, 5),
11146                                 false, false, 1);
11147
11148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11149                        DAG.getConstant(6, MVT::i32));
11150     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11151                                 MachinePointerInfo(TrmpAddr, 6),
11152                                 false, false, 1);
11153
11154     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11155   }
11156 }
11157
11158 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11159                                             SelectionDAG &DAG) const {
11160   /*
11161    The rounding mode is in bits 11:10 of FPSR, and has the following
11162    settings:
11163      00 Round to nearest
11164      01 Round to -inf
11165      10 Round to +inf
11166      11 Round to 0
11167
11168   FLT_ROUNDS, on the other hand, expects the following:
11169     -1 Undefined
11170      0 Round to 0
11171      1 Round to nearest
11172      2 Round to +inf
11173      3 Round to -inf
11174
11175   To perform the conversion, we do:
11176     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11177   */
11178
11179   MachineFunction &MF = DAG.getMachineFunction();
11180   const TargetMachine &TM = MF.getTarget();
11181   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11182   unsigned StackAlignment = TFI.getStackAlignment();
11183   EVT VT = Op.getValueType();
11184   DebugLoc DL = Op.getDebugLoc();
11185
11186   // Save FP Control Word to stack slot
11187   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11188   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11189
11190   MachineMemOperand *MMO =
11191    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11192                            MachineMemOperand::MOStore, 2, 2);
11193
11194   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11195   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11196                                           DAG.getVTList(MVT::Other),
11197                                           Ops, 2, MVT::i16, MMO);
11198
11199   // Load FP Control Word from stack slot
11200   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11201                             MachinePointerInfo(), false, false, false, 0);
11202
11203   // Transform as necessary
11204   SDValue CWD1 =
11205     DAG.getNode(ISD::SRL, DL, MVT::i16,
11206                 DAG.getNode(ISD::AND, DL, MVT::i16,
11207                             CWD, DAG.getConstant(0x800, MVT::i16)),
11208                 DAG.getConstant(11, MVT::i8));
11209   SDValue CWD2 =
11210     DAG.getNode(ISD::SRL, DL, MVT::i16,
11211                 DAG.getNode(ISD::AND, DL, MVT::i16,
11212                             CWD, DAG.getConstant(0x400, MVT::i16)),
11213                 DAG.getConstant(9, MVT::i8));
11214
11215   SDValue RetVal =
11216     DAG.getNode(ISD::AND, DL, MVT::i16,
11217                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11218                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11219                             DAG.getConstant(1, MVT::i16)),
11220                 DAG.getConstant(3, MVT::i16));
11221
11222   return DAG.getNode((VT.getSizeInBits() < 16 ?
11223                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11224 }
11225
11226 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11227   EVT VT = Op.getValueType();
11228   EVT OpVT = VT;
11229   unsigned NumBits = VT.getSizeInBits();
11230   DebugLoc dl = Op.getDebugLoc();
11231
11232   Op = Op.getOperand(0);
11233   if (VT == MVT::i8) {
11234     // Zero extend to i32 since there is not an i8 bsr.
11235     OpVT = MVT::i32;
11236     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11237   }
11238
11239   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11240   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11241   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11242
11243   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11244   SDValue Ops[] = {
11245     Op,
11246     DAG.getConstant(NumBits+NumBits-1, OpVT),
11247     DAG.getConstant(X86::COND_E, MVT::i8),
11248     Op.getValue(1)
11249   };
11250   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11251
11252   // Finally xor with NumBits-1.
11253   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11254
11255   if (VT == MVT::i8)
11256     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11257   return Op;
11258 }
11259
11260 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11261   EVT VT = Op.getValueType();
11262   EVT OpVT = VT;
11263   unsigned NumBits = VT.getSizeInBits();
11264   DebugLoc dl = Op.getDebugLoc();
11265
11266   Op = Op.getOperand(0);
11267   if (VT == MVT::i8) {
11268     // Zero extend to i32 since there is not an i8 bsr.
11269     OpVT = MVT::i32;
11270     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11271   }
11272
11273   // Issue a bsr (scan bits in reverse).
11274   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11275   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11276
11277   // And xor with NumBits-1.
11278   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11279
11280   if (VT == MVT::i8)
11281     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11282   return Op;
11283 }
11284
11285 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11286   EVT VT = Op.getValueType();
11287   unsigned NumBits = VT.getSizeInBits();
11288   DebugLoc dl = Op.getDebugLoc();
11289   Op = Op.getOperand(0);
11290
11291   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11292   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11293   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11294
11295   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11296   SDValue Ops[] = {
11297     Op,
11298     DAG.getConstant(NumBits, VT),
11299     DAG.getConstant(X86::COND_E, MVT::i8),
11300     Op.getValue(1)
11301   };
11302   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11303 }
11304
11305 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11306 // ones, and then concatenate the result back.
11307 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11308   EVT VT = Op.getValueType();
11309
11310   assert(VT.is256BitVector() && VT.isInteger() &&
11311          "Unsupported value type for operation");
11312
11313   unsigned NumElems = VT.getVectorNumElements();
11314   DebugLoc dl = Op.getDebugLoc();
11315
11316   // Extract the LHS vectors
11317   SDValue LHS = Op.getOperand(0);
11318   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11319   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11320
11321   // Extract the RHS vectors
11322   SDValue RHS = Op.getOperand(1);
11323   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11324   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11325
11326   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11327   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11328
11329   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11330                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11331                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11332 }
11333
11334 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11335   assert(Op.getValueType().is256BitVector() &&
11336          Op.getValueType().isInteger() &&
11337          "Only handle AVX 256-bit vector integer operation");
11338   return Lower256IntArith(Op, DAG);
11339 }
11340
11341 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11342   assert(Op.getValueType().is256BitVector() &&
11343          Op.getValueType().isInteger() &&
11344          "Only handle AVX 256-bit vector integer operation");
11345   return Lower256IntArith(Op, DAG);
11346 }
11347
11348 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11349                         SelectionDAG &DAG) {
11350   DebugLoc dl = Op.getDebugLoc();
11351   EVT VT = Op.getValueType();
11352
11353   // Decompose 256-bit ops into smaller 128-bit ops.
11354   if (VT.is256BitVector() && !Subtarget->hasInt256())
11355     return Lower256IntArith(Op, DAG);
11356
11357   SDValue A = Op.getOperand(0);
11358   SDValue B = Op.getOperand(1);
11359
11360   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11361   if (VT == MVT::v4i32) {
11362     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11363            "Should not custom lower when pmuldq is available!");
11364
11365     // Extract the odd parts.
11366     const int UnpackMask[] = { 1, -1, 3, -1 };
11367     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11368     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11369
11370     // Multiply the even parts.
11371     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11372     // Now multiply odd parts.
11373     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11374
11375     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11376     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11377
11378     // Merge the two vectors back together with a shuffle. This expands into 2
11379     // shuffles.
11380     const int ShufMask[] = { 0, 4, 2, 6 };
11381     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11382   }
11383
11384   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11385          "Only know how to lower V2I64/V4I64 multiply");
11386
11387   //  Ahi = psrlqi(a, 32);
11388   //  Bhi = psrlqi(b, 32);
11389   //
11390   //  AloBlo = pmuludq(a, b);
11391   //  AloBhi = pmuludq(a, Bhi);
11392   //  AhiBlo = pmuludq(Ahi, b);
11393
11394   //  AloBhi = psllqi(AloBhi, 32);
11395   //  AhiBlo = psllqi(AhiBlo, 32);
11396   //  return AloBlo + AloBhi + AhiBlo;
11397
11398   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11399
11400   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11401   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11402
11403   // Bit cast to 32-bit vectors for MULUDQ
11404   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11405   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11406   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11407   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11408   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11409
11410   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11411   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11412   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11413
11414   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11415   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11416
11417   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11418   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11419 }
11420
11421 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11422   EVT VT = Op.getValueType();
11423   EVT EltTy = VT.getVectorElementType();
11424   unsigned NumElts = VT.getVectorNumElements();
11425   SDValue N0 = Op.getOperand(0);
11426   DebugLoc dl = Op.getDebugLoc();
11427
11428   // Lower sdiv X, pow2-const.
11429   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11430   if (!C)
11431     return SDValue();
11432
11433   APInt SplatValue, SplatUndef;
11434   unsigned MinSplatBits;
11435   bool HasAnyUndefs;
11436   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11437     return SDValue();
11438
11439   if ((SplatValue != 0) &&
11440       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11441     unsigned lg2 = SplatValue.countTrailingZeros();
11442     // Splat the sign bit.
11443     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11444     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11445     // Add (N0 < 0) ? abs2 - 1 : 0;
11446     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11447     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11448     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11449     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11450     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11451
11452     // If we're dividing by a positive value, we're done.  Otherwise, we must
11453     // negate the result.
11454     if (SplatValue.isNonNegative())
11455       return SRA;
11456
11457     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11458     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11459     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11460   }
11461   return SDValue();
11462 }
11463
11464 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11465
11466   EVT VT = Op.getValueType();
11467   DebugLoc dl = Op.getDebugLoc();
11468   SDValue R = Op.getOperand(0);
11469   SDValue Amt = Op.getOperand(1);
11470   LLVMContext *Context = DAG.getContext();
11471
11472   if (!Subtarget->hasSSE2())
11473     return SDValue();
11474
11475   // Optimize shl/srl/sra with constant shift amount.
11476   if (isSplatVector(Amt.getNode())) {
11477     SDValue SclrAmt = Amt->getOperand(0);
11478     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11479       uint64_t ShiftAmt = C->getZExtValue();
11480
11481       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11482           (Subtarget->hasInt256() &&
11483            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11484         if (Op.getOpcode() == ISD::SHL)
11485           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11486                              DAG.getConstant(ShiftAmt, MVT::i32));
11487         if (Op.getOpcode() == ISD::SRL)
11488           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11489                              DAG.getConstant(ShiftAmt, MVT::i32));
11490         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11491           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11492                              DAG.getConstant(ShiftAmt, MVT::i32));
11493       }
11494
11495       if (VT == MVT::v16i8) {
11496         if (Op.getOpcode() == ISD::SHL) {
11497           // Make a large shift.
11498           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11499                                     DAG.getConstant(ShiftAmt, MVT::i32));
11500           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11501           // Zero out the rightmost bits.
11502           SmallVector<SDValue, 16> V(16,
11503                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11504                                                      MVT::i8));
11505           return DAG.getNode(ISD::AND, dl, VT, SHL,
11506                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11507         }
11508         if (Op.getOpcode() == ISD::SRL) {
11509           // Make a large shift.
11510           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11511                                     DAG.getConstant(ShiftAmt, MVT::i32));
11512           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11513           // Zero out the leftmost bits.
11514           SmallVector<SDValue, 16> V(16,
11515                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11516                                                      MVT::i8));
11517           return DAG.getNode(ISD::AND, dl, VT, SRL,
11518                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11519         }
11520         if (Op.getOpcode() == ISD::SRA) {
11521           if (ShiftAmt == 7) {
11522             // R s>> 7  ===  R s< 0
11523             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11524             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11525           }
11526
11527           // R s>> a === ((R u>> a) ^ m) - m
11528           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11529           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11530                                                          MVT::i8));
11531           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11532           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11533           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11534           return Res;
11535         }
11536         llvm_unreachable("Unknown shift opcode.");
11537       }
11538
11539       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11540         if (Op.getOpcode() == ISD::SHL) {
11541           // Make a large shift.
11542           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11543                                     DAG.getConstant(ShiftAmt, MVT::i32));
11544           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11545           // Zero out the rightmost bits.
11546           SmallVector<SDValue, 32> V(32,
11547                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11548                                                      MVT::i8));
11549           return DAG.getNode(ISD::AND, dl, VT, SHL,
11550                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11551         }
11552         if (Op.getOpcode() == ISD::SRL) {
11553           // Make a large shift.
11554           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11555                                     DAG.getConstant(ShiftAmt, MVT::i32));
11556           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11557           // Zero out the leftmost bits.
11558           SmallVector<SDValue, 32> V(32,
11559                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11560                                                      MVT::i8));
11561           return DAG.getNode(ISD::AND, dl, VT, SRL,
11562                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11563         }
11564         if (Op.getOpcode() == ISD::SRA) {
11565           if (ShiftAmt == 7) {
11566             // R s>> 7  ===  R s< 0
11567             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11568             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11569           }
11570
11571           // R s>> a === ((R u>> a) ^ m) - m
11572           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11573           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11574                                                          MVT::i8));
11575           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11576           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11577           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11578           return Res;
11579         }
11580         llvm_unreachable("Unknown shift opcode.");
11581       }
11582     }
11583   }
11584
11585   // Lower SHL with variable shift amount.
11586   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11587     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11588                      DAG.getConstant(23, MVT::i32));
11589
11590     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11591     Constant *C = ConstantDataVector::get(*Context, CV);
11592     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11593     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11594                                  MachinePointerInfo::getConstantPool(),
11595                                  false, false, false, 16);
11596
11597     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11598     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11599     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11600     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11601   }
11602   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11603     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11604
11605     // a = a << 5;
11606     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11607                      DAG.getConstant(5, MVT::i32));
11608     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11609
11610     // Turn 'a' into a mask suitable for VSELECT
11611     SDValue VSelM = DAG.getConstant(0x80, VT);
11612     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11613     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11614
11615     SDValue CM1 = DAG.getConstant(0x0f, VT);
11616     SDValue CM2 = DAG.getConstant(0x3f, VT);
11617
11618     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11619     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11620     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11621                             DAG.getConstant(4, MVT::i32), DAG);
11622     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11623     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11624
11625     // a += a
11626     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11627     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11628     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11629
11630     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11631     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11632     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11633                             DAG.getConstant(2, MVT::i32), DAG);
11634     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11635     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11636
11637     // a += a
11638     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11639     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11640     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11641
11642     // return VSELECT(r, r+r, a);
11643     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11644                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11645     return R;
11646   }
11647
11648   // Decompose 256-bit shifts into smaller 128-bit shifts.
11649   if (VT.is256BitVector()) {
11650     unsigned NumElems = VT.getVectorNumElements();
11651     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11652     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11653
11654     // Extract the two vectors
11655     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11656     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11657
11658     // Recreate the shift amount vectors
11659     SDValue Amt1, Amt2;
11660     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11661       // Constant shift amount
11662       SmallVector<SDValue, 4> Amt1Csts;
11663       SmallVector<SDValue, 4> Amt2Csts;
11664       for (unsigned i = 0; i != NumElems/2; ++i)
11665         Amt1Csts.push_back(Amt->getOperand(i));
11666       for (unsigned i = NumElems/2; i != NumElems; ++i)
11667         Amt2Csts.push_back(Amt->getOperand(i));
11668
11669       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11670                                  &Amt1Csts[0], NumElems/2);
11671       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11672                                  &Amt2Csts[0], NumElems/2);
11673     } else {
11674       // Variable shift amount
11675       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11676       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11677     }
11678
11679     // Issue new vector shifts for the smaller types
11680     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11681     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11682
11683     // Concatenate the result back
11684     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11685   }
11686
11687   return SDValue();
11688 }
11689
11690 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11691   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11692   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11693   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11694   // has only one use.
11695   SDNode *N = Op.getNode();
11696   SDValue LHS = N->getOperand(0);
11697   SDValue RHS = N->getOperand(1);
11698   unsigned BaseOp = 0;
11699   unsigned Cond = 0;
11700   DebugLoc DL = Op.getDebugLoc();
11701   switch (Op.getOpcode()) {
11702   default: llvm_unreachable("Unknown ovf instruction!");
11703   case ISD::SADDO:
11704     // A subtract of one will be selected as a INC. Note that INC doesn't
11705     // set CF, so we can't do this for UADDO.
11706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11707       if (C->isOne()) {
11708         BaseOp = X86ISD::INC;
11709         Cond = X86::COND_O;
11710         break;
11711       }
11712     BaseOp = X86ISD::ADD;
11713     Cond = X86::COND_O;
11714     break;
11715   case ISD::UADDO:
11716     BaseOp = X86ISD::ADD;
11717     Cond = X86::COND_B;
11718     break;
11719   case ISD::SSUBO:
11720     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11721     // set CF, so we can't do this for USUBO.
11722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11723       if (C->isOne()) {
11724         BaseOp = X86ISD::DEC;
11725         Cond = X86::COND_O;
11726         break;
11727       }
11728     BaseOp = X86ISD::SUB;
11729     Cond = X86::COND_O;
11730     break;
11731   case ISD::USUBO:
11732     BaseOp = X86ISD::SUB;
11733     Cond = X86::COND_B;
11734     break;
11735   case ISD::SMULO:
11736     BaseOp = X86ISD::SMUL;
11737     Cond = X86::COND_O;
11738     break;
11739   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11740     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11741                                  MVT::i32);
11742     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11743
11744     SDValue SetCC =
11745       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11746                   DAG.getConstant(X86::COND_O, MVT::i32),
11747                   SDValue(Sum.getNode(), 2));
11748
11749     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11750   }
11751   }
11752
11753   // Also sets EFLAGS.
11754   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11755   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11756
11757   SDValue SetCC =
11758     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11759                 DAG.getConstant(Cond, MVT::i32),
11760                 SDValue(Sum.getNode(), 1));
11761
11762   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11763 }
11764
11765 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11766                                                   SelectionDAG &DAG) const {
11767   DebugLoc dl = Op.getDebugLoc();
11768   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11769   EVT VT = Op.getValueType();
11770
11771   if (!Subtarget->hasSSE2() || !VT.isVector())
11772     return SDValue();
11773
11774   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11775                       ExtraVT.getScalarType().getSizeInBits();
11776   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11777
11778   switch (VT.getSimpleVT().SimpleTy) {
11779     default: return SDValue();
11780     case MVT::v8i32:
11781     case MVT::v16i16:
11782       if (!Subtarget->hasFp256())
11783         return SDValue();
11784       if (!Subtarget->hasInt256()) {
11785         // needs to be split
11786         unsigned NumElems = VT.getVectorNumElements();
11787
11788         // Extract the LHS vectors
11789         SDValue LHS = Op.getOperand(0);
11790         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11791         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11792
11793         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11794         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11795
11796         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11797         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11798         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11799                                    ExtraNumElems/2);
11800         SDValue Extra = DAG.getValueType(ExtraVT);
11801
11802         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11803         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11804
11805         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11806       }
11807       // fall through
11808     case MVT::v4i32:
11809     case MVT::v8i16: {
11810       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11811                                          Op.getOperand(0), ShAmt, DAG);
11812       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11813     }
11814   }
11815 }
11816
11817 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11818                               SelectionDAG &DAG) {
11819   DebugLoc dl = Op.getDebugLoc();
11820
11821   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11822   // There isn't any reason to disable it if the target processor supports it.
11823   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11824     SDValue Chain = Op.getOperand(0);
11825     SDValue Zero = DAG.getConstant(0, MVT::i32);
11826     SDValue Ops[] = {
11827       DAG.getRegister(X86::ESP, MVT::i32), // Base
11828       DAG.getTargetConstant(1, MVT::i8),   // Scale
11829       DAG.getRegister(0, MVT::i32),        // Index
11830       DAG.getTargetConstant(0, MVT::i32),  // Disp
11831       DAG.getRegister(0, MVT::i32),        // Segment.
11832       Zero,
11833       Chain
11834     };
11835     SDNode *Res =
11836       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11837                           array_lengthof(Ops));
11838     return SDValue(Res, 0);
11839   }
11840
11841   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11842   if (!isDev)
11843     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11844
11845   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11846   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11847   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11848   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11849
11850   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11851   if (!Op1 && !Op2 && !Op3 && Op4)
11852     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11853
11854   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11855   if (Op1 && !Op2 && !Op3 && !Op4)
11856     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11857
11858   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11859   //           (MFENCE)>;
11860   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11861 }
11862
11863 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11864                                  SelectionDAG &DAG) {
11865   DebugLoc dl = Op.getDebugLoc();
11866   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11867     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11868   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11869     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11870
11871   // The only fence that needs an instruction is a sequentially-consistent
11872   // cross-thread fence.
11873   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11874     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11875     // no-sse2). There isn't any reason to disable it if the target processor
11876     // supports it.
11877     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11878       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11879
11880     SDValue Chain = Op.getOperand(0);
11881     SDValue Zero = DAG.getConstant(0, MVT::i32);
11882     SDValue Ops[] = {
11883       DAG.getRegister(X86::ESP, MVT::i32), // Base
11884       DAG.getTargetConstant(1, MVT::i8),   // Scale
11885       DAG.getRegister(0, MVT::i32),        // Index
11886       DAG.getTargetConstant(0, MVT::i32),  // Disp
11887       DAG.getRegister(0, MVT::i32),        // Segment.
11888       Zero,
11889       Chain
11890     };
11891     SDNode *Res =
11892       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11893                          array_lengthof(Ops));
11894     return SDValue(Res, 0);
11895   }
11896
11897   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11898   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11899 }
11900
11901 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11902                              SelectionDAG &DAG) {
11903   EVT T = Op.getValueType();
11904   DebugLoc DL = Op.getDebugLoc();
11905   unsigned Reg = 0;
11906   unsigned size = 0;
11907   switch(T.getSimpleVT().SimpleTy) {
11908   default: llvm_unreachable("Invalid value type!");
11909   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11910   case MVT::i16: Reg = X86::AX;  size = 2; break;
11911   case MVT::i32: Reg = X86::EAX; size = 4; break;
11912   case MVT::i64:
11913     assert(Subtarget->is64Bit() && "Node not type legal!");
11914     Reg = X86::RAX; size = 8;
11915     break;
11916   }
11917   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11918                                     Op.getOperand(2), SDValue());
11919   SDValue Ops[] = { cpIn.getValue(0),
11920                     Op.getOperand(1),
11921                     Op.getOperand(3),
11922                     DAG.getTargetConstant(size, MVT::i8),
11923                     cpIn.getValue(1) };
11924   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11925   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11926   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11927                                            Ops, 5, T, MMO);
11928   SDValue cpOut =
11929     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11930   return cpOut;
11931 }
11932
11933 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11934                                      SelectionDAG &DAG) {
11935   assert(Subtarget->is64Bit() && "Result not type legalized?");
11936   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11937   SDValue TheChain = Op.getOperand(0);
11938   DebugLoc dl = Op.getDebugLoc();
11939   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11940   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11941   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11942                                    rax.getValue(2));
11943   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11944                             DAG.getConstant(32, MVT::i8));
11945   SDValue Ops[] = {
11946     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11947     rdx.getValue(1)
11948   };
11949   return DAG.getMergeValues(Ops, 2, dl);
11950 }
11951
11952 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11953   EVT SrcVT = Op.getOperand(0).getValueType();
11954   EVT DstVT = Op.getValueType();
11955   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11956          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11957   assert((DstVT == MVT::i64 ||
11958           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11959          "Unexpected custom BITCAST");
11960   // i64 <=> MMX conversions are Legal.
11961   if (SrcVT==MVT::i64 && DstVT.isVector())
11962     return Op;
11963   if (DstVT==MVT::i64 && SrcVT.isVector())
11964     return Op;
11965   // MMX <=> MMX conversions are Legal.
11966   if (SrcVT.isVector() && DstVT.isVector())
11967     return Op;
11968   // All other conversions need to be expanded.
11969   return SDValue();
11970 }
11971
11972 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11973   SDNode *Node = Op.getNode();
11974   DebugLoc dl = Node->getDebugLoc();
11975   EVT T = Node->getValueType(0);
11976   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11977                               DAG.getConstant(0, T), Node->getOperand(2));
11978   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11979                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11980                        Node->getOperand(0),
11981                        Node->getOperand(1), negOp,
11982                        cast<AtomicSDNode>(Node)->getSrcValue(),
11983                        cast<AtomicSDNode>(Node)->getAlignment(),
11984                        cast<AtomicSDNode>(Node)->getOrdering(),
11985                        cast<AtomicSDNode>(Node)->getSynchScope());
11986 }
11987
11988 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11989   SDNode *Node = Op.getNode();
11990   DebugLoc dl = Node->getDebugLoc();
11991   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11992
11993   // Convert seq_cst store -> xchg
11994   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11995   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11996   //        (The only way to get a 16-byte store is cmpxchg16b)
11997   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11998   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11999       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12000     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12001                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12002                                  Node->getOperand(0),
12003                                  Node->getOperand(1), Node->getOperand(2),
12004                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12005                                  cast<AtomicSDNode>(Node)->getOrdering(),
12006                                  cast<AtomicSDNode>(Node)->getSynchScope());
12007     return Swap.getValue(1);
12008   }
12009   // Other atomic stores have a simple pattern.
12010   return Op;
12011 }
12012
12013 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12014   EVT VT = Op.getNode()->getValueType(0);
12015
12016   // Let legalize expand this if it isn't a legal type yet.
12017   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12018     return SDValue();
12019
12020   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12021
12022   unsigned Opc;
12023   bool ExtraOp = false;
12024   switch (Op.getOpcode()) {
12025   default: llvm_unreachable("Invalid code");
12026   case ISD::ADDC: Opc = X86ISD::ADD; break;
12027   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12028   case ISD::SUBC: Opc = X86ISD::SUB; break;
12029   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12030   }
12031
12032   if (!ExtraOp)
12033     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12034                        Op.getOperand(1));
12035   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12036                      Op.getOperand(1), Op.getOperand(2));
12037 }
12038
12039 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12040   assert(Subtarget->isTargetDarwin());
12041  
12042   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12043   // which returns the values in two XMM registers.
12044   DebugLoc dl = Op.getDebugLoc();
12045   SDValue Arg = Op.getOperand(0);
12046   EVT ArgVT = Arg.getValueType();
12047   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12048   
12049   ArgListTy Args;
12050   ArgListEntry Entry;
12051   
12052   Entry.Node = Arg;
12053   Entry.Ty = ArgTy;
12054   Entry.isSExt = false;
12055   Entry.isZExt = false;
12056   Args.push_back(Entry);
12057   
12058   const char *LibcallName = (ArgVT == MVT::f64)
12059     ? "__sincos_stret" : "__sincosf_stret";
12060   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12061   
12062   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12063   TargetLowering::
12064   CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12065                        false, false, false, false, 0,
12066                        CallingConv::C, /*isTaillCall=*/false,
12067                        /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12068                        Callee, Args, DAG, dl);
12069   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12070   return CallResult.first;
12071 }
12072
12073 /// LowerOperation - Provide custom lowering hooks for some operations.
12074 ///
12075 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12076   switch (Op.getOpcode()) {
12077   default: llvm_unreachable("Should not custom lower this!");
12078   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12079   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12080   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12081   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12082   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12083   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12084   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12085   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12086   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12087   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12088   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12089   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12090   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12091   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12092   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12093   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12094   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12095   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12096   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12097   case ISD::SHL_PARTS:
12098   case ISD::SRA_PARTS:
12099   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12100   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12101   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12102   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12103   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12104   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12105   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12106   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12107   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12108   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12109   case ISD::FABS:               return LowerFABS(Op, DAG);
12110   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12111   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12112   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12113   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12114   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12115   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12116   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12117   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12118   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12119   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12120   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12121   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12122   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12123   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12124   case ISD::FRAME_TO_ARGS_OFFSET:
12125                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12126   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12127   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12128   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12129   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12130   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12131   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12132   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12133   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12134   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12135   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12136   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12137   case ISD::SRA:
12138   case ISD::SRL:
12139   case ISD::SHL:                return LowerShift(Op, DAG);
12140   case ISD::SADDO:
12141   case ISD::UADDO:
12142   case ISD::SSUBO:
12143   case ISD::USUBO:
12144   case ISD::SMULO:
12145   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12146   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12147   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12148   case ISD::ADDC:
12149   case ISD::ADDE:
12150   case ISD::SUBC:
12151   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12152   case ISD::ADD:                return LowerADD(Op, DAG);
12153   case ISD::SUB:                return LowerSUB(Op, DAG);
12154   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12155   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12156   }
12157 }
12158
12159 static void ReplaceATOMIC_LOAD(SDNode *Node,
12160                                   SmallVectorImpl<SDValue> &Results,
12161                                   SelectionDAG &DAG) {
12162   DebugLoc dl = Node->getDebugLoc();
12163   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12164
12165   // Convert wide load -> cmpxchg8b/cmpxchg16b
12166   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12167   //        (The only way to get a 16-byte load is cmpxchg16b)
12168   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12169   SDValue Zero = DAG.getConstant(0, VT);
12170   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12171                                Node->getOperand(0),
12172                                Node->getOperand(1), Zero, Zero,
12173                                cast<AtomicSDNode>(Node)->getMemOperand(),
12174                                cast<AtomicSDNode>(Node)->getOrdering(),
12175                                cast<AtomicSDNode>(Node)->getSynchScope());
12176   Results.push_back(Swap.getValue(0));
12177   Results.push_back(Swap.getValue(1));
12178 }
12179
12180 static void
12181 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12182                         SelectionDAG &DAG, unsigned NewOp) {
12183   DebugLoc dl = Node->getDebugLoc();
12184   assert (Node->getValueType(0) == MVT::i64 &&
12185           "Only know how to expand i64 atomics");
12186
12187   SDValue Chain = Node->getOperand(0);
12188   SDValue In1 = Node->getOperand(1);
12189   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12190                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12191   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12192                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12193   SDValue Ops[] = { Chain, In1, In2L, In2H };
12194   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12195   SDValue Result =
12196     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12197                             cast<MemSDNode>(Node)->getMemOperand());
12198   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12199   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12200   Results.push_back(Result.getValue(2));
12201 }
12202
12203 /// ReplaceNodeResults - Replace a node with an illegal result type
12204 /// with a new node built out of custom code.
12205 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12206                                            SmallVectorImpl<SDValue>&Results,
12207                                            SelectionDAG &DAG) const {
12208   DebugLoc dl = N->getDebugLoc();
12209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12210   switch (N->getOpcode()) {
12211   default:
12212     llvm_unreachable("Do not know how to custom type legalize this operation!");
12213   case ISD::SIGN_EXTEND_INREG:
12214   case ISD::ADDC:
12215   case ISD::ADDE:
12216   case ISD::SUBC:
12217   case ISD::SUBE:
12218     // We don't want to expand or promote these.
12219     return;
12220   case ISD::FP_TO_SINT:
12221   case ISD::FP_TO_UINT: {
12222     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12223
12224     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12225       return;
12226
12227     std::pair<SDValue,SDValue> Vals =
12228         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12229     SDValue FIST = Vals.first, StackSlot = Vals.second;
12230     if (FIST.getNode() != 0) {
12231       EVT VT = N->getValueType(0);
12232       // Return a load from the stack slot.
12233       if (StackSlot.getNode() != 0)
12234         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12235                                       MachinePointerInfo(),
12236                                       false, false, false, 0));
12237       else
12238         Results.push_back(FIST);
12239     }
12240     return;
12241   }
12242   case ISD::UINT_TO_FP: {
12243     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12244         N->getValueType(0) != MVT::v2f32)
12245       return;
12246     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12247                                  N->getOperand(0));
12248     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12249                                      MVT::f64);
12250     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12251     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12252                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12253     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12254     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12255     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12256     return;
12257   }
12258   case ISD::FP_ROUND: {
12259     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12260         return;
12261     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12262     Results.push_back(V);
12263     return;
12264   }
12265   case ISD::READCYCLECOUNTER: {
12266     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12267     SDValue TheChain = N->getOperand(0);
12268     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12269     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12270                                      rd.getValue(1));
12271     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12272                                      eax.getValue(2));
12273     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12274     SDValue Ops[] = { eax, edx };
12275     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12276     Results.push_back(edx.getValue(1));
12277     return;
12278   }
12279   case ISD::ATOMIC_CMP_SWAP: {
12280     EVT T = N->getValueType(0);
12281     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12282     bool Regs64bit = T == MVT::i128;
12283     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12284     SDValue cpInL, cpInH;
12285     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12286                         DAG.getConstant(0, HalfT));
12287     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12288                         DAG.getConstant(1, HalfT));
12289     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12290                              Regs64bit ? X86::RAX : X86::EAX,
12291                              cpInL, SDValue());
12292     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12293                              Regs64bit ? X86::RDX : X86::EDX,
12294                              cpInH, cpInL.getValue(1));
12295     SDValue swapInL, swapInH;
12296     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12297                           DAG.getConstant(0, HalfT));
12298     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12299                           DAG.getConstant(1, HalfT));
12300     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12301                                Regs64bit ? X86::RBX : X86::EBX,
12302                                swapInL, cpInH.getValue(1));
12303     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12304                                Regs64bit ? X86::RCX : X86::ECX,
12305                                swapInH, swapInL.getValue(1));
12306     SDValue Ops[] = { swapInH.getValue(0),
12307                       N->getOperand(1),
12308                       swapInH.getValue(1) };
12309     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12310     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12311     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12312                                   X86ISD::LCMPXCHG8_DAG;
12313     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12314                                              Ops, 3, T, MMO);
12315     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12316                                         Regs64bit ? X86::RAX : X86::EAX,
12317                                         HalfT, Result.getValue(1));
12318     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12319                                         Regs64bit ? X86::RDX : X86::EDX,
12320                                         HalfT, cpOutL.getValue(2));
12321     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12322     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12323     Results.push_back(cpOutH.getValue(1));
12324     return;
12325   }
12326   case ISD::ATOMIC_LOAD_ADD:
12327   case ISD::ATOMIC_LOAD_AND:
12328   case ISD::ATOMIC_LOAD_NAND:
12329   case ISD::ATOMIC_LOAD_OR:
12330   case ISD::ATOMIC_LOAD_SUB:
12331   case ISD::ATOMIC_LOAD_XOR:
12332   case ISD::ATOMIC_LOAD_MAX:
12333   case ISD::ATOMIC_LOAD_MIN:
12334   case ISD::ATOMIC_LOAD_UMAX:
12335   case ISD::ATOMIC_LOAD_UMIN:
12336   case ISD::ATOMIC_SWAP: {
12337     unsigned Opc;
12338     switch (N->getOpcode()) {
12339     default: llvm_unreachable("Unexpected opcode");
12340     case ISD::ATOMIC_LOAD_ADD:
12341       Opc = X86ISD::ATOMADD64_DAG;
12342       break;
12343     case ISD::ATOMIC_LOAD_AND:
12344       Opc = X86ISD::ATOMAND64_DAG;
12345       break;
12346     case ISD::ATOMIC_LOAD_NAND:
12347       Opc = X86ISD::ATOMNAND64_DAG;
12348       break;
12349     case ISD::ATOMIC_LOAD_OR:
12350       Opc = X86ISD::ATOMOR64_DAG;
12351       break;
12352     case ISD::ATOMIC_LOAD_SUB:
12353       Opc = X86ISD::ATOMSUB64_DAG;
12354       break;
12355     case ISD::ATOMIC_LOAD_XOR:
12356       Opc = X86ISD::ATOMXOR64_DAG;
12357       break;
12358     case ISD::ATOMIC_LOAD_MAX:
12359       Opc = X86ISD::ATOMMAX64_DAG;
12360       break;
12361     case ISD::ATOMIC_LOAD_MIN:
12362       Opc = X86ISD::ATOMMIN64_DAG;
12363       break;
12364     case ISD::ATOMIC_LOAD_UMAX:
12365       Opc = X86ISD::ATOMUMAX64_DAG;
12366       break;
12367     case ISD::ATOMIC_LOAD_UMIN:
12368       Opc = X86ISD::ATOMUMIN64_DAG;
12369       break;
12370     case ISD::ATOMIC_SWAP:
12371       Opc = X86ISD::ATOMSWAP64_DAG;
12372       break;
12373     }
12374     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12375     return;
12376   }
12377   case ISD::ATOMIC_LOAD:
12378     ReplaceATOMIC_LOAD(N, Results, DAG);
12379   }
12380 }
12381
12382 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12383   switch (Opcode) {
12384   default: return NULL;
12385   case X86ISD::BSF:                return "X86ISD::BSF";
12386   case X86ISD::BSR:                return "X86ISD::BSR";
12387   case X86ISD::SHLD:               return "X86ISD::SHLD";
12388   case X86ISD::SHRD:               return "X86ISD::SHRD";
12389   case X86ISD::FAND:               return "X86ISD::FAND";
12390   case X86ISD::FOR:                return "X86ISD::FOR";
12391   case X86ISD::FXOR:               return "X86ISD::FXOR";
12392   case X86ISD::FSRL:               return "X86ISD::FSRL";
12393   case X86ISD::FILD:               return "X86ISD::FILD";
12394   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12395   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12396   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12397   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12398   case X86ISD::FLD:                return "X86ISD::FLD";
12399   case X86ISD::FST:                return "X86ISD::FST";
12400   case X86ISD::CALL:               return "X86ISD::CALL";
12401   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12402   case X86ISD::BT:                 return "X86ISD::BT";
12403   case X86ISD::CMP:                return "X86ISD::CMP";
12404   case X86ISD::COMI:               return "X86ISD::COMI";
12405   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12406   case X86ISD::SETCC:              return "X86ISD::SETCC";
12407   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12408   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12409   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12410   case X86ISD::CMOV:               return "X86ISD::CMOV";
12411   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12412   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12413   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12414   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12415   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12416   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12417   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12418   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12419   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12420   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12421   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12422   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12423   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12424   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12425   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12426   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12427   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12428   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12429   case X86ISD::HADD:               return "X86ISD::HADD";
12430   case X86ISD::HSUB:               return "X86ISD::HSUB";
12431   case X86ISD::FHADD:              return "X86ISD::FHADD";
12432   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12433   case X86ISD::UMAX:               return "X86ISD::UMAX";
12434   case X86ISD::UMIN:               return "X86ISD::UMIN";
12435   case X86ISD::SMAX:               return "X86ISD::SMAX";
12436   case X86ISD::SMIN:               return "X86ISD::SMIN";
12437   case X86ISD::FMAX:               return "X86ISD::FMAX";
12438   case X86ISD::FMIN:               return "X86ISD::FMIN";
12439   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12440   case X86ISD::FMINC:              return "X86ISD::FMINC";
12441   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12442   case X86ISD::FRCP:               return "X86ISD::FRCP";
12443   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12444   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12445   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12446   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12447   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12448   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12449   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12450   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12451   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12452   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12453   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12454   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12455   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12456   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12457   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12458   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12459   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12460   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12461   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12462   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12463   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12464   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12465   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12466   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12467   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12468   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12469   case X86ISD::VSHL:               return "X86ISD::VSHL";
12470   case X86ISD::VSRL:               return "X86ISD::VSRL";
12471   case X86ISD::VSRA:               return "X86ISD::VSRA";
12472   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12473   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12474   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12475   case X86ISD::CMPP:               return "X86ISD::CMPP";
12476   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12477   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12478   case X86ISD::ADD:                return "X86ISD::ADD";
12479   case X86ISD::SUB:                return "X86ISD::SUB";
12480   case X86ISD::ADC:                return "X86ISD::ADC";
12481   case X86ISD::SBB:                return "X86ISD::SBB";
12482   case X86ISD::SMUL:               return "X86ISD::SMUL";
12483   case X86ISD::UMUL:               return "X86ISD::UMUL";
12484   case X86ISD::INC:                return "X86ISD::INC";
12485   case X86ISD::DEC:                return "X86ISD::DEC";
12486   case X86ISD::OR:                 return "X86ISD::OR";
12487   case X86ISD::XOR:                return "X86ISD::XOR";
12488   case X86ISD::AND:                return "X86ISD::AND";
12489   case X86ISD::BLSI:               return "X86ISD::BLSI";
12490   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12491   case X86ISD::BLSR:               return "X86ISD::BLSR";
12492   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12493   case X86ISD::PTEST:              return "X86ISD::PTEST";
12494   case X86ISD::TESTP:              return "X86ISD::TESTP";
12495   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12496   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12497   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12498   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12499   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12500   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12501   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12502   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12503   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12504   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12505   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12506   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12507   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12508   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12509   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12510   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12511   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12512   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12513   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12514   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12515   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12516   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12517   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12518   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12519   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12520   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12521   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12522   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12523   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12524   case X86ISD::SAHF:               return "X86ISD::SAHF";
12525   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12526   case X86ISD::FMADD:              return "X86ISD::FMADD";
12527   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12528   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12529   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12530   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12531   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12532   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12533   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12534   }
12535 }
12536
12537 // isLegalAddressingMode - Return true if the addressing mode represented
12538 // by AM is legal for this target, for a load/store of the specified type.
12539 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12540                                               Type *Ty) const {
12541   // X86 supports extremely general addressing modes.
12542   CodeModel::Model M = getTargetMachine().getCodeModel();
12543   Reloc::Model R = getTargetMachine().getRelocationModel();
12544
12545   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12546   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12547     return false;
12548
12549   if (AM.BaseGV) {
12550     unsigned GVFlags =
12551       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12552
12553     // If a reference to this global requires an extra load, we can't fold it.
12554     if (isGlobalStubReference(GVFlags))
12555       return false;
12556
12557     // If BaseGV requires a register for the PIC base, we cannot also have a
12558     // BaseReg specified.
12559     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12560       return false;
12561
12562     // If lower 4G is not available, then we must use rip-relative addressing.
12563     if ((M != CodeModel::Small || R != Reloc::Static) &&
12564         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12565       return false;
12566   }
12567
12568   switch (AM.Scale) {
12569   case 0:
12570   case 1:
12571   case 2:
12572   case 4:
12573   case 8:
12574     // These scales always work.
12575     break;
12576   case 3:
12577   case 5:
12578   case 9:
12579     // These scales are formed with basereg+scalereg.  Only accept if there is
12580     // no basereg yet.
12581     if (AM.HasBaseReg)
12582       return false;
12583     break;
12584   default:  // Other stuff never works.
12585     return false;
12586   }
12587
12588   return true;
12589 }
12590
12591 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12592   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12593     return false;
12594   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12595   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12596   return NumBits1 > NumBits2;
12597 }
12598
12599 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12600   return isInt<32>(Imm);
12601 }
12602
12603 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12604   // Can also use sub to handle negated immediates.
12605   return isInt<32>(Imm);
12606 }
12607
12608 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12609   if (!VT1.isInteger() || !VT2.isInteger())
12610     return false;
12611   unsigned NumBits1 = VT1.getSizeInBits();
12612   unsigned NumBits2 = VT2.getSizeInBits();
12613   return NumBits1 > NumBits2;
12614 }
12615
12616 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12617   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12618   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12619 }
12620
12621 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12622   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12623   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12624 }
12625
12626 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12627   EVT VT1 = Val.getValueType();
12628   if (isZExtFree(VT1, VT2))
12629     return true;
12630
12631   if (Val.getOpcode() != ISD::LOAD)
12632     return false;
12633
12634   if (!VT1.isSimple() || !VT1.isInteger() ||
12635       !VT2.isSimple() || !VT2.isInteger())
12636     return false;
12637
12638   switch (VT1.getSimpleVT().SimpleTy) {
12639   default: break;
12640   case MVT::i8:
12641   case MVT::i16:
12642   case MVT::i32:
12643     // X86 has 8, 16, and 32-bit zero-extending loads.
12644     return true;
12645   }
12646
12647   return false;
12648 }
12649
12650 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12651   // i16 instructions are longer (0x66 prefix) and potentially slower.
12652   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12653 }
12654
12655 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12656 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12657 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12658 /// are assumed to be legal.
12659 bool
12660 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12661                                       EVT VT) const {
12662   // Very little shuffling can be done for 64-bit vectors right now.
12663   if (VT.getSizeInBits() == 64)
12664     return false;
12665
12666   // FIXME: pshufb, blends, shifts.
12667   return (VT.getVectorNumElements() == 2 ||
12668           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12669           isMOVLMask(M, VT) ||
12670           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12671           isPSHUFDMask(M, VT) ||
12672           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12673           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12674           isPALIGNRMask(M, VT, Subtarget) ||
12675           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12676           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12677           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12678           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12679 }
12680
12681 bool
12682 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12683                                           EVT VT) const {
12684   unsigned NumElts = VT.getVectorNumElements();
12685   // FIXME: This collection of masks seems suspect.
12686   if (NumElts == 2)
12687     return true;
12688   if (NumElts == 4 && VT.is128BitVector()) {
12689     return (isMOVLMask(Mask, VT)  ||
12690             isCommutedMOVLMask(Mask, VT, true) ||
12691             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12692             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12693   }
12694   return false;
12695 }
12696
12697 //===----------------------------------------------------------------------===//
12698 //                           X86 Scheduler Hooks
12699 //===----------------------------------------------------------------------===//
12700
12701 /// Utility function to emit xbegin specifying the start of an RTM region.
12702 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12703                                      const TargetInstrInfo *TII) {
12704   DebugLoc DL = MI->getDebugLoc();
12705
12706   const BasicBlock *BB = MBB->getBasicBlock();
12707   MachineFunction::iterator I = MBB;
12708   ++I;
12709
12710   // For the v = xbegin(), we generate
12711   //
12712   // thisMBB:
12713   //  xbegin sinkMBB
12714   //
12715   // mainMBB:
12716   //  eax = -1
12717   //
12718   // sinkMBB:
12719   //  v = eax
12720
12721   MachineBasicBlock *thisMBB = MBB;
12722   MachineFunction *MF = MBB->getParent();
12723   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12724   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12725   MF->insert(I, mainMBB);
12726   MF->insert(I, sinkMBB);
12727
12728   // Transfer the remainder of BB and its successor edges to sinkMBB.
12729   sinkMBB->splice(sinkMBB->begin(), MBB,
12730                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12731   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12732
12733   // thisMBB:
12734   //  xbegin sinkMBB
12735   //  # fallthrough to mainMBB
12736   //  # abortion to sinkMBB
12737   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12738   thisMBB->addSuccessor(mainMBB);
12739   thisMBB->addSuccessor(sinkMBB);
12740
12741   // mainMBB:
12742   //  EAX = -1
12743   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12744   mainMBB->addSuccessor(sinkMBB);
12745
12746   // sinkMBB:
12747   // EAX is live into the sinkMBB
12748   sinkMBB->addLiveIn(X86::EAX);
12749   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12750           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12751     .addReg(X86::EAX);
12752
12753   MI->eraseFromParent();
12754   return sinkMBB;
12755 }
12756
12757 // Get CMPXCHG opcode for the specified data type.
12758 static unsigned getCmpXChgOpcode(EVT VT) {
12759   switch (VT.getSimpleVT().SimpleTy) {
12760   case MVT::i8:  return X86::LCMPXCHG8;
12761   case MVT::i16: return X86::LCMPXCHG16;
12762   case MVT::i32: return X86::LCMPXCHG32;
12763   case MVT::i64: return X86::LCMPXCHG64;
12764   default:
12765     break;
12766   }
12767   llvm_unreachable("Invalid operand size!");
12768 }
12769
12770 // Get LOAD opcode for the specified data type.
12771 static unsigned getLoadOpcode(EVT VT) {
12772   switch (VT.getSimpleVT().SimpleTy) {
12773   case MVT::i8:  return X86::MOV8rm;
12774   case MVT::i16: return X86::MOV16rm;
12775   case MVT::i32: return X86::MOV32rm;
12776   case MVT::i64: return X86::MOV64rm;
12777   default:
12778     break;
12779   }
12780   llvm_unreachable("Invalid operand size!");
12781 }
12782
12783 // Get opcode of the non-atomic one from the specified atomic instruction.
12784 static unsigned getNonAtomicOpcode(unsigned Opc) {
12785   switch (Opc) {
12786   case X86::ATOMAND8:  return X86::AND8rr;
12787   case X86::ATOMAND16: return X86::AND16rr;
12788   case X86::ATOMAND32: return X86::AND32rr;
12789   case X86::ATOMAND64: return X86::AND64rr;
12790   case X86::ATOMOR8:   return X86::OR8rr;
12791   case X86::ATOMOR16:  return X86::OR16rr;
12792   case X86::ATOMOR32:  return X86::OR32rr;
12793   case X86::ATOMOR64:  return X86::OR64rr;
12794   case X86::ATOMXOR8:  return X86::XOR8rr;
12795   case X86::ATOMXOR16: return X86::XOR16rr;
12796   case X86::ATOMXOR32: return X86::XOR32rr;
12797   case X86::ATOMXOR64: return X86::XOR64rr;
12798   }
12799   llvm_unreachable("Unhandled atomic-load-op opcode!");
12800 }
12801
12802 // Get opcode of the non-atomic one from the specified atomic instruction with
12803 // extra opcode.
12804 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12805                                                unsigned &ExtraOpc) {
12806   switch (Opc) {
12807   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12808   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12809   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12810   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12811   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12812   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12813   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12814   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12815   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12816   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12817   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12818   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12819   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12820   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12821   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12822   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12823   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12824   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12825   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12826   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12827   }
12828   llvm_unreachable("Unhandled atomic-load-op opcode!");
12829 }
12830
12831 // Get opcode of the non-atomic one from the specified atomic instruction for
12832 // 64-bit data type on 32-bit target.
12833 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12834   switch (Opc) {
12835   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12836   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12837   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12838   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12839   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12840   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12841   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12842   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12843   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12844   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12845   }
12846   llvm_unreachable("Unhandled atomic-load-op opcode!");
12847 }
12848
12849 // Get opcode of the non-atomic one from the specified atomic instruction for
12850 // 64-bit data type on 32-bit target with extra opcode.
12851 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12852                                                    unsigned &HiOpc,
12853                                                    unsigned &ExtraOpc) {
12854   switch (Opc) {
12855   case X86::ATOMNAND6432:
12856     ExtraOpc = X86::NOT32r;
12857     HiOpc = X86::AND32rr;
12858     return X86::AND32rr;
12859   }
12860   llvm_unreachable("Unhandled atomic-load-op opcode!");
12861 }
12862
12863 // Get pseudo CMOV opcode from the specified data type.
12864 static unsigned getPseudoCMOVOpc(EVT VT) {
12865   switch (VT.getSimpleVT().SimpleTy) {
12866   case MVT::i8:  return X86::CMOV_GR8;
12867   case MVT::i16: return X86::CMOV_GR16;
12868   case MVT::i32: return X86::CMOV_GR32;
12869   default:
12870     break;
12871   }
12872   llvm_unreachable("Unknown CMOV opcode!");
12873 }
12874
12875 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12876 // They will be translated into a spin-loop or compare-exchange loop from
12877 //
12878 //    ...
12879 //    dst = atomic-fetch-op MI.addr, MI.val
12880 //    ...
12881 //
12882 // to
12883 //
12884 //    ...
12885 //    EAX = LOAD MI.addr
12886 // loop:
12887 //    t1 = OP MI.val, EAX
12888 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12889 //    JNE loop
12890 // sink:
12891 //    dst = EAX
12892 //    ...
12893 MachineBasicBlock *
12894 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12895                                        MachineBasicBlock *MBB) const {
12896   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12897   DebugLoc DL = MI->getDebugLoc();
12898
12899   MachineFunction *MF = MBB->getParent();
12900   MachineRegisterInfo &MRI = MF->getRegInfo();
12901
12902   const BasicBlock *BB = MBB->getBasicBlock();
12903   MachineFunction::iterator I = MBB;
12904   ++I;
12905
12906   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12907          "Unexpected number of operands");
12908
12909   assert(MI->hasOneMemOperand() &&
12910          "Expected atomic-load-op to have one memoperand");
12911
12912   // Memory Reference
12913   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12914   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12915
12916   unsigned DstReg, SrcReg;
12917   unsigned MemOpndSlot;
12918
12919   unsigned CurOp = 0;
12920
12921   DstReg = MI->getOperand(CurOp++).getReg();
12922   MemOpndSlot = CurOp;
12923   CurOp += X86::AddrNumOperands;
12924   SrcReg = MI->getOperand(CurOp++).getReg();
12925
12926   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12927   MVT::SimpleValueType VT = *RC->vt_begin();
12928   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12929
12930   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12931   unsigned LOADOpc = getLoadOpcode(VT);
12932
12933   // For the atomic load-arith operator, we generate
12934   //
12935   //  thisMBB:
12936   //    EAX = LOAD [MI.addr]
12937   //  mainMBB:
12938   //    t1 = OP MI.val, EAX
12939   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12940   //    JNE mainMBB
12941   //  sinkMBB:
12942
12943   MachineBasicBlock *thisMBB = MBB;
12944   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12945   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12946   MF->insert(I, mainMBB);
12947   MF->insert(I, sinkMBB);
12948
12949   MachineInstrBuilder MIB;
12950
12951   // Transfer the remainder of BB and its successor edges to sinkMBB.
12952   sinkMBB->splice(sinkMBB->begin(), MBB,
12953                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12954   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12955
12956   // thisMBB:
12957   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12958   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12959     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12960   MIB.setMemRefs(MMOBegin, MMOEnd);
12961
12962   thisMBB->addSuccessor(mainMBB);
12963
12964   // mainMBB:
12965   MachineBasicBlock *origMainMBB = mainMBB;
12966   mainMBB->addLiveIn(AccPhyReg);
12967
12968   // Copy AccPhyReg as it is used more than once.
12969   unsigned AccReg = MRI.createVirtualRegister(RC);
12970   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12971     .addReg(AccPhyReg);
12972
12973   unsigned t1 = MRI.createVirtualRegister(RC);
12974   unsigned Opc = MI->getOpcode();
12975   switch (Opc) {
12976   default:
12977     llvm_unreachable("Unhandled atomic-load-op opcode!");
12978   case X86::ATOMAND8:
12979   case X86::ATOMAND16:
12980   case X86::ATOMAND32:
12981   case X86::ATOMAND64:
12982   case X86::ATOMOR8:
12983   case X86::ATOMOR16:
12984   case X86::ATOMOR32:
12985   case X86::ATOMOR64:
12986   case X86::ATOMXOR8:
12987   case X86::ATOMXOR16:
12988   case X86::ATOMXOR32:
12989   case X86::ATOMXOR64: {
12990     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12991     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12992       .addReg(AccReg);
12993     break;
12994   }
12995   case X86::ATOMNAND8:
12996   case X86::ATOMNAND16:
12997   case X86::ATOMNAND32:
12998   case X86::ATOMNAND64: {
12999     unsigned t2 = MRI.createVirtualRegister(RC);
13000     unsigned NOTOpc;
13001     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13002     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
13003       .addReg(AccReg);
13004     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
13005     break;
13006   }
13007   case X86::ATOMMAX8:
13008   case X86::ATOMMAX16:
13009   case X86::ATOMMAX32:
13010   case X86::ATOMMAX64:
13011   case X86::ATOMMIN8:
13012   case X86::ATOMMIN16:
13013   case X86::ATOMMIN32:
13014   case X86::ATOMMIN64:
13015   case X86::ATOMUMAX8:
13016   case X86::ATOMUMAX16:
13017   case X86::ATOMUMAX32:
13018   case X86::ATOMUMAX64:
13019   case X86::ATOMUMIN8:
13020   case X86::ATOMUMIN16:
13021   case X86::ATOMUMIN32:
13022   case X86::ATOMUMIN64: {
13023     unsigned CMPOpc;
13024     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13025
13026     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13027       .addReg(SrcReg)
13028       .addReg(AccReg);
13029
13030     if (Subtarget->hasCMov()) {
13031       if (VT != MVT::i8) {
13032         // Native support
13033         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
13034           .addReg(SrcReg)
13035           .addReg(AccReg);
13036       } else {
13037         // Promote i8 to i32 to use CMOV32
13038         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
13039         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13040         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13041         unsigned t2 = MRI.createVirtualRegister(RC32);
13042
13043         unsigned Undef = MRI.createVirtualRegister(RC32);
13044         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13045
13046         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13047           .addReg(Undef)
13048           .addReg(SrcReg)
13049           .addImm(X86::sub_8bit);
13050         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13051           .addReg(Undef)
13052           .addReg(AccReg)
13053           .addImm(X86::sub_8bit);
13054
13055         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13056           .addReg(SrcReg32)
13057           .addReg(AccReg32);
13058
13059         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
13060           .addReg(t2, 0, X86::sub_8bit);
13061       }
13062     } else {
13063       // Use pseudo select and lower them.
13064       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13065              "Invalid atomic-load-op transformation!");
13066       unsigned SelOpc = getPseudoCMOVOpc(VT);
13067       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13068       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13069       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13070               .addReg(SrcReg).addReg(AccReg)
13071               .addImm(CC);
13072       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13073     }
13074     break;
13075   }
13076   }
13077
13078   // Copy AccPhyReg back from virtual register.
13079   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13080     .addReg(AccReg);
13081
13082   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13083   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13084     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13085   MIB.addReg(t1);
13086   MIB.setMemRefs(MMOBegin, MMOEnd);
13087
13088   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13089
13090   mainMBB->addSuccessor(origMainMBB);
13091   mainMBB->addSuccessor(sinkMBB);
13092
13093   // sinkMBB:
13094   sinkMBB->addLiveIn(AccPhyReg);
13095
13096   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13097           TII->get(TargetOpcode::COPY), DstReg)
13098     .addReg(AccPhyReg);
13099
13100   MI->eraseFromParent();
13101   return sinkMBB;
13102 }
13103
13104 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13105 // instructions. They will be translated into a spin-loop or compare-exchange
13106 // loop from
13107 //
13108 //    ...
13109 //    dst = atomic-fetch-op MI.addr, MI.val
13110 //    ...
13111 //
13112 // to
13113 //
13114 //    ...
13115 //    EAX = LOAD [MI.addr + 0]
13116 //    EDX = LOAD [MI.addr + 4]
13117 // loop:
13118 //    EBX = OP MI.val.lo, EAX
13119 //    ECX = OP MI.val.hi, EDX
13120 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13121 //    JNE loop
13122 // sink:
13123 //    dst = EDX:EAX
13124 //    ...
13125 MachineBasicBlock *
13126 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13127                                            MachineBasicBlock *MBB) const {
13128   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13129   DebugLoc DL = MI->getDebugLoc();
13130
13131   MachineFunction *MF = MBB->getParent();
13132   MachineRegisterInfo &MRI = MF->getRegInfo();
13133
13134   const BasicBlock *BB = MBB->getBasicBlock();
13135   MachineFunction::iterator I = MBB;
13136   ++I;
13137
13138   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13139          "Unexpected number of operands");
13140
13141   assert(MI->hasOneMemOperand() &&
13142          "Expected atomic-load-op32 to have one memoperand");
13143
13144   // Memory Reference
13145   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13146   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13147
13148   unsigned DstLoReg, DstHiReg;
13149   unsigned SrcLoReg, SrcHiReg;
13150   unsigned MemOpndSlot;
13151
13152   unsigned CurOp = 0;
13153
13154   DstLoReg = MI->getOperand(CurOp++).getReg();
13155   DstHiReg = MI->getOperand(CurOp++).getReg();
13156   MemOpndSlot = CurOp;
13157   CurOp += X86::AddrNumOperands;
13158   SrcLoReg = MI->getOperand(CurOp++).getReg();
13159   SrcHiReg = MI->getOperand(CurOp++).getReg();
13160
13161   const TargetRegisterClass *RC = &X86::GR32RegClass;
13162   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13163
13164   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13165   unsigned LOADOpc = X86::MOV32rm;
13166
13167   // For the atomic load-arith operator, we generate
13168   //
13169   //  thisMBB:
13170   //    EAX = LOAD [MI.addr + 0]
13171   //    EDX = LOAD [MI.addr + 4]
13172   //  mainMBB:
13173   //    EBX = OP MI.vallo, EAX
13174   //    ECX = OP MI.valhi, EDX
13175   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13176   //    JNE mainMBB
13177   //  sinkMBB:
13178
13179   MachineBasicBlock *thisMBB = MBB;
13180   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13181   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13182   MF->insert(I, mainMBB);
13183   MF->insert(I, sinkMBB);
13184
13185   MachineInstrBuilder MIB;
13186
13187   // Transfer the remainder of BB and its successor edges to sinkMBB.
13188   sinkMBB->splice(sinkMBB->begin(), MBB,
13189                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13190   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13191
13192   // thisMBB:
13193   // Lo
13194   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13195   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13196     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13197   MIB.setMemRefs(MMOBegin, MMOEnd);
13198   // Hi
13199   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13200   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13201     if (i == X86::AddrDisp)
13202       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13203     else
13204       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13205   }
13206   MIB.setMemRefs(MMOBegin, MMOEnd);
13207
13208   thisMBB->addSuccessor(mainMBB);
13209
13210   // mainMBB:
13211   MachineBasicBlock *origMainMBB = mainMBB;
13212   mainMBB->addLiveIn(X86::EAX);
13213   mainMBB->addLiveIn(X86::EDX);
13214
13215   // Copy EDX:EAX as they are used more than once.
13216   unsigned LoReg = MRI.createVirtualRegister(RC);
13217   unsigned HiReg = MRI.createVirtualRegister(RC);
13218   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13219   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13220
13221   unsigned t1L = MRI.createVirtualRegister(RC);
13222   unsigned t1H = MRI.createVirtualRegister(RC);
13223
13224   unsigned Opc = MI->getOpcode();
13225   switch (Opc) {
13226   default:
13227     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13228   case X86::ATOMAND6432:
13229   case X86::ATOMOR6432:
13230   case X86::ATOMXOR6432:
13231   case X86::ATOMADD6432:
13232   case X86::ATOMSUB6432: {
13233     unsigned HiOpc;
13234     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13235     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13236     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13237     break;
13238   }
13239   case X86::ATOMNAND6432: {
13240     unsigned HiOpc, NOTOpc;
13241     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13242     unsigned t2L = MRI.createVirtualRegister(RC);
13243     unsigned t2H = MRI.createVirtualRegister(RC);
13244     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13245     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13246     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13247     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13248     break;
13249   }
13250   case X86::ATOMMAX6432:
13251   case X86::ATOMMIN6432:
13252   case X86::ATOMUMAX6432:
13253   case X86::ATOMUMIN6432: {
13254     unsigned HiOpc;
13255     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13256     unsigned cL = MRI.createVirtualRegister(RC8);
13257     unsigned cH = MRI.createVirtualRegister(RC8);
13258     unsigned cL32 = MRI.createVirtualRegister(RC);
13259     unsigned cH32 = MRI.createVirtualRegister(RC);
13260     unsigned cc = MRI.createVirtualRegister(RC);
13261     // cl := cmp src_lo, lo
13262     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13263       .addReg(SrcLoReg).addReg(LoReg);
13264     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13265     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13266     // ch := cmp src_hi, hi
13267     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13268       .addReg(SrcHiReg).addReg(HiReg);
13269     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13270     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13271     // cc := if (src_hi == hi) ? cl : ch;
13272     if (Subtarget->hasCMov()) {
13273       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13274         .addReg(cH32).addReg(cL32);
13275     } else {
13276       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13277               .addReg(cH32).addReg(cL32)
13278               .addImm(X86::COND_E);
13279       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13280     }
13281     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13282     if (Subtarget->hasCMov()) {
13283       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13284         .addReg(SrcLoReg).addReg(LoReg);
13285       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13286         .addReg(SrcHiReg).addReg(HiReg);
13287     } else {
13288       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13289               .addReg(SrcLoReg).addReg(LoReg)
13290               .addImm(X86::COND_NE);
13291       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13292       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13293               .addReg(SrcHiReg).addReg(HiReg)
13294               .addImm(X86::COND_NE);
13295       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13296     }
13297     break;
13298   }
13299   case X86::ATOMSWAP6432: {
13300     unsigned HiOpc;
13301     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13302     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13303     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13304     break;
13305   }
13306   }
13307
13308   // Copy EDX:EAX back from HiReg:LoReg
13309   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13310   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13311   // Copy ECX:EBX from t1H:t1L
13312   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13313   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13314
13315   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13316   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13317     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13318   MIB.setMemRefs(MMOBegin, MMOEnd);
13319
13320   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13321
13322   mainMBB->addSuccessor(origMainMBB);
13323   mainMBB->addSuccessor(sinkMBB);
13324
13325   // sinkMBB:
13326   sinkMBB->addLiveIn(X86::EAX);
13327   sinkMBB->addLiveIn(X86::EDX);
13328
13329   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13330           TII->get(TargetOpcode::COPY), DstLoReg)
13331     .addReg(X86::EAX);
13332   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13333           TII->get(TargetOpcode::COPY), DstHiReg)
13334     .addReg(X86::EDX);
13335
13336   MI->eraseFromParent();
13337   return sinkMBB;
13338 }
13339
13340 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13341 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13342 // in the .td file.
13343 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13344                                        const TargetInstrInfo *TII) {
13345   unsigned Opc;
13346   switch (MI->getOpcode()) {
13347   default: llvm_unreachable("illegal opcode!");
13348   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13349   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13350   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13351   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13352   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13353   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13354   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13355   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13356   }
13357
13358   DebugLoc dl = MI->getDebugLoc();
13359   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13360
13361   unsigned NumArgs = MI->getNumOperands();
13362   for (unsigned i = 1; i < NumArgs; ++i) {
13363     MachineOperand &Op = MI->getOperand(i);
13364     if (!(Op.isReg() && Op.isImplicit()))
13365       MIB.addOperand(Op);
13366   }
13367   if (MI->hasOneMemOperand())
13368     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13369
13370   BuildMI(*BB, MI, dl,
13371     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13372     .addReg(X86::XMM0);
13373
13374   MI->eraseFromParent();
13375   return BB;
13376 }
13377
13378 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13379 // defs in an instruction pattern
13380 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13381                                        const TargetInstrInfo *TII) {
13382   unsigned Opc;
13383   switch (MI->getOpcode()) {
13384   default: llvm_unreachable("illegal opcode!");
13385   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13386   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13387   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13388   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13389   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13390   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13391   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13392   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13393   }
13394
13395   DebugLoc dl = MI->getDebugLoc();
13396   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13397
13398   unsigned NumArgs = MI->getNumOperands(); // remove the results
13399   for (unsigned i = 1; i < NumArgs; ++i) {
13400     MachineOperand &Op = MI->getOperand(i);
13401     if (!(Op.isReg() && Op.isImplicit()))
13402       MIB.addOperand(Op);
13403   }
13404   if (MI->hasOneMemOperand())
13405     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13406
13407   BuildMI(*BB, MI, dl,
13408     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13409     .addReg(X86::ECX);
13410
13411   MI->eraseFromParent();
13412   return BB;
13413 }
13414
13415 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13416                                        const TargetInstrInfo *TII,
13417                                        const X86Subtarget* Subtarget) {
13418   DebugLoc dl = MI->getDebugLoc();
13419
13420   // Address into RAX/EAX, other two args into ECX, EDX.
13421   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13422   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13423   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13424   for (int i = 0; i < X86::AddrNumOperands; ++i)
13425     MIB.addOperand(MI->getOperand(i));
13426
13427   unsigned ValOps = X86::AddrNumOperands;
13428   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13429     .addReg(MI->getOperand(ValOps).getReg());
13430   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13431     .addReg(MI->getOperand(ValOps+1).getReg());
13432
13433   // The instruction doesn't actually take any operands though.
13434   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13435
13436   MI->eraseFromParent(); // The pseudo is gone now.
13437   return BB;
13438 }
13439
13440 MachineBasicBlock *
13441 X86TargetLowering::EmitVAARG64WithCustomInserter(
13442                    MachineInstr *MI,
13443                    MachineBasicBlock *MBB) const {
13444   // Emit va_arg instruction on X86-64.
13445
13446   // Operands to this pseudo-instruction:
13447   // 0  ) Output        : destination address (reg)
13448   // 1-5) Input         : va_list address (addr, i64mem)
13449   // 6  ) ArgSize       : Size (in bytes) of vararg type
13450   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13451   // 8  ) Align         : Alignment of type
13452   // 9  ) EFLAGS (implicit-def)
13453
13454   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13455   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13456
13457   unsigned DestReg = MI->getOperand(0).getReg();
13458   MachineOperand &Base = MI->getOperand(1);
13459   MachineOperand &Scale = MI->getOperand(2);
13460   MachineOperand &Index = MI->getOperand(3);
13461   MachineOperand &Disp = MI->getOperand(4);
13462   MachineOperand &Segment = MI->getOperand(5);
13463   unsigned ArgSize = MI->getOperand(6).getImm();
13464   unsigned ArgMode = MI->getOperand(7).getImm();
13465   unsigned Align = MI->getOperand(8).getImm();
13466
13467   // Memory Reference
13468   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13469   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13470   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13471
13472   // Machine Information
13473   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13474   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13475   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13476   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13477   DebugLoc DL = MI->getDebugLoc();
13478
13479   // struct va_list {
13480   //   i32   gp_offset
13481   //   i32   fp_offset
13482   //   i64   overflow_area (address)
13483   //   i64   reg_save_area (address)
13484   // }
13485   // sizeof(va_list) = 24
13486   // alignment(va_list) = 8
13487
13488   unsigned TotalNumIntRegs = 6;
13489   unsigned TotalNumXMMRegs = 8;
13490   bool UseGPOffset = (ArgMode == 1);
13491   bool UseFPOffset = (ArgMode == 2);
13492   unsigned MaxOffset = TotalNumIntRegs * 8 +
13493                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13494
13495   /* Align ArgSize to a multiple of 8 */
13496   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13497   bool NeedsAlign = (Align > 8);
13498
13499   MachineBasicBlock *thisMBB = MBB;
13500   MachineBasicBlock *overflowMBB;
13501   MachineBasicBlock *offsetMBB;
13502   MachineBasicBlock *endMBB;
13503
13504   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13505   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13506   unsigned OffsetReg = 0;
13507
13508   if (!UseGPOffset && !UseFPOffset) {
13509     // If we only pull from the overflow region, we don't create a branch.
13510     // We don't need to alter control flow.
13511     OffsetDestReg = 0; // unused
13512     OverflowDestReg = DestReg;
13513
13514     offsetMBB = NULL;
13515     overflowMBB = thisMBB;
13516     endMBB = thisMBB;
13517   } else {
13518     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13519     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13520     // If not, pull from overflow_area. (branch to overflowMBB)
13521     //
13522     //       thisMBB
13523     //         |     .
13524     //         |        .
13525     //     offsetMBB   overflowMBB
13526     //         |        .
13527     //         |     .
13528     //        endMBB
13529
13530     // Registers for the PHI in endMBB
13531     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13532     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13533
13534     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13535     MachineFunction *MF = MBB->getParent();
13536     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13537     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13538     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13539
13540     MachineFunction::iterator MBBIter = MBB;
13541     ++MBBIter;
13542
13543     // Insert the new basic blocks
13544     MF->insert(MBBIter, offsetMBB);
13545     MF->insert(MBBIter, overflowMBB);
13546     MF->insert(MBBIter, endMBB);
13547
13548     // Transfer the remainder of MBB and its successor edges to endMBB.
13549     endMBB->splice(endMBB->begin(), thisMBB,
13550                     llvm::next(MachineBasicBlock::iterator(MI)),
13551                     thisMBB->end());
13552     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13553
13554     // Make offsetMBB and overflowMBB successors of thisMBB
13555     thisMBB->addSuccessor(offsetMBB);
13556     thisMBB->addSuccessor(overflowMBB);
13557
13558     // endMBB is a successor of both offsetMBB and overflowMBB
13559     offsetMBB->addSuccessor(endMBB);
13560     overflowMBB->addSuccessor(endMBB);
13561
13562     // Load the offset value into a register
13563     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13564     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13565       .addOperand(Base)
13566       .addOperand(Scale)
13567       .addOperand(Index)
13568       .addDisp(Disp, UseFPOffset ? 4 : 0)
13569       .addOperand(Segment)
13570       .setMemRefs(MMOBegin, MMOEnd);
13571
13572     // Check if there is enough room left to pull this argument.
13573     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13574       .addReg(OffsetReg)
13575       .addImm(MaxOffset + 8 - ArgSizeA8);
13576
13577     // Branch to "overflowMBB" if offset >= max
13578     // Fall through to "offsetMBB" otherwise
13579     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13580       .addMBB(overflowMBB);
13581   }
13582
13583   // In offsetMBB, emit code to use the reg_save_area.
13584   if (offsetMBB) {
13585     assert(OffsetReg != 0);
13586
13587     // Read the reg_save_area address.
13588     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13589     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13590       .addOperand(Base)
13591       .addOperand(Scale)
13592       .addOperand(Index)
13593       .addDisp(Disp, 16)
13594       .addOperand(Segment)
13595       .setMemRefs(MMOBegin, MMOEnd);
13596
13597     // Zero-extend the offset
13598     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13599       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13600         .addImm(0)
13601         .addReg(OffsetReg)
13602         .addImm(X86::sub_32bit);
13603
13604     // Add the offset to the reg_save_area to get the final address.
13605     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13606       .addReg(OffsetReg64)
13607       .addReg(RegSaveReg);
13608
13609     // Compute the offset for the next argument
13610     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13611     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13612       .addReg(OffsetReg)
13613       .addImm(UseFPOffset ? 16 : 8);
13614
13615     // Store it back into the va_list.
13616     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13617       .addOperand(Base)
13618       .addOperand(Scale)
13619       .addOperand(Index)
13620       .addDisp(Disp, UseFPOffset ? 4 : 0)
13621       .addOperand(Segment)
13622       .addReg(NextOffsetReg)
13623       .setMemRefs(MMOBegin, MMOEnd);
13624
13625     // Jump to endMBB
13626     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13627       .addMBB(endMBB);
13628   }
13629
13630   //
13631   // Emit code to use overflow area
13632   //
13633
13634   // Load the overflow_area address into a register.
13635   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13636   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13637     .addOperand(Base)
13638     .addOperand(Scale)
13639     .addOperand(Index)
13640     .addDisp(Disp, 8)
13641     .addOperand(Segment)
13642     .setMemRefs(MMOBegin, MMOEnd);
13643
13644   // If we need to align it, do so. Otherwise, just copy the address
13645   // to OverflowDestReg.
13646   if (NeedsAlign) {
13647     // Align the overflow address
13648     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13649     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13650
13651     // aligned_addr = (addr + (align-1)) & ~(align-1)
13652     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13653       .addReg(OverflowAddrReg)
13654       .addImm(Align-1);
13655
13656     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13657       .addReg(TmpReg)
13658       .addImm(~(uint64_t)(Align-1));
13659   } else {
13660     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13661       .addReg(OverflowAddrReg);
13662   }
13663
13664   // Compute the next overflow address after this argument.
13665   // (the overflow address should be kept 8-byte aligned)
13666   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13667   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13668     .addReg(OverflowDestReg)
13669     .addImm(ArgSizeA8);
13670
13671   // Store the new overflow address.
13672   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13673     .addOperand(Base)
13674     .addOperand(Scale)
13675     .addOperand(Index)
13676     .addDisp(Disp, 8)
13677     .addOperand(Segment)
13678     .addReg(NextAddrReg)
13679     .setMemRefs(MMOBegin, MMOEnd);
13680
13681   // If we branched, emit the PHI to the front of endMBB.
13682   if (offsetMBB) {
13683     BuildMI(*endMBB, endMBB->begin(), DL,
13684             TII->get(X86::PHI), DestReg)
13685       .addReg(OffsetDestReg).addMBB(offsetMBB)
13686       .addReg(OverflowDestReg).addMBB(overflowMBB);
13687   }
13688
13689   // Erase the pseudo instruction
13690   MI->eraseFromParent();
13691
13692   return endMBB;
13693 }
13694
13695 MachineBasicBlock *
13696 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13697                                                  MachineInstr *MI,
13698                                                  MachineBasicBlock *MBB) const {
13699   // Emit code to save XMM registers to the stack. The ABI says that the
13700   // number of registers to save is given in %al, so it's theoretically
13701   // possible to do an indirect jump trick to avoid saving all of them,
13702   // however this code takes a simpler approach and just executes all
13703   // of the stores if %al is non-zero. It's less code, and it's probably
13704   // easier on the hardware branch predictor, and stores aren't all that
13705   // expensive anyway.
13706
13707   // Create the new basic blocks. One block contains all the XMM stores,
13708   // and one block is the final destination regardless of whether any
13709   // stores were performed.
13710   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13711   MachineFunction *F = MBB->getParent();
13712   MachineFunction::iterator MBBIter = MBB;
13713   ++MBBIter;
13714   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13715   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13716   F->insert(MBBIter, XMMSaveMBB);
13717   F->insert(MBBIter, EndMBB);
13718
13719   // Transfer the remainder of MBB and its successor edges to EndMBB.
13720   EndMBB->splice(EndMBB->begin(), MBB,
13721                  llvm::next(MachineBasicBlock::iterator(MI)),
13722                  MBB->end());
13723   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13724
13725   // The original block will now fall through to the XMM save block.
13726   MBB->addSuccessor(XMMSaveMBB);
13727   // The XMMSaveMBB will fall through to the end block.
13728   XMMSaveMBB->addSuccessor(EndMBB);
13729
13730   // Now add the instructions.
13731   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13732   DebugLoc DL = MI->getDebugLoc();
13733
13734   unsigned CountReg = MI->getOperand(0).getReg();
13735   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13736   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13737
13738   if (!Subtarget->isTargetWin64()) {
13739     // If %al is 0, branch around the XMM save block.
13740     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13741     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13742     MBB->addSuccessor(EndMBB);
13743   }
13744
13745   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13746   // In the XMM save block, save all the XMM argument registers.
13747   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13748     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13749     MachineMemOperand *MMO =
13750       F->getMachineMemOperand(
13751           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13752         MachineMemOperand::MOStore,
13753         /*Size=*/16, /*Align=*/16);
13754     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13755       .addFrameIndex(RegSaveFrameIndex)
13756       .addImm(/*Scale=*/1)
13757       .addReg(/*IndexReg=*/0)
13758       .addImm(/*Disp=*/Offset)
13759       .addReg(/*Segment=*/0)
13760       .addReg(MI->getOperand(i).getReg())
13761       .addMemOperand(MMO);
13762   }
13763
13764   MI->eraseFromParent();   // The pseudo instruction is gone now.
13765
13766   return EndMBB;
13767 }
13768
13769 // The EFLAGS operand of SelectItr might be missing a kill marker
13770 // because there were multiple uses of EFLAGS, and ISel didn't know
13771 // which to mark. Figure out whether SelectItr should have had a
13772 // kill marker, and set it if it should. Returns the correct kill
13773 // marker value.
13774 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13775                                      MachineBasicBlock* BB,
13776                                      const TargetRegisterInfo* TRI) {
13777   // Scan forward through BB for a use/def of EFLAGS.
13778   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13779   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13780     const MachineInstr& mi = *miI;
13781     if (mi.readsRegister(X86::EFLAGS))
13782       return false;
13783     if (mi.definesRegister(X86::EFLAGS))
13784       break; // Should have kill-flag - update below.
13785   }
13786
13787   // If we hit the end of the block, check whether EFLAGS is live into a
13788   // successor.
13789   if (miI == BB->end()) {
13790     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13791                                           sEnd = BB->succ_end();
13792          sItr != sEnd; ++sItr) {
13793       MachineBasicBlock* succ = *sItr;
13794       if (succ->isLiveIn(X86::EFLAGS))
13795         return false;
13796     }
13797   }
13798
13799   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13800   // out. SelectMI should have a kill flag on EFLAGS.
13801   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13802   return true;
13803 }
13804
13805 MachineBasicBlock *
13806 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13807                                      MachineBasicBlock *BB) const {
13808   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13809   DebugLoc DL = MI->getDebugLoc();
13810
13811   // To "insert" a SELECT_CC instruction, we actually have to insert the
13812   // diamond control-flow pattern.  The incoming instruction knows the
13813   // destination vreg to set, the condition code register to branch on, the
13814   // true/false values to select between, and a branch opcode to use.
13815   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13816   MachineFunction::iterator It = BB;
13817   ++It;
13818
13819   //  thisMBB:
13820   //  ...
13821   //   TrueVal = ...
13822   //   cmpTY ccX, r1, r2
13823   //   bCC copy1MBB
13824   //   fallthrough --> copy0MBB
13825   MachineBasicBlock *thisMBB = BB;
13826   MachineFunction *F = BB->getParent();
13827   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13828   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13829   F->insert(It, copy0MBB);
13830   F->insert(It, sinkMBB);
13831
13832   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13833   // live into the sink and copy blocks.
13834   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13835   if (!MI->killsRegister(X86::EFLAGS) &&
13836       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13837     copy0MBB->addLiveIn(X86::EFLAGS);
13838     sinkMBB->addLiveIn(X86::EFLAGS);
13839   }
13840
13841   // Transfer the remainder of BB and its successor edges to sinkMBB.
13842   sinkMBB->splice(sinkMBB->begin(), BB,
13843                   llvm::next(MachineBasicBlock::iterator(MI)),
13844                   BB->end());
13845   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13846
13847   // Add the true and fallthrough blocks as its successors.
13848   BB->addSuccessor(copy0MBB);
13849   BB->addSuccessor(sinkMBB);
13850
13851   // Create the conditional branch instruction.
13852   unsigned Opc =
13853     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13854   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13855
13856   //  copy0MBB:
13857   //   %FalseValue = ...
13858   //   # fallthrough to sinkMBB
13859   copy0MBB->addSuccessor(sinkMBB);
13860
13861   //  sinkMBB:
13862   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13863   //  ...
13864   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13865           TII->get(X86::PHI), MI->getOperand(0).getReg())
13866     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13867     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13868
13869   MI->eraseFromParent();   // The pseudo instruction is gone now.
13870   return sinkMBB;
13871 }
13872
13873 MachineBasicBlock *
13874 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13875                                         bool Is64Bit) const {
13876   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13877   DebugLoc DL = MI->getDebugLoc();
13878   MachineFunction *MF = BB->getParent();
13879   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13880
13881   assert(getTargetMachine().Options.EnableSegmentedStacks);
13882
13883   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13884   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13885
13886   // BB:
13887   //  ... [Till the alloca]
13888   // If stacklet is not large enough, jump to mallocMBB
13889   //
13890   // bumpMBB:
13891   //  Allocate by subtracting from RSP
13892   //  Jump to continueMBB
13893   //
13894   // mallocMBB:
13895   //  Allocate by call to runtime
13896   //
13897   // continueMBB:
13898   //  ...
13899   //  [rest of original BB]
13900   //
13901
13902   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13903   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13904   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13905
13906   MachineRegisterInfo &MRI = MF->getRegInfo();
13907   const TargetRegisterClass *AddrRegClass =
13908     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13909
13910   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13911     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13912     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13913     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13914     sizeVReg = MI->getOperand(1).getReg(),
13915     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13916
13917   MachineFunction::iterator MBBIter = BB;
13918   ++MBBIter;
13919
13920   MF->insert(MBBIter, bumpMBB);
13921   MF->insert(MBBIter, mallocMBB);
13922   MF->insert(MBBIter, continueMBB);
13923
13924   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13925                       (MachineBasicBlock::iterator(MI)), BB->end());
13926   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13927
13928   // Add code to the main basic block to check if the stack limit has been hit,
13929   // and if so, jump to mallocMBB otherwise to bumpMBB.
13930   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13931   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13932     .addReg(tmpSPVReg).addReg(sizeVReg);
13933   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13934     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13935     .addReg(SPLimitVReg);
13936   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13937
13938   // bumpMBB simply decreases the stack pointer, since we know the current
13939   // stacklet has enough space.
13940   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13941     .addReg(SPLimitVReg);
13942   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13943     .addReg(SPLimitVReg);
13944   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13945
13946   // Calls into a routine in libgcc to allocate more space from the heap.
13947   const uint32_t *RegMask =
13948     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13949   if (Is64Bit) {
13950     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13951       .addReg(sizeVReg);
13952     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13953       .addExternalSymbol("__morestack_allocate_stack_space")
13954       .addRegMask(RegMask)
13955       .addReg(X86::RDI, RegState::Implicit)
13956       .addReg(X86::RAX, RegState::ImplicitDefine);
13957   } else {
13958     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13959       .addImm(12);
13960     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13961     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13962       .addExternalSymbol("__morestack_allocate_stack_space")
13963       .addRegMask(RegMask)
13964       .addReg(X86::EAX, RegState::ImplicitDefine);
13965   }
13966
13967   if (!Is64Bit)
13968     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13969       .addImm(16);
13970
13971   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13972     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13973   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13974
13975   // Set up the CFG correctly.
13976   BB->addSuccessor(bumpMBB);
13977   BB->addSuccessor(mallocMBB);
13978   mallocMBB->addSuccessor(continueMBB);
13979   bumpMBB->addSuccessor(continueMBB);
13980
13981   // Take care of the PHI nodes.
13982   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13983           MI->getOperand(0).getReg())
13984     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13985     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13986
13987   // Delete the original pseudo instruction.
13988   MI->eraseFromParent();
13989
13990   // And we're done.
13991   return continueMBB;
13992 }
13993
13994 MachineBasicBlock *
13995 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13996                                           MachineBasicBlock *BB) const {
13997   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13998   DebugLoc DL = MI->getDebugLoc();
13999
14000   assert(!Subtarget->isTargetEnvMacho());
14001
14002   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14003   // non-trivial part is impdef of ESP.
14004
14005   if (Subtarget->isTargetWin64()) {
14006     if (Subtarget->isTargetCygMing()) {
14007       // ___chkstk(Mingw64):
14008       // Clobbers R10, R11, RAX and EFLAGS.
14009       // Updates RSP.
14010       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14011         .addExternalSymbol("___chkstk")
14012         .addReg(X86::RAX, RegState::Implicit)
14013         .addReg(X86::RSP, RegState::Implicit)
14014         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14015         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14016         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14017     } else {
14018       // __chkstk(MSVCRT): does not update stack pointer.
14019       // Clobbers R10, R11 and EFLAGS.
14020       // FIXME: RAX(allocated size) might be reused and not killed.
14021       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14022         .addExternalSymbol("__chkstk")
14023         .addReg(X86::RAX, RegState::Implicit)
14024         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14025       // RAX has the offset to subtracted from RSP.
14026       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14027         .addReg(X86::RSP)
14028         .addReg(X86::RAX);
14029     }
14030   } else {
14031     const char *StackProbeSymbol =
14032       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14033
14034     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14035       .addExternalSymbol(StackProbeSymbol)
14036       .addReg(X86::EAX, RegState::Implicit)
14037       .addReg(X86::ESP, RegState::Implicit)
14038       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14039       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14040       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14041   }
14042
14043   MI->eraseFromParent();   // The pseudo instruction is gone now.
14044   return BB;
14045 }
14046
14047 MachineBasicBlock *
14048 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14049                                       MachineBasicBlock *BB) const {
14050   // This is pretty easy.  We're taking the value that we received from
14051   // our load from the relocation, sticking it in either RDI (x86-64)
14052   // or EAX and doing an indirect call.  The return value will then
14053   // be in the normal return register.
14054   const X86InstrInfo *TII
14055     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14056   DebugLoc DL = MI->getDebugLoc();
14057   MachineFunction *F = BB->getParent();
14058
14059   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14060   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14061
14062   // Get a register mask for the lowered call.
14063   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14064   // proper register mask.
14065   const uint32_t *RegMask =
14066     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14067   if (Subtarget->is64Bit()) {
14068     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14069                                       TII->get(X86::MOV64rm), X86::RDI)
14070     .addReg(X86::RIP)
14071     .addImm(0).addReg(0)
14072     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14073                       MI->getOperand(3).getTargetFlags())
14074     .addReg(0);
14075     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14076     addDirectMem(MIB, X86::RDI);
14077     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14078   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14079     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14080                                       TII->get(X86::MOV32rm), X86::EAX)
14081     .addReg(0)
14082     .addImm(0).addReg(0)
14083     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14084                       MI->getOperand(3).getTargetFlags())
14085     .addReg(0);
14086     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14087     addDirectMem(MIB, X86::EAX);
14088     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14089   } else {
14090     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14091                                       TII->get(X86::MOV32rm), X86::EAX)
14092     .addReg(TII->getGlobalBaseReg(F))
14093     .addImm(0).addReg(0)
14094     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14095                       MI->getOperand(3).getTargetFlags())
14096     .addReg(0);
14097     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14098     addDirectMem(MIB, X86::EAX);
14099     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14100   }
14101
14102   MI->eraseFromParent(); // The pseudo instruction is gone now.
14103   return BB;
14104 }
14105
14106 MachineBasicBlock *
14107 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14108                                     MachineBasicBlock *MBB) const {
14109   DebugLoc DL = MI->getDebugLoc();
14110   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14111
14112   MachineFunction *MF = MBB->getParent();
14113   MachineRegisterInfo &MRI = MF->getRegInfo();
14114
14115   const BasicBlock *BB = MBB->getBasicBlock();
14116   MachineFunction::iterator I = MBB;
14117   ++I;
14118
14119   // Memory Reference
14120   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14121   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14122
14123   unsigned DstReg;
14124   unsigned MemOpndSlot = 0;
14125
14126   unsigned CurOp = 0;
14127
14128   DstReg = MI->getOperand(CurOp++).getReg();
14129   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14130   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14131   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14132   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14133
14134   MemOpndSlot = CurOp;
14135
14136   MVT PVT = getPointerTy();
14137   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14138          "Invalid Pointer Size!");
14139
14140   // For v = setjmp(buf), we generate
14141   //
14142   // thisMBB:
14143   //  buf[LabelOffset] = restoreMBB
14144   //  SjLjSetup restoreMBB
14145   //
14146   // mainMBB:
14147   //  v_main = 0
14148   //
14149   // sinkMBB:
14150   //  v = phi(main, restore)
14151   //
14152   // restoreMBB:
14153   //  v_restore = 1
14154
14155   MachineBasicBlock *thisMBB = MBB;
14156   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14157   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14158   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14159   MF->insert(I, mainMBB);
14160   MF->insert(I, sinkMBB);
14161   MF->push_back(restoreMBB);
14162
14163   MachineInstrBuilder MIB;
14164
14165   // Transfer the remainder of BB and its successor edges to sinkMBB.
14166   sinkMBB->splice(sinkMBB->begin(), MBB,
14167                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14168   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14169
14170   // thisMBB:
14171   unsigned PtrStoreOpc = 0;
14172   unsigned LabelReg = 0;
14173   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14174   Reloc::Model RM = getTargetMachine().getRelocationModel();
14175   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14176                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14177
14178   // Prepare IP either in reg or imm.
14179   if (!UseImmLabel) {
14180     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14181     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14182     LabelReg = MRI.createVirtualRegister(PtrRC);
14183     if (Subtarget->is64Bit()) {
14184       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14185               .addReg(X86::RIP)
14186               .addImm(0)
14187               .addReg(0)
14188               .addMBB(restoreMBB)
14189               .addReg(0);
14190     } else {
14191       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14192       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14193               .addReg(XII->getGlobalBaseReg(MF))
14194               .addImm(0)
14195               .addReg(0)
14196               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14197               .addReg(0);
14198     }
14199   } else
14200     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14201   // Store IP
14202   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14203   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14204     if (i == X86::AddrDisp)
14205       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14206     else
14207       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14208   }
14209   if (!UseImmLabel)
14210     MIB.addReg(LabelReg);
14211   else
14212     MIB.addMBB(restoreMBB);
14213   MIB.setMemRefs(MMOBegin, MMOEnd);
14214   // Setup
14215   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14216           .addMBB(restoreMBB);
14217   MIB.addRegMask(RegInfo->getNoPreservedMask());
14218   thisMBB->addSuccessor(mainMBB);
14219   thisMBB->addSuccessor(restoreMBB);
14220
14221   // mainMBB:
14222   //  EAX = 0
14223   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14224   mainMBB->addSuccessor(sinkMBB);
14225
14226   // sinkMBB:
14227   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14228           TII->get(X86::PHI), DstReg)
14229     .addReg(mainDstReg).addMBB(mainMBB)
14230     .addReg(restoreDstReg).addMBB(restoreMBB);
14231
14232   // restoreMBB:
14233   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14234   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14235   restoreMBB->addSuccessor(sinkMBB);
14236
14237   MI->eraseFromParent();
14238   return sinkMBB;
14239 }
14240
14241 MachineBasicBlock *
14242 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14243                                      MachineBasicBlock *MBB) const {
14244   DebugLoc DL = MI->getDebugLoc();
14245   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14246
14247   MachineFunction *MF = MBB->getParent();
14248   MachineRegisterInfo &MRI = MF->getRegInfo();
14249
14250   // Memory Reference
14251   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14252   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14253
14254   MVT PVT = getPointerTy();
14255   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14256          "Invalid Pointer Size!");
14257
14258   const TargetRegisterClass *RC =
14259     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14260   unsigned Tmp = MRI.createVirtualRegister(RC);
14261   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14262   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14263   unsigned SP = RegInfo->getStackRegister();
14264
14265   MachineInstrBuilder MIB;
14266
14267   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14268   const int64_t SPOffset = 2 * PVT.getStoreSize();
14269
14270   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14271   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14272
14273   // Reload FP
14274   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14275   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14276     MIB.addOperand(MI->getOperand(i));
14277   MIB.setMemRefs(MMOBegin, MMOEnd);
14278   // Reload IP
14279   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14280   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14281     if (i == X86::AddrDisp)
14282       MIB.addDisp(MI->getOperand(i), LabelOffset);
14283     else
14284       MIB.addOperand(MI->getOperand(i));
14285   }
14286   MIB.setMemRefs(MMOBegin, MMOEnd);
14287   // Reload SP
14288   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14289   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14290     if (i == X86::AddrDisp)
14291       MIB.addDisp(MI->getOperand(i), SPOffset);
14292     else
14293       MIB.addOperand(MI->getOperand(i));
14294   }
14295   MIB.setMemRefs(MMOBegin, MMOEnd);
14296   // Jump
14297   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14298
14299   MI->eraseFromParent();
14300   return MBB;
14301 }
14302
14303 MachineBasicBlock *
14304 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14305                                                MachineBasicBlock *BB) const {
14306   switch (MI->getOpcode()) {
14307   default: llvm_unreachable("Unexpected instr type to insert");
14308   case X86::TAILJMPd64:
14309   case X86::TAILJMPr64:
14310   case X86::TAILJMPm64:
14311     llvm_unreachable("TAILJMP64 would not be touched here.");
14312   case X86::TCRETURNdi64:
14313   case X86::TCRETURNri64:
14314   case X86::TCRETURNmi64:
14315     return BB;
14316   case X86::WIN_ALLOCA:
14317     return EmitLoweredWinAlloca(MI, BB);
14318   case X86::SEG_ALLOCA_32:
14319     return EmitLoweredSegAlloca(MI, BB, false);
14320   case X86::SEG_ALLOCA_64:
14321     return EmitLoweredSegAlloca(MI, BB, true);
14322   case X86::TLSCall_32:
14323   case X86::TLSCall_64:
14324     return EmitLoweredTLSCall(MI, BB);
14325   case X86::CMOV_GR8:
14326   case X86::CMOV_FR32:
14327   case X86::CMOV_FR64:
14328   case X86::CMOV_V4F32:
14329   case X86::CMOV_V2F64:
14330   case X86::CMOV_V2I64:
14331   case X86::CMOV_V8F32:
14332   case X86::CMOV_V4F64:
14333   case X86::CMOV_V4I64:
14334   case X86::CMOV_GR16:
14335   case X86::CMOV_GR32:
14336   case X86::CMOV_RFP32:
14337   case X86::CMOV_RFP64:
14338   case X86::CMOV_RFP80:
14339     return EmitLoweredSelect(MI, BB);
14340
14341   case X86::FP32_TO_INT16_IN_MEM:
14342   case X86::FP32_TO_INT32_IN_MEM:
14343   case X86::FP32_TO_INT64_IN_MEM:
14344   case X86::FP64_TO_INT16_IN_MEM:
14345   case X86::FP64_TO_INT32_IN_MEM:
14346   case X86::FP64_TO_INT64_IN_MEM:
14347   case X86::FP80_TO_INT16_IN_MEM:
14348   case X86::FP80_TO_INT32_IN_MEM:
14349   case X86::FP80_TO_INT64_IN_MEM: {
14350     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14351     DebugLoc DL = MI->getDebugLoc();
14352
14353     // Change the floating point control register to use "round towards zero"
14354     // mode when truncating to an integer value.
14355     MachineFunction *F = BB->getParent();
14356     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14357     addFrameReference(BuildMI(*BB, MI, DL,
14358                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14359
14360     // Load the old value of the high byte of the control word...
14361     unsigned OldCW =
14362       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14363     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14364                       CWFrameIdx);
14365
14366     // Set the high part to be round to zero...
14367     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14368       .addImm(0xC7F);
14369
14370     // Reload the modified control word now...
14371     addFrameReference(BuildMI(*BB, MI, DL,
14372                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14373
14374     // Restore the memory image of control word to original value
14375     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14376       .addReg(OldCW);
14377
14378     // Get the X86 opcode to use.
14379     unsigned Opc;
14380     switch (MI->getOpcode()) {
14381     default: llvm_unreachable("illegal opcode!");
14382     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14383     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14384     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14385     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14386     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14387     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14388     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14389     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14390     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14391     }
14392
14393     X86AddressMode AM;
14394     MachineOperand &Op = MI->getOperand(0);
14395     if (Op.isReg()) {
14396       AM.BaseType = X86AddressMode::RegBase;
14397       AM.Base.Reg = Op.getReg();
14398     } else {
14399       AM.BaseType = X86AddressMode::FrameIndexBase;
14400       AM.Base.FrameIndex = Op.getIndex();
14401     }
14402     Op = MI->getOperand(1);
14403     if (Op.isImm())
14404       AM.Scale = Op.getImm();
14405     Op = MI->getOperand(2);
14406     if (Op.isImm())
14407       AM.IndexReg = Op.getImm();
14408     Op = MI->getOperand(3);
14409     if (Op.isGlobal()) {
14410       AM.GV = Op.getGlobal();
14411     } else {
14412       AM.Disp = Op.getImm();
14413     }
14414     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14415                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14416
14417     // Reload the original control word now.
14418     addFrameReference(BuildMI(*BB, MI, DL,
14419                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14420
14421     MI->eraseFromParent();   // The pseudo instruction is gone now.
14422     return BB;
14423   }
14424     // String/text processing lowering.
14425   case X86::PCMPISTRM128REG:
14426   case X86::VPCMPISTRM128REG:
14427   case X86::PCMPISTRM128MEM:
14428   case X86::VPCMPISTRM128MEM:
14429   case X86::PCMPESTRM128REG:
14430   case X86::VPCMPESTRM128REG:
14431   case X86::PCMPESTRM128MEM:
14432   case X86::VPCMPESTRM128MEM:
14433     assert(Subtarget->hasSSE42() &&
14434            "Target must have SSE4.2 or AVX features enabled");
14435     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14436
14437   // String/text processing lowering.
14438   case X86::PCMPISTRIREG:
14439   case X86::VPCMPISTRIREG:
14440   case X86::PCMPISTRIMEM:
14441   case X86::VPCMPISTRIMEM:
14442   case X86::PCMPESTRIREG:
14443   case X86::VPCMPESTRIREG:
14444   case X86::PCMPESTRIMEM:
14445   case X86::VPCMPESTRIMEM:
14446     assert(Subtarget->hasSSE42() &&
14447            "Target must have SSE4.2 or AVX features enabled");
14448     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14449
14450   // Thread synchronization.
14451   case X86::MONITOR:
14452     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14453
14454   // xbegin
14455   case X86::XBEGIN:
14456     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14457
14458   // Atomic Lowering.
14459   case X86::ATOMAND8:
14460   case X86::ATOMAND16:
14461   case X86::ATOMAND32:
14462   case X86::ATOMAND64:
14463     // Fall through
14464   case X86::ATOMOR8:
14465   case X86::ATOMOR16:
14466   case X86::ATOMOR32:
14467   case X86::ATOMOR64:
14468     // Fall through
14469   case X86::ATOMXOR16:
14470   case X86::ATOMXOR8:
14471   case X86::ATOMXOR32:
14472   case X86::ATOMXOR64:
14473     // Fall through
14474   case X86::ATOMNAND8:
14475   case X86::ATOMNAND16:
14476   case X86::ATOMNAND32:
14477   case X86::ATOMNAND64:
14478     // Fall through
14479   case X86::ATOMMAX8:
14480   case X86::ATOMMAX16:
14481   case X86::ATOMMAX32:
14482   case X86::ATOMMAX64:
14483     // Fall through
14484   case X86::ATOMMIN8:
14485   case X86::ATOMMIN16:
14486   case X86::ATOMMIN32:
14487   case X86::ATOMMIN64:
14488     // Fall through
14489   case X86::ATOMUMAX8:
14490   case X86::ATOMUMAX16:
14491   case X86::ATOMUMAX32:
14492   case X86::ATOMUMAX64:
14493     // Fall through
14494   case X86::ATOMUMIN8:
14495   case X86::ATOMUMIN16:
14496   case X86::ATOMUMIN32:
14497   case X86::ATOMUMIN64:
14498     return EmitAtomicLoadArith(MI, BB);
14499
14500   // This group does 64-bit operations on a 32-bit host.
14501   case X86::ATOMAND6432:
14502   case X86::ATOMOR6432:
14503   case X86::ATOMXOR6432:
14504   case X86::ATOMNAND6432:
14505   case X86::ATOMADD6432:
14506   case X86::ATOMSUB6432:
14507   case X86::ATOMMAX6432:
14508   case X86::ATOMMIN6432:
14509   case X86::ATOMUMAX6432:
14510   case X86::ATOMUMIN6432:
14511   case X86::ATOMSWAP6432:
14512     return EmitAtomicLoadArith6432(MI, BB);
14513
14514   case X86::VASTART_SAVE_XMM_REGS:
14515     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14516
14517   case X86::VAARG_64:
14518     return EmitVAARG64WithCustomInserter(MI, BB);
14519
14520   case X86::EH_SjLj_SetJmp32:
14521   case X86::EH_SjLj_SetJmp64:
14522     return emitEHSjLjSetJmp(MI, BB);
14523
14524   case X86::EH_SjLj_LongJmp32:
14525   case X86::EH_SjLj_LongJmp64:
14526     return emitEHSjLjLongJmp(MI, BB);
14527   }
14528 }
14529
14530 //===----------------------------------------------------------------------===//
14531 //                           X86 Optimization Hooks
14532 //===----------------------------------------------------------------------===//
14533
14534 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14535                                                        APInt &KnownZero,
14536                                                        APInt &KnownOne,
14537                                                        const SelectionDAG &DAG,
14538                                                        unsigned Depth) const {
14539   unsigned BitWidth = KnownZero.getBitWidth();
14540   unsigned Opc = Op.getOpcode();
14541   assert((Opc >= ISD::BUILTIN_OP_END ||
14542           Opc == ISD::INTRINSIC_WO_CHAIN ||
14543           Opc == ISD::INTRINSIC_W_CHAIN ||
14544           Opc == ISD::INTRINSIC_VOID) &&
14545          "Should use MaskedValueIsZero if you don't know whether Op"
14546          " is a target node!");
14547
14548   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14549   switch (Opc) {
14550   default: break;
14551   case X86ISD::ADD:
14552   case X86ISD::SUB:
14553   case X86ISD::ADC:
14554   case X86ISD::SBB:
14555   case X86ISD::SMUL:
14556   case X86ISD::UMUL:
14557   case X86ISD::INC:
14558   case X86ISD::DEC:
14559   case X86ISD::OR:
14560   case X86ISD::XOR:
14561   case X86ISD::AND:
14562     // These nodes' second result is a boolean.
14563     if (Op.getResNo() == 0)
14564       break;
14565     // Fallthrough
14566   case X86ISD::SETCC:
14567     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14568     break;
14569   case ISD::INTRINSIC_WO_CHAIN: {
14570     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14571     unsigned NumLoBits = 0;
14572     switch (IntId) {
14573     default: break;
14574     case Intrinsic::x86_sse_movmsk_ps:
14575     case Intrinsic::x86_avx_movmsk_ps_256:
14576     case Intrinsic::x86_sse2_movmsk_pd:
14577     case Intrinsic::x86_avx_movmsk_pd_256:
14578     case Intrinsic::x86_mmx_pmovmskb:
14579     case Intrinsic::x86_sse2_pmovmskb_128:
14580     case Intrinsic::x86_avx2_pmovmskb: {
14581       // High bits of movmskp{s|d}, pmovmskb are known zero.
14582       switch (IntId) {
14583         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14584         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14585         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14586         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14587         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14588         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14589         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14590         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14591       }
14592       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14593       break;
14594     }
14595     }
14596     break;
14597   }
14598   }
14599 }
14600
14601 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14602                                                          unsigned Depth) const {
14603   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14604   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14605     return Op.getValueType().getScalarType().getSizeInBits();
14606
14607   // Fallback case.
14608   return 1;
14609 }
14610
14611 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14612 /// node is a GlobalAddress + offset.
14613 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14614                                        const GlobalValue* &GA,
14615                                        int64_t &Offset) const {
14616   if (N->getOpcode() == X86ISD::Wrapper) {
14617     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14618       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14619       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14620       return true;
14621     }
14622   }
14623   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14624 }
14625
14626 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14627 /// same as extracting the high 128-bit part of 256-bit vector and then
14628 /// inserting the result into the low part of a new 256-bit vector
14629 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14630   EVT VT = SVOp->getValueType(0);
14631   unsigned NumElems = VT.getVectorNumElements();
14632
14633   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14634   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14635     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14636         SVOp->getMaskElt(j) >= 0)
14637       return false;
14638
14639   return true;
14640 }
14641
14642 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14643 /// same as extracting the low 128-bit part of 256-bit vector and then
14644 /// inserting the result into the high part of a new 256-bit vector
14645 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14646   EVT VT = SVOp->getValueType(0);
14647   unsigned NumElems = VT.getVectorNumElements();
14648
14649   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14650   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14651     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14652         SVOp->getMaskElt(j) >= 0)
14653       return false;
14654
14655   return true;
14656 }
14657
14658 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14659 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14660                                         TargetLowering::DAGCombinerInfo &DCI,
14661                                         const X86Subtarget* Subtarget) {
14662   DebugLoc dl = N->getDebugLoc();
14663   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14664   SDValue V1 = SVOp->getOperand(0);
14665   SDValue V2 = SVOp->getOperand(1);
14666   EVT VT = SVOp->getValueType(0);
14667   unsigned NumElems = VT.getVectorNumElements();
14668
14669   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14670       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14671     //
14672     //                   0,0,0,...
14673     //                      |
14674     //    V      UNDEF    BUILD_VECTOR    UNDEF
14675     //     \      /           \           /
14676     //  CONCAT_VECTOR         CONCAT_VECTOR
14677     //         \                  /
14678     //          \                /
14679     //          RESULT: V + zero extended
14680     //
14681     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14682         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14683         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14684       return SDValue();
14685
14686     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14687       return SDValue();
14688
14689     // To match the shuffle mask, the first half of the mask should
14690     // be exactly the first vector, and all the rest a splat with the
14691     // first element of the second one.
14692     for (unsigned i = 0; i != NumElems/2; ++i)
14693       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14694           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14695         return SDValue();
14696
14697     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14698     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14699       if (Ld->hasNUsesOfValue(1, 0)) {
14700         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14701         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14702         SDValue ResNode =
14703           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14704                                   Ld->getMemoryVT(),
14705                                   Ld->getPointerInfo(),
14706                                   Ld->getAlignment(),
14707                                   false/*isVolatile*/, true/*ReadMem*/,
14708                                   false/*WriteMem*/);
14709
14710         // Make sure the newly-created LOAD is in the same position as Ld in
14711         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14712         // and update uses of Ld's output chain to use the TokenFactor.
14713         if (Ld->hasAnyUseOfValue(1)) {
14714           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14715                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14716           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14717           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14718                                  SDValue(ResNode.getNode(), 1));
14719         }
14720
14721         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14722       }
14723     }
14724
14725     // Emit a zeroed vector and insert the desired subvector on its
14726     // first half.
14727     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14728     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14729     return DCI.CombineTo(N, InsV);
14730   }
14731
14732   //===--------------------------------------------------------------------===//
14733   // Combine some shuffles into subvector extracts and inserts:
14734   //
14735
14736   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14737   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14738     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14739     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14740     return DCI.CombineTo(N, InsV);
14741   }
14742
14743   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14744   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14745     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14746     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14747     return DCI.CombineTo(N, InsV);
14748   }
14749
14750   return SDValue();
14751 }
14752
14753 /// PerformShuffleCombine - Performs several different shuffle combines.
14754 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14755                                      TargetLowering::DAGCombinerInfo &DCI,
14756                                      const X86Subtarget *Subtarget) {
14757   DebugLoc dl = N->getDebugLoc();
14758   EVT VT = N->getValueType(0);
14759
14760   // Don't create instructions with illegal types after legalize types has run.
14761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14762   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14763     return SDValue();
14764
14765   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14766   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14767       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14768     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14769
14770   // Only handle 128 wide vector from here on.
14771   if (!VT.is128BitVector())
14772     return SDValue();
14773
14774   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14775   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14776   // consecutive, non-overlapping, and in the right order.
14777   SmallVector<SDValue, 16> Elts;
14778   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14779     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14780
14781   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14782 }
14783
14784 /// PerformTruncateCombine - Converts truncate operation to
14785 /// a sequence of vector shuffle operations.
14786 /// It is possible when we truncate 256-bit vector to 128-bit vector
14787 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14788                                       TargetLowering::DAGCombinerInfo &DCI,
14789                                       const X86Subtarget *Subtarget)  {
14790   return SDValue();
14791 }
14792
14793 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14794 /// specific shuffle of a load can be folded into a single element load.
14795 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14796 /// shuffles have been customed lowered so we need to handle those here.
14797 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14798                                          TargetLowering::DAGCombinerInfo &DCI) {
14799   if (DCI.isBeforeLegalizeOps())
14800     return SDValue();
14801
14802   SDValue InVec = N->getOperand(0);
14803   SDValue EltNo = N->getOperand(1);
14804
14805   if (!isa<ConstantSDNode>(EltNo))
14806     return SDValue();
14807
14808   EVT VT = InVec.getValueType();
14809
14810   bool HasShuffleIntoBitcast = false;
14811   if (InVec.getOpcode() == ISD::BITCAST) {
14812     // Don't duplicate a load with other uses.
14813     if (!InVec.hasOneUse())
14814       return SDValue();
14815     EVT BCVT = InVec.getOperand(0).getValueType();
14816     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14817       return SDValue();
14818     InVec = InVec.getOperand(0);
14819     HasShuffleIntoBitcast = true;
14820   }
14821
14822   if (!isTargetShuffle(InVec.getOpcode()))
14823     return SDValue();
14824
14825   // Don't duplicate a load with other uses.
14826   if (!InVec.hasOneUse())
14827     return SDValue();
14828
14829   SmallVector<int, 16> ShuffleMask;
14830   bool UnaryShuffle;
14831   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14832                             UnaryShuffle))
14833     return SDValue();
14834
14835   // Select the input vector, guarding against out of range extract vector.
14836   unsigned NumElems = VT.getVectorNumElements();
14837   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14838   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14839   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14840                                          : InVec.getOperand(1);
14841
14842   // If inputs to shuffle are the same for both ops, then allow 2 uses
14843   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14844
14845   if (LdNode.getOpcode() == ISD::BITCAST) {
14846     // Don't duplicate a load with other uses.
14847     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14848       return SDValue();
14849
14850     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14851     LdNode = LdNode.getOperand(0);
14852   }
14853
14854   if (!ISD::isNormalLoad(LdNode.getNode()))
14855     return SDValue();
14856
14857   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14858
14859   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14860     return SDValue();
14861
14862   if (HasShuffleIntoBitcast) {
14863     // If there's a bitcast before the shuffle, check if the load type and
14864     // alignment is valid.
14865     unsigned Align = LN0->getAlignment();
14866     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14867     unsigned NewAlign = TLI.getDataLayout()->
14868       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14869
14870     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14871       return SDValue();
14872   }
14873
14874   // All checks match so transform back to vector_shuffle so that DAG combiner
14875   // can finish the job
14876   DebugLoc dl = N->getDebugLoc();
14877
14878   // Create shuffle node taking into account the case that its a unary shuffle
14879   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14880   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14881                                  InVec.getOperand(0), Shuffle,
14882                                  &ShuffleMask[0]);
14883   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14884   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14885                      EltNo);
14886 }
14887
14888 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14889 /// generation and convert it from being a bunch of shuffles and extracts
14890 /// to a simple store and scalar loads to extract the elements.
14891 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14892                                          TargetLowering::DAGCombinerInfo &DCI) {
14893   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14894   if (NewOp.getNode())
14895     return NewOp;
14896
14897   SDValue InputVector = N->getOperand(0);
14898   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14899   // from mmx to v2i32 has a single usage.
14900   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14901       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14902       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14903     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14904                        N->getValueType(0),
14905                        InputVector.getNode()->getOperand(0));
14906
14907   // Only operate on vectors of 4 elements, where the alternative shuffling
14908   // gets to be more expensive.
14909   if (InputVector.getValueType() != MVT::v4i32)
14910     return SDValue();
14911
14912   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14913   // single use which is a sign-extend or zero-extend, and all elements are
14914   // used.
14915   SmallVector<SDNode *, 4> Uses;
14916   unsigned ExtractedElements = 0;
14917   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14918        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14919     if (UI.getUse().getResNo() != InputVector.getResNo())
14920       return SDValue();
14921
14922     SDNode *Extract = *UI;
14923     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14924       return SDValue();
14925
14926     if (Extract->getValueType(0) != MVT::i32)
14927       return SDValue();
14928     if (!Extract->hasOneUse())
14929       return SDValue();
14930     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14931         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14932       return SDValue();
14933     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14934       return SDValue();
14935
14936     // Record which element was extracted.
14937     ExtractedElements |=
14938       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14939
14940     Uses.push_back(Extract);
14941   }
14942
14943   // If not all the elements were used, this may not be worthwhile.
14944   if (ExtractedElements != 15)
14945     return SDValue();
14946
14947   // Ok, we've now decided to do the transformation.
14948   DebugLoc dl = InputVector.getDebugLoc();
14949
14950   // Store the value to a temporary stack slot.
14951   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14952   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14953                             MachinePointerInfo(), false, false, 0);
14954
14955   // Replace each use (extract) with a load of the appropriate element.
14956   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14957        UE = Uses.end(); UI != UE; ++UI) {
14958     SDNode *Extract = *UI;
14959
14960     // cOMpute the element's address.
14961     SDValue Idx = Extract->getOperand(1);
14962     unsigned EltSize =
14963         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14964     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14965     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14966     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14967
14968     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14969                                      StackPtr, OffsetVal);
14970
14971     // Load the scalar.
14972     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14973                                      ScalarAddr, MachinePointerInfo(),
14974                                      false, false, false, 0);
14975
14976     // Replace the exact with the load.
14977     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14978   }
14979
14980   // The replacement was made in place; don't return anything.
14981   return SDValue();
14982 }
14983
14984 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14985 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14986                                    SDValue RHS, SelectionDAG &DAG,
14987                                    const X86Subtarget *Subtarget) {
14988   if (!VT.isVector())
14989     return 0;
14990
14991   switch (VT.getSimpleVT().SimpleTy) {
14992   default: return 0;
14993   case MVT::v32i8:
14994   case MVT::v16i16:
14995   case MVT::v8i32:
14996     if (!Subtarget->hasAVX2())
14997       return 0;
14998   case MVT::v16i8:
14999   case MVT::v8i16:
15000   case MVT::v4i32:
15001     if (!Subtarget->hasSSE2())
15002       return 0;
15003   }
15004
15005   // SSE2 has only a small subset of the operations.
15006   bool hasUnsigned = Subtarget->hasSSE41() ||
15007                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15008   bool hasSigned = Subtarget->hasSSE41() ||
15009                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15010
15011   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15012
15013   // Check for x CC y ? x : y.
15014   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15015       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15016     switch (CC) {
15017     default: break;
15018     case ISD::SETULT:
15019     case ISD::SETULE:
15020       return hasUnsigned ? X86ISD::UMIN : 0;
15021     case ISD::SETUGT:
15022     case ISD::SETUGE:
15023       return hasUnsigned ? X86ISD::UMAX : 0;
15024     case ISD::SETLT:
15025     case ISD::SETLE:
15026       return hasSigned ? X86ISD::SMIN : 0;
15027     case ISD::SETGT:
15028     case ISD::SETGE:
15029       return hasSigned ? X86ISD::SMAX : 0;
15030     }
15031   // Check for x CC y ? y : x -- a min/max with reversed arms.
15032   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15033              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15034     switch (CC) {
15035     default: break;
15036     case ISD::SETULT:
15037     case ISD::SETULE:
15038       return hasUnsigned ? X86ISD::UMAX : 0;
15039     case ISD::SETUGT:
15040     case ISD::SETUGE:
15041       return hasUnsigned ? X86ISD::UMIN : 0;
15042     case ISD::SETLT:
15043     case ISD::SETLE:
15044       return hasSigned ? X86ISD::SMAX : 0;
15045     case ISD::SETGT:
15046     case ISD::SETGE:
15047       return hasSigned ? X86ISD::SMIN : 0;
15048     }
15049   }
15050
15051   return 0;
15052 }
15053
15054 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15055 /// nodes.
15056 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15057                                     TargetLowering::DAGCombinerInfo &DCI,
15058                                     const X86Subtarget *Subtarget) {
15059   DebugLoc DL = N->getDebugLoc();
15060   SDValue Cond = N->getOperand(0);
15061   // Get the LHS/RHS of the select.
15062   SDValue LHS = N->getOperand(1);
15063   SDValue RHS = N->getOperand(2);
15064   EVT VT = LHS.getValueType();
15065
15066   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15067   // instructions match the semantics of the common C idiom x<y?x:y but not
15068   // x<=y?x:y, because of how they handle negative zero (which can be
15069   // ignored in unsafe-math mode).
15070   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15071       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15072       (Subtarget->hasSSE2() ||
15073        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15074     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15075
15076     unsigned Opcode = 0;
15077     // Check for x CC y ? x : y.
15078     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15079         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15080       switch (CC) {
15081       default: break;
15082       case ISD::SETULT:
15083         // Converting this to a min would handle NaNs incorrectly, and swapping
15084         // the operands would cause it to handle comparisons between positive
15085         // and negative zero incorrectly.
15086         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15087           if (!DAG.getTarget().Options.UnsafeFPMath &&
15088               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15089             break;
15090           std::swap(LHS, RHS);
15091         }
15092         Opcode = X86ISD::FMIN;
15093         break;
15094       case ISD::SETOLE:
15095         // Converting this to a min would handle comparisons between positive
15096         // and negative zero incorrectly.
15097         if (!DAG.getTarget().Options.UnsafeFPMath &&
15098             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15099           break;
15100         Opcode = X86ISD::FMIN;
15101         break;
15102       case ISD::SETULE:
15103         // Converting this to a min would handle both negative zeros and NaNs
15104         // incorrectly, but we can swap the operands to fix both.
15105         std::swap(LHS, RHS);
15106       case ISD::SETOLT:
15107       case ISD::SETLT:
15108       case ISD::SETLE:
15109         Opcode = X86ISD::FMIN;
15110         break;
15111
15112       case ISD::SETOGE:
15113         // Converting this to a max would handle comparisons between positive
15114         // and negative zero incorrectly.
15115         if (!DAG.getTarget().Options.UnsafeFPMath &&
15116             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15117           break;
15118         Opcode = X86ISD::FMAX;
15119         break;
15120       case ISD::SETUGT:
15121         // Converting this to a max would handle NaNs incorrectly, and swapping
15122         // the operands would cause it to handle comparisons between positive
15123         // and negative zero incorrectly.
15124         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15125           if (!DAG.getTarget().Options.UnsafeFPMath &&
15126               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15127             break;
15128           std::swap(LHS, RHS);
15129         }
15130         Opcode = X86ISD::FMAX;
15131         break;
15132       case ISD::SETUGE:
15133         // Converting this to a max would handle both negative zeros and NaNs
15134         // incorrectly, but we can swap the operands to fix both.
15135         std::swap(LHS, RHS);
15136       case ISD::SETOGT:
15137       case ISD::SETGT:
15138       case ISD::SETGE:
15139         Opcode = X86ISD::FMAX;
15140         break;
15141       }
15142     // Check for x CC y ? y : x -- a min/max with reversed arms.
15143     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15144                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15145       switch (CC) {
15146       default: break;
15147       case ISD::SETOGE:
15148         // Converting this to a min would handle comparisons between positive
15149         // and negative zero incorrectly, and swapping the operands would
15150         // cause it to handle NaNs incorrectly.
15151         if (!DAG.getTarget().Options.UnsafeFPMath &&
15152             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15153           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15154             break;
15155           std::swap(LHS, RHS);
15156         }
15157         Opcode = X86ISD::FMIN;
15158         break;
15159       case ISD::SETUGT:
15160         // Converting this to a min would handle NaNs incorrectly.
15161         if (!DAG.getTarget().Options.UnsafeFPMath &&
15162             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15163           break;
15164         Opcode = X86ISD::FMIN;
15165         break;
15166       case ISD::SETUGE:
15167         // Converting this to a min would handle both negative zeros and NaNs
15168         // incorrectly, but we can swap the operands to fix both.
15169         std::swap(LHS, RHS);
15170       case ISD::SETOGT:
15171       case ISD::SETGT:
15172       case ISD::SETGE:
15173         Opcode = X86ISD::FMIN;
15174         break;
15175
15176       case ISD::SETULT:
15177         // Converting this to a max would handle NaNs incorrectly.
15178         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15179           break;
15180         Opcode = X86ISD::FMAX;
15181         break;
15182       case ISD::SETOLE:
15183         // Converting this to a max would handle comparisons between positive
15184         // and negative zero incorrectly, and swapping the operands would
15185         // cause it to handle NaNs incorrectly.
15186         if (!DAG.getTarget().Options.UnsafeFPMath &&
15187             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15188           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15189             break;
15190           std::swap(LHS, RHS);
15191         }
15192         Opcode = X86ISD::FMAX;
15193         break;
15194       case ISD::SETULE:
15195         // Converting this to a max would handle both negative zeros and NaNs
15196         // incorrectly, but we can swap the operands to fix both.
15197         std::swap(LHS, RHS);
15198       case ISD::SETOLT:
15199       case ISD::SETLT:
15200       case ISD::SETLE:
15201         Opcode = X86ISD::FMAX;
15202         break;
15203       }
15204     }
15205
15206     if (Opcode)
15207       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15208   }
15209
15210   // If this is a select between two integer constants, try to do some
15211   // optimizations.
15212   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15213     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15214       // Don't do this for crazy integer types.
15215       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15216         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15217         // so that TrueC (the true value) is larger than FalseC.
15218         bool NeedsCondInvert = false;
15219
15220         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15221             // Efficiently invertible.
15222             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15223              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15224               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15225           NeedsCondInvert = true;
15226           std::swap(TrueC, FalseC);
15227         }
15228
15229         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15230         if (FalseC->getAPIntValue() == 0 &&
15231             TrueC->getAPIntValue().isPowerOf2()) {
15232           if (NeedsCondInvert) // Invert the condition if needed.
15233             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15234                                DAG.getConstant(1, Cond.getValueType()));
15235
15236           // Zero extend the condition if needed.
15237           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15238
15239           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15240           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15241                              DAG.getConstant(ShAmt, MVT::i8));
15242         }
15243
15244         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15245         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15246           if (NeedsCondInvert) // Invert the condition if needed.
15247             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15248                                DAG.getConstant(1, Cond.getValueType()));
15249
15250           // Zero extend the condition if needed.
15251           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15252                              FalseC->getValueType(0), Cond);
15253           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15254                              SDValue(FalseC, 0));
15255         }
15256
15257         // Optimize cases that will turn into an LEA instruction.  This requires
15258         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15259         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15260           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15261           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15262
15263           bool isFastMultiplier = false;
15264           if (Diff < 10) {
15265             switch ((unsigned char)Diff) {
15266               default: break;
15267               case 1:  // result = add base, cond
15268               case 2:  // result = lea base(    , cond*2)
15269               case 3:  // result = lea base(cond, cond*2)
15270               case 4:  // result = lea base(    , cond*4)
15271               case 5:  // result = lea base(cond, cond*4)
15272               case 8:  // result = lea base(    , cond*8)
15273               case 9:  // result = lea base(cond, cond*8)
15274                 isFastMultiplier = true;
15275                 break;
15276             }
15277           }
15278
15279           if (isFastMultiplier) {
15280             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15281             if (NeedsCondInvert) // Invert the condition if needed.
15282               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15283                                  DAG.getConstant(1, Cond.getValueType()));
15284
15285             // Zero extend the condition if needed.
15286             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15287                                Cond);
15288             // Scale the condition by the difference.
15289             if (Diff != 1)
15290               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15291                                  DAG.getConstant(Diff, Cond.getValueType()));
15292
15293             // Add the base if non-zero.
15294             if (FalseC->getAPIntValue() != 0)
15295               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15296                                  SDValue(FalseC, 0));
15297             return Cond;
15298           }
15299         }
15300       }
15301   }
15302
15303   // Canonicalize max and min:
15304   // (x > y) ? x : y -> (x >= y) ? x : y
15305   // (x < y) ? x : y -> (x <= y) ? x : y
15306   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15307   // the need for an extra compare
15308   // against zero. e.g.
15309   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15310   // subl   %esi, %edi
15311   // testl  %edi, %edi
15312   // movl   $0, %eax
15313   // cmovgl %edi, %eax
15314   // =>
15315   // xorl   %eax, %eax
15316   // subl   %esi, $edi
15317   // cmovsl %eax, %edi
15318   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15319       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15320       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15321     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15322     switch (CC) {
15323     default: break;
15324     case ISD::SETLT:
15325     case ISD::SETGT: {
15326       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15327       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15328                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15329       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15330     }
15331     }
15332   }
15333
15334   // Match VSELECTs into subs with unsigned saturation.
15335   if (!DCI.isBeforeLegalize() &&
15336       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15337       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15338       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15339        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15340     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15341
15342     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15343     // left side invert the predicate to simplify logic below.
15344     SDValue Other;
15345     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15346       Other = RHS;
15347       CC = ISD::getSetCCInverse(CC, true);
15348     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15349       Other = LHS;
15350     }
15351
15352     if (Other.getNode() && Other->getNumOperands() == 2 &&
15353         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15354       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15355       SDValue CondRHS = Cond->getOperand(1);
15356
15357       // Look for a general sub with unsigned saturation first.
15358       // x >= y ? x-y : 0 --> subus x, y
15359       // x >  y ? x-y : 0 --> subus x, y
15360       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15361           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15362         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15363
15364       // If the RHS is a constant we have to reverse the const canonicalization.
15365       // x > C-1 ? x+-C : 0 --> subus x, C
15366       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15367           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15368         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15369         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15370           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15371                                      DAG.getConstant(-A, VT.getScalarType()));
15372           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15373                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15374                                          V.data(), V.size()));
15375         }
15376       }
15377
15378       // Another special case: If C was a sign bit, the sub has been
15379       // canonicalized into a xor.
15380       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15381       //        it's safe to decanonicalize the xor?
15382       // x s< 0 ? x^C : 0 --> subus x, C
15383       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15384           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15385           isSplatVector(OpRHS.getNode())) {
15386         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15387         if (A.isSignBit())
15388           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15389       }
15390     }
15391   }
15392
15393   // Try to match a min/max vector operation.
15394   if (!DCI.isBeforeLegalize() &&
15395       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15396     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15397       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15398
15399   // If we know that this node is legal then we know that it is going to be
15400   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15401   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15402   // to simplify previous instructions.
15403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15404   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15405       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15406     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15407
15408     // Don't optimize vector selects that map to mask-registers.
15409     if (BitWidth == 1)
15410       return SDValue();
15411
15412     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15413     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15414
15415     APInt KnownZero, KnownOne;
15416     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15417                                           DCI.isBeforeLegalizeOps());
15418     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15419         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15420       DCI.CommitTargetLoweringOpt(TLO);
15421   }
15422
15423   return SDValue();
15424 }
15425
15426 // Check whether a boolean test is testing a boolean value generated by
15427 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15428 // code.
15429 //
15430 // Simplify the following patterns:
15431 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15432 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15433 // to (Op EFLAGS Cond)
15434 //
15435 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15436 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15437 // to (Op EFLAGS !Cond)
15438 //
15439 // where Op could be BRCOND or CMOV.
15440 //
15441 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15442   // Quit if not CMP and SUB with its value result used.
15443   if (Cmp.getOpcode() != X86ISD::CMP &&
15444       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15445       return SDValue();
15446
15447   // Quit if not used as a boolean value.
15448   if (CC != X86::COND_E && CC != X86::COND_NE)
15449     return SDValue();
15450
15451   // Check CMP operands. One of them should be 0 or 1 and the other should be
15452   // an SetCC or extended from it.
15453   SDValue Op1 = Cmp.getOperand(0);
15454   SDValue Op2 = Cmp.getOperand(1);
15455
15456   SDValue SetCC;
15457   const ConstantSDNode* C = 0;
15458   bool needOppositeCond = (CC == X86::COND_E);
15459
15460   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15461     SetCC = Op2;
15462   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15463     SetCC = Op1;
15464   else // Quit if all operands are not constants.
15465     return SDValue();
15466
15467   if (C->getZExtValue() == 1)
15468     needOppositeCond = !needOppositeCond;
15469   else if (C->getZExtValue() != 0)
15470     // Quit if the constant is neither 0 or 1.
15471     return SDValue();
15472
15473   // Skip 'zext' node.
15474   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15475     SetCC = SetCC.getOperand(0);
15476
15477   switch (SetCC.getOpcode()) {
15478   case X86ISD::SETCC:
15479     // Set the condition code or opposite one if necessary.
15480     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15481     if (needOppositeCond)
15482       CC = X86::GetOppositeBranchCondition(CC);
15483     return SetCC.getOperand(1);
15484   case X86ISD::CMOV: {
15485     // Check whether false/true value has canonical one, i.e. 0 or 1.
15486     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15487     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15488     // Quit if true value is not a constant.
15489     if (!TVal)
15490       return SDValue();
15491     // Quit if false value is not a constant.
15492     if (!FVal) {
15493       // A special case for rdrand, where 0 is set if false cond is found.
15494       SDValue Op = SetCC.getOperand(0);
15495       if (Op.getOpcode() != X86ISD::RDRAND)
15496         return SDValue();
15497     }
15498     // Quit if false value is not the constant 0 or 1.
15499     bool FValIsFalse = true;
15500     if (FVal && FVal->getZExtValue() != 0) {
15501       if (FVal->getZExtValue() != 1)
15502         return SDValue();
15503       // If FVal is 1, opposite cond is needed.
15504       needOppositeCond = !needOppositeCond;
15505       FValIsFalse = false;
15506     }
15507     // Quit if TVal is not the constant opposite of FVal.
15508     if (FValIsFalse && TVal->getZExtValue() != 1)
15509       return SDValue();
15510     if (!FValIsFalse && TVal->getZExtValue() != 0)
15511       return SDValue();
15512     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15513     if (needOppositeCond)
15514       CC = X86::GetOppositeBranchCondition(CC);
15515     return SetCC.getOperand(3);
15516   }
15517   }
15518
15519   return SDValue();
15520 }
15521
15522 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15523 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15524                                   TargetLowering::DAGCombinerInfo &DCI,
15525                                   const X86Subtarget *Subtarget) {
15526   DebugLoc DL = N->getDebugLoc();
15527
15528   // If the flag operand isn't dead, don't touch this CMOV.
15529   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15530     return SDValue();
15531
15532   SDValue FalseOp = N->getOperand(0);
15533   SDValue TrueOp = N->getOperand(1);
15534   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15535   SDValue Cond = N->getOperand(3);
15536
15537   if (CC == X86::COND_E || CC == X86::COND_NE) {
15538     switch (Cond.getOpcode()) {
15539     default: break;
15540     case X86ISD::BSR:
15541     case X86ISD::BSF:
15542       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15543       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15544         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15545     }
15546   }
15547
15548   SDValue Flags;
15549
15550   Flags = checkBoolTestSetCCCombine(Cond, CC);
15551   if (Flags.getNode() &&
15552       // Extra check as FCMOV only supports a subset of X86 cond.
15553       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15554     SDValue Ops[] = { FalseOp, TrueOp,
15555                       DAG.getConstant(CC, MVT::i8), Flags };
15556     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15557                        Ops, array_lengthof(Ops));
15558   }
15559
15560   // If this is a select between two integer constants, try to do some
15561   // optimizations.  Note that the operands are ordered the opposite of SELECT
15562   // operands.
15563   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15564     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15565       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15566       // larger than FalseC (the false value).
15567       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15568         CC = X86::GetOppositeBranchCondition(CC);
15569         std::swap(TrueC, FalseC);
15570         std::swap(TrueOp, FalseOp);
15571       }
15572
15573       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15574       // This is efficient for any integer data type (including i8/i16) and
15575       // shift amount.
15576       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15577         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15578                            DAG.getConstant(CC, MVT::i8), Cond);
15579
15580         // Zero extend the condition if needed.
15581         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15582
15583         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15584         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15585                            DAG.getConstant(ShAmt, MVT::i8));
15586         if (N->getNumValues() == 2)  // Dead flag value?
15587           return DCI.CombineTo(N, Cond, SDValue());
15588         return Cond;
15589       }
15590
15591       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15592       // for any integer data type, including i8/i16.
15593       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15594         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15595                            DAG.getConstant(CC, MVT::i8), Cond);
15596
15597         // Zero extend the condition if needed.
15598         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15599                            FalseC->getValueType(0), Cond);
15600         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15601                            SDValue(FalseC, 0));
15602
15603         if (N->getNumValues() == 2)  // Dead flag value?
15604           return DCI.CombineTo(N, Cond, SDValue());
15605         return Cond;
15606       }
15607
15608       // Optimize cases that will turn into an LEA instruction.  This requires
15609       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15610       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15611         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15612         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15613
15614         bool isFastMultiplier = false;
15615         if (Diff < 10) {
15616           switch ((unsigned char)Diff) {
15617           default: break;
15618           case 1:  // result = add base, cond
15619           case 2:  // result = lea base(    , cond*2)
15620           case 3:  // result = lea base(cond, cond*2)
15621           case 4:  // result = lea base(    , cond*4)
15622           case 5:  // result = lea base(cond, cond*4)
15623           case 8:  // result = lea base(    , cond*8)
15624           case 9:  // result = lea base(cond, cond*8)
15625             isFastMultiplier = true;
15626             break;
15627           }
15628         }
15629
15630         if (isFastMultiplier) {
15631           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15632           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15633                              DAG.getConstant(CC, MVT::i8), Cond);
15634           // Zero extend the condition if needed.
15635           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15636                              Cond);
15637           // Scale the condition by the difference.
15638           if (Diff != 1)
15639             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15640                                DAG.getConstant(Diff, Cond.getValueType()));
15641
15642           // Add the base if non-zero.
15643           if (FalseC->getAPIntValue() != 0)
15644             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15645                                SDValue(FalseC, 0));
15646           if (N->getNumValues() == 2)  // Dead flag value?
15647             return DCI.CombineTo(N, Cond, SDValue());
15648           return Cond;
15649         }
15650       }
15651     }
15652   }
15653
15654   // Handle these cases:
15655   //   (select (x != c), e, c) -> select (x != c), e, x),
15656   //   (select (x == c), c, e) -> select (x == c), x, e)
15657   // where the c is an integer constant, and the "select" is the combination
15658   // of CMOV and CMP.
15659   //
15660   // The rationale for this change is that the conditional-move from a constant
15661   // needs two instructions, however, conditional-move from a register needs
15662   // only one instruction.
15663   //
15664   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15665   //  some instruction-combining opportunities. This opt needs to be
15666   //  postponed as late as possible.
15667   //
15668   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15669     // the DCI.xxxx conditions are provided to postpone the optimization as
15670     // late as possible.
15671
15672     ConstantSDNode *CmpAgainst = 0;
15673     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15674         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15675         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15676
15677       if (CC == X86::COND_NE &&
15678           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15679         CC = X86::GetOppositeBranchCondition(CC);
15680         std::swap(TrueOp, FalseOp);
15681       }
15682
15683       if (CC == X86::COND_E &&
15684           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15685         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15686                           DAG.getConstant(CC, MVT::i8), Cond };
15687         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15688                            array_lengthof(Ops));
15689       }
15690     }
15691   }
15692
15693   return SDValue();
15694 }
15695
15696 /// PerformMulCombine - Optimize a single multiply with constant into two
15697 /// in order to implement it with two cheaper instructions, e.g.
15698 /// LEA + SHL, LEA + LEA.
15699 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15700                                  TargetLowering::DAGCombinerInfo &DCI) {
15701   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15702     return SDValue();
15703
15704   EVT VT = N->getValueType(0);
15705   if (VT != MVT::i64)
15706     return SDValue();
15707
15708   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15709   if (!C)
15710     return SDValue();
15711   uint64_t MulAmt = C->getZExtValue();
15712   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15713     return SDValue();
15714
15715   uint64_t MulAmt1 = 0;
15716   uint64_t MulAmt2 = 0;
15717   if ((MulAmt % 9) == 0) {
15718     MulAmt1 = 9;
15719     MulAmt2 = MulAmt / 9;
15720   } else if ((MulAmt % 5) == 0) {
15721     MulAmt1 = 5;
15722     MulAmt2 = MulAmt / 5;
15723   } else if ((MulAmt % 3) == 0) {
15724     MulAmt1 = 3;
15725     MulAmt2 = MulAmt / 3;
15726   }
15727   if (MulAmt2 &&
15728       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15729     DebugLoc DL = N->getDebugLoc();
15730
15731     if (isPowerOf2_64(MulAmt2) &&
15732         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15733       // If second multiplifer is pow2, issue it first. We want the multiply by
15734       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15735       // is an add.
15736       std::swap(MulAmt1, MulAmt2);
15737
15738     SDValue NewMul;
15739     if (isPowerOf2_64(MulAmt1))
15740       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15741                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15742     else
15743       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15744                            DAG.getConstant(MulAmt1, VT));
15745
15746     if (isPowerOf2_64(MulAmt2))
15747       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15748                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15749     else
15750       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15751                            DAG.getConstant(MulAmt2, VT));
15752
15753     // Do not add new nodes to DAG combiner worklist.
15754     DCI.CombineTo(N, NewMul, false);
15755   }
15756   return SDValue();
15757 }
15758
15759 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15760   SDValue N0 = N->getOperand(0);
15761   SDValue N1 = N->getOperand(1);
15762   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15763   EVT VT = N0.getValueType();
15764
15765   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15766   // since the result of setcc_c is all zero's or all ones.
15767   if (VT.isInteger() && !VT.isVector() &&
15768       N1C && N0.getOpcode() == ISD::AND &&
15769       N0.getOperand(1).getOpcode() == ISD::Constant) {
15770     SDValue N00 = N0.getOperand(0);
15771     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15772         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15773           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15774          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15775       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15776       APInt ShAmt = N1C->getAPIntValue();
15777       Mask = Mask.shl(ShAmt);
15778       if (Mask != 0)
15779         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15780                            N00, DAG.getConstant(Mask, VT));
15781     }
15782   }
15783
15784   // Hardware support for vector shifts is sparse which makes us scalarize the
15785   // vector operations in many cases. Also, on sandybridge ADD is faster than
15786   // shl.
15787   // (shl V, 1) -> add V,V
15788   if (isSplatVector(N1.getNode())) {
15789     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15790     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15791     // We shift all of the values by one. In many cases we do not have
15792     // hardware support for this operation. This is better expressed as an ADD
15793     // of two values.
15794     if (N1C && (1 == N1C->getZExtValue())) {
15795       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15796     }
15797   }
15798
15799   return SDValue();
15800 }
15801
15802 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15803 ///                       when possible.
15804 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15805                                    TargetLowering::DAGCombinerInfo &DCI,
15806                                    const X86Subtarget *Subtarget) {
15807   EVT VT = N->getValueType(0);
15808   if (N->getOpcode() == ISD::SHL) {
15809     SDValue V = PerformSHLCombine(N, DAG);
15810     if (V.getNode()) return V;
15811   }
15812
15813   // On X86 with SSE2 support, we can transform this to a vector shift if
15814   // all elements are shifted by the same amount.  We can't do this in legalize
15815   // because the a constant vector is typically transformed to a constant pool
15816   // so we have no knowledge of the shift amount.
15817   if (!Subtarget->hasSSE2())
15818     return SDValue();
15819
15820   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15821       (!Subtarget->hasInt256() ||
15822        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15823     return SDValue();
15824
15825   SDValue ShAmtOp = N->getOperand(1);
15826   EVT EltVT = VT.getVectorElementType();
15827   DebugLoc DL = N->getDebugLoc();
15828   SDValue BaseShAmt = SDValue();
15829   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15830     unsigned NumElts = VT.getVectorNumElements();
15831     unsigned i = 0;
15832     for (; i != NumElts; ++i) {
15833       SDValue Arg = ShAmtOp.getOperand(i);
15834       if (Arg.getOpcode() == ISD::UNDEF) continue;
15835       BaseShAmt = Arg;
15836       break;
15837     }
15838     // Handle the case where the build_vector is all undef
15839     // FIXME: Should DAG allow this?
15840     if (i == NumElts)
15841       return SDValue();
15842
15843     for (; i != NumElts; ++i) {
15844       SDValue Arg = ShAmtOp.getOperand(i);
15845       if (Arg.getOpcode() == ISD::UNDEF) continue;
15846       if (Arg != BaseShAmt) {
15847         return SDValue();
15848       }
15849     }
15850   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15851              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15852     SDValue InVec = ShAmtOp.getOperand(0);
15853     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15854       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15855       unsigned i = 0;
15856       for (; i != NumElts; ++i) {
15857         SDValue Arg = InVec.getOperand(i);
15858         if (Arg.getOpcode() == ISD::UNDEF) continue;
15859         BaseShAmt = Arg;
15860         break;
15861       }
15862     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15863        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15864          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15865          if (C->getZExtValue() == SplatIdx)
15866            BaseShAmt = InVec.getOperand(1);
15867        }
15868     }
15869     if (BaseShAmt.getNode() == 0) {
15870       // Don't create instructions with illegal types after legalize
15871       // types has run.
15872       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15873           !DCI.isBeforeLegalize())
15874         return SDValue();
15875
15876       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15877                               DAG.getIntPtrConstant(0));
15878     }
15879   } else
15880     return SDValue();
15881
15882   // The shift amount is an i32.
15883   if (EltVT.bitsGT(MVT::i32))
15884     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15885   else if (EltVT.bitsLT(MVT::i32))
15886     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15887
15888   // The shift amount is identical so we can do a vector shift.
15889   SDValue  ValOp = N->getOperand(0);
15890   switch (N->getOpcode()) {
15891   default:
15892     llvm_unreachable("Unknown shift opcode!");
15893   case ISD::SHL:
15894     switch (VT.getSimpleVT().SimpleTy) {
15895     default: return SDValue();
15896     case MVT::v2i64:
15897     case MVT::v4i32:
15898     case MVT::v8i16:
15899     case MVT::v4i64:
15900     case MVT::v8i32:
15901     case MVT::v16i16:
15902       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15903     }
15904   case ISD::SRA:
15905     switch (VT.getSimpleVT().SimpleTy) {
15906     default: return SDValue();
15907     case MVT::v4i32:
15908     case MVT::v8i16:
15909     case MVT::v8i32:
15910     case MVT::v16i16:
15911       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15912     }
15913   case ISD::SRL:
15914     switch (VT.getSimpleVT().SimpleTy) {
15915     default: return SDValue();
15916     case MVT::v2i64:
15917     case MVT::v4i32:
15918     case MVT::v8i16:
15919     case MVT::v4i64:
15920     case MVT::v8i32:
15921     case MVT::v16i16:
15922       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15923     }
15924   }
15925 }
15926
15927 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15928 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15929 // and friends.  Likewise for OR -> CMPNEQSS.
15930 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15931                             TargetLowering::DAGCombinerInfo &DCI,
15932                             const X86Subtarget *Subtarget) {
15933   unsigned opcode;
15934
15935   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15936   // we're requiring SSE2 for both.
15937   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15938     SDValue N0 = N->getOperand(0);
15939     SDValue N1 = N->getOperand(1);
15940     SDValue CMP0 = N0->getOperand(1);
15941     SDValue CMP1 = N1->getOperand(1);
15942     DebugLoc DL = N->getDebugLoc();
15943
15944     // The SETCCs should both refer to the same CMP.
15945     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15946       return SDValue();
15947
15948     SDValue CMP00 = CMP0->getOperand(0);
15949     SDValue CMP01 = CMP0->getOperand(1);
15950     EVT     VT    = CMP00.getValueType();
15951
15952     if (VT == MVT::f32 || VT == MVT::f64) {
15953       bool ExpectingFlags = false;
15954       // Check for any users that want flags:
15955       for (SDNode::use_iterator UI = N->use_begin(),
15956              UE = N->use_end();
15957            !ExpectingFlags && UI != UE; ++UI)
15958         switch (UI->getOpcode()) {
15959         default:
15960         case ISD::BR_CC:
15961         case ISD::BRCOND:
15962         case ISD::SELECT:
15963           ExpectingFlags = true;
15964           break;
15965         case ISD::CopyToReg:
15966         case ISD::SIGN_EXTEND:
15967         case ISD::ZERO_EXTEND:
15968         case ISD::ANY_EXTEND:
15969           break;
15970         }
15971
15972       if (!ExpectingFlags) {
15973         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15974         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15975
15976         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15977           X86::CondCode tmp = cc0;
15978           cc0 = cc1;
15979           cc1 = tmp;
15980         }
15981
15982         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15983             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15984           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15985           X86ISD::NodeType NTOperator = is64BitFP ?
15986             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15987           // FIXME: need symbolic constants for these magic numbers.
15988           // See X86ATTInstPrinter.cpp:printSSECC().
15989           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15990           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15991                                               DAG.getConstant(x86cc, MVT::i8));
15992           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15993                                               OnesOrZeroesF);
15994           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15995                                       DAG.getConstant(1, MVT::i32));
15996           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15997           return OneBitOfTruth;
15998         }
15999       }
16000     }
16001   }
16002   return SDValue();
16003 }
16004
16005 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16006 /// so it can be folded inside ANDNP.
16007 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16008   EVT VT = N->getValueType(0);
16009
16010   // Match direct AllOnes for 128 and 256-bit vectors
16011   if (ISD::isBuildVectorAllOnes(N))
16012     return true;
16013
16014   // Look through a bit convert.
16015   if (N->getOpcode() == ISD::BITCAST)
16016     N = N->getOperand(0).getNode();
16017
16018   // Sometimes the operand may come from a insert_subvector building a 256-bit
16019   // allones vector
16020   if (VT.is256BitVector() &&
16021       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16022     SDValue V1 = N->getOperand(0);
16023     SDValue V2 = N->getOperand(1);
16024
16025     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16026         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16027         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16028         ISD::isBuildVectorAllOnes(V2.getNode()))
16029       return true;
16030   }
16031
16032   return false;
16033 }
16034
16035 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16036 // register. In most cases we actually compare or select YMM-sized registers
16037 // and mixing the two types creates horrible code. This method optimizes
16038 // some of the transition sequences.
16039 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16040                                  TargetLowering::DAGCombinerInfo &DCI,
16041                                  const X86Subtarget *Subtarget) {
16042   EVT VT = N->getValueType(0);
16043   if (!VT.is256BitVector())
16044     return SDValue();
16045
16046   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16047           N->getOpcode() == ISD::ZERO_EXTEND ||
16048           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16049
16050   SDValue Narrow = N->getOperand(0);
16051   EVT NarrowVT = Narrow->getValueType(0);
16052   if (!NarrowVT.is128BitVector())
16053     return SDValue();
16054
16055   if (Narrow->getOpcode() != ISD::XOR &&
16056       Narrow->getOpcode() != ISD::AND &&
16057       Narrow->getOpcode() != ISD::OR)
16058     return SDValue();
16059
16060   SDValue N0  = Narrow->getOperand(0);
16061   SDValue N1  = Narrow->getOperand(1);
16062   DebugLoc DL = Narrow->getDebugLoc();
16063
16064   // The Left side has to be a trunc.
16065   if (N0.getOpcode() != ISD::TRUNCATE)
16066     return SDValue();
16067
16068   // The type of the truncated inputs.
16069   EVT WideVT = N0->getOperand(0)->getValueType(0);
16070   if (WideVT != VT)
16071     return SDValue();
16072
16073   // The right side has to be a 'trunc' or a constant vector.
16074   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16075   bool RHSConst = (isSplatVector(N1.getNode()) &&
16076                    isa<ConstantSDNode>(N1->getOperand(0)));
16077   if (!RHSTrunc && !RHSConst)
16078     return SDValue();
16079
16080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16081
16082   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16083     return SDValue();
16084
16085   // Set N0 and N1 to hold the inputs to the new wide operation.
16086   N0 = N0->getOperand(0);
16087   if (RHSConst) {
16088     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16089                      N1->getOperand(0));
16090     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16091     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16092   } else if (RHSTrunc) {
16093     N1 = N1->getOperand(0);
16094   }
16095
16096   // Generate the wide operation.
16097   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16098   unsigned Opcode = N->getOpcode();
16099   switch (Opcode) {
16100   case ISD::ANY_EXTEND:
16101     return Op;
16102   case ISD::ZERO_EXTEND: {
16103     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16104     APInt Mask = APInt::getAllOnesValue(InBits);
16105     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16106     return DAG.getNode(ISD::AND, DL, VT,
16107                        Op, DAG.getConstant(Mask, VT));
16108   }
16109   case ISD::SIGN_EXTEND:
16110     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16111                        Op, DAG.getValueType(NarrowVT));
16112   default:
16113     llvm_unreachable("Unexpected opcode");
16114   }
16115 }
16116
16117 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16118                                  TargetLowering::DAGCombinerInfo &DCI,
16119                                  const X86Subtarget *Subtarget) {
16120   EVT VT = N->getValueType(0);
16121   if (DCI.isBeforeLegalizeOps())
16122     return SDValue();
16123
16124   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16125   if (R.getNode())
16126     return R;
16127
16128   // Create BLSI, and BLSR instructions
16129   // BLSI is X & (-X)
16130   // BLSR is X & (X-1)
16131   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16132     SDValue N0 = N->getOperand(0);
16133     SDValue N1 = N->getOperand(1);
16134     DebugLoc DL = N->getDebugLoc();
16135
16136     // Check LHS for neg
16137     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16138         isZero(N0.getOperand(0)))
16139       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16140
16141     // Check RHS for neg
16142     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16143         isZero(N1.getOperand(0)))
16144       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16145
16146     // Check LHS for X-1
16147     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16148         isAllOnes(N0.getOperand(1)))
16149       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16150
16151     // Check RHS for X-1
16152     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16153         isAllOnes(N1.getOperand(1)))
16154       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16155
16156     return SDValue();
16157   }
16158
16159   // Want to form ANDNP nodes:
16160   // 1) In the hopes of then easily combining them with OR and AND nodes
16161   //    to form PBLEND/PSIGN.
16162   // 2) To match ANDN packed intrinsics
16163   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16164     return SDValue();
16165
16166   SDValue N0 = N->getOperand(0);
16167   SDValue N1 = N->getOperand(1);
16168   DebugLoc DL = N->getDebugLoc();
16169
16170   // Check LHS for vnot
16171   if (N0.getOpcode() == ISD::XOR &&
16172       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16173       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16174     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16175
16176   // Check RHS for vnot
16177   if (N1.getOpcode() == ISD::XOR &&
16178       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16179       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16180     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16181
16182   return SDValue();
16183 }
16184
16185 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16186                                 TargetLowering::DAGCombinerInfo &DCI,
16187                                 const X86Subtarget *Subtarget) {
16188   EVT VT = N->getValueType(0);
16189   if (DCI.isBeforeLegalizeOps())
16190     return SDValue();
16191
16192   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16193   if (R.getNode())
16194     return R;
16195
16196   SDValue N0 = N->getOperand(0);
16197   SDValue N1 = N->getOperand(1);
16198
16199   // look for psign/blend
16200   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16201     if (!Subtarget->hasSSSE3() ||
16202         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16203       return SDValue();
16204
16205     // Canonicalize pandn to RHS
16206     if (N0.getOpcode() == X86ISD::ANDNP)
16207       std::swap(N0, N1);
16208     // or (and (m, y), (pandn m, x))
16209     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16210       SDValue Mask = N1.getOperand(0);
16211       SDValue X    = N1.getOperand(1);
16212       SDValue Y;
16213       if (N0.getOperand(0) == Mask)
16214         Y = N0.getOperand(1);
16215       if (N0.getOperand(1) == Mask)
16216         Y = N0.getOperand(0);
16217
16218       // Check to see if the mask appeared in both the AND and ANDNP and
16219       if (!Y.getNode())
16220         return SDValue();
16221
16222       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16223       // Look through mask bitcast.
16224       if (Mask.getOpcode() == ISD::BITCAST)
16225         Mask = Mask.getOperand(0);
16226       if (X.getOpcode() == ISD::BITCAST)
16227         X = X.getOperand(0);
16228       if (Y.getOpcode() == ISD::BITCAST)
16229         Y = Y.getOperand(0);
16230
16231       EVT MaskVT = Mask.getValueType();
16232
16233       // Validate that the Mask operand is a vector sra node.
16234       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16235       // there is no psrai.b
16236       if (Mask.getOpcode() != X86ISD::VSRAI)
16237         return SDValue();
16238
16239       // Check that the SRA is all signbits.
16240       SDValue SraC = Mask.getOperand(1);
16241       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16242       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16243       if ((SraAmt + 1) != EltBits)
16244         return SDValue();
16245
16246       DebugLoc DL = N->getDebugLoc();
16247
16248       // We are going to replace the AND, OR, NAND with either BLEND
16249       // or PSIGN, which only look at the MSB. The VSRAI instruction
16250       // does not affect the highest bit, so we can get rid of it.
16251       Mask = Mask.getOperand(0);
16252
16253       // Now we know we at least have a plendvb with the mask val.  See if
16254       // we can form a psignb/w/d.
16255       // psign = x.type == y.type == mask.type && y = sub(0, x);
16256       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16257           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16258           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16259         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16260                "Unsupported VT for PSIGN");
16261         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16262         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16263       }
16264       // PBLENDVB only available on SSE 4.1
16265       if (!Subtarget->hasSSE41())
16266         return SDValue();
16267
16268       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16269
16270       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16271       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16272       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16273       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16274       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16275     }
16276   }
16277
16278   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16279     return SDValue();
16280
16281   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16282   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16283     std::swap(N0, N1);
16284   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16285     return SDValue();
16286   if (!N0.hasOneUse() || !N1.hasOneUse())
16287     return SDValue();
16288
16289   SDValue ShAmt0 = N0.getOperand(1);
16290   if (ShAmt0.getValueType() != MVT::i8)
16291     return SDValue();
16292   SDValue ShAmt1 = N1.getOperand(1);
16293   if (ShAmt1.getValueType() != MVT::i8)
16294     return SDValue();
16295   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16296     ShAmt0 = ShAmt0.getOperand(0);
16297   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16298     ShAmt1 = ShAmt1.getOperand(0);
16299
16300   DebugLoc DL = N->getDebugLoc();
16301   unsigned Opc = X86ISD::SHLD;
16302   SDValue Op0 = N0.getOperand(0);
16303   SDValue Op1 = N1.getOperand(0);
16304   if (ShAmt0.getOpcode() == ISD::SUB) {
16305     Opc = X86ISD::SHRD;
16306     std::swap(Op0, Op1);
16307     std::swap(ShAmt0, ShAmt1);
16308   }
16309
16310   unsigned Bits = VT.getSizeInBits();
16311   if (ShAmt1.getOpcode() == ISD::SUB) {
16312     SDValue Sum = ShAmt1.getOperand(0);
16313     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16314       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16315       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16316         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16317       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16318         return DAG.getNode(Opc, DL, VT,
16319                            Op0, Op1,
16320                            DAG.getNode(ISD::TRUNCATE, DL,
16321                                        MVT::i8, ShAmt0));
16322     }
16323   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16324     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16325     if (ShAmt0C &&
16326         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16327       return DAG.getNode(Opc, DL, VT,
16328                          N0.getOperand(0), N1.getOperand(0),
16329                          DAG.getNode(ISD::TRUNCATE, DL,
16330                                        MVT::i8, ShAmt0));
16331   }
16332
16333   return SDValue();
16334 }
16335
16336 // Generate NEG and CMOV for integer abs.
16337 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16338   EVT VT = N->getValueType(0);
16339
16340   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16341   // 8-bit integer abs to NEG and CMOV.
16342   if (VT.isInteger() && VT.getSizeInBits() == 8)
16343     return SDValue();
16344
16345   SDValue N0 = N->getOperand(0);
16346   SDValue N1 = N->getOperand(1);
16347   DebugLoc DL = N->getDebugLoc();
16348
16349   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16350   // and change it to SUB and CMOV.
16351   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16352       N0.getOpcode() == ISD::ADD &&
16353       N0.getOperand(1) == N1 &&
16354       N1.getOpcode() == ISD::SRA &&
16355       N1.getOperand(0) == N0.getOperand(0))
16356     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16357       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16358         // Generate SUB & CMOV.
16359         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16360                                   DAG.getConstant(0, VT), N0.getOperand(0));
16361
16362         SDValue Ops[] = { N0.getOperand(0), Neg,
16363                           DAG.getConstant(X86::COND_GE, MVT::i8),
16364                           SDValue(Neg.getNode(), 1) };
16365         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16366                            Ops, array_lengthof(Ops));
16367       }
16368   return SDValue();
16369 }
16370
16371 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16372 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16373                                  TargetLowering::DAGCombinerInfo &DCI,
16374                                  const X86Subtarget *Subtarget) {
16375   EVT VT = N->getValueType(0);
16376   if (DCI.isBeforeLegalizeOps())
16377     return SDValue();
16378
16379   if (Subtarget->hasCMov()) {
16380     SDValue RV = performIntegerAbsCombine(N, DAG);
16381     if (RV.getNode())
16382       return RV;
16383   }
16384
16385   // Try forming BMI if it is available.
16386   if (!Subtarget->hasBMI())
16387     return SDValue();
16388
16389   if (VT != MVT::i32 && VT != MVT::i64)
16390     return SDValue();
16391
16392   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16393
16394   // Create BLSMSK instructions by finding X ^ (X-1)
16395   SDValue N0 = N->getOperand(0);
16396   SDValue N1 = N->getOperand(1);
16397   DebugLoc DL = N->getDebugLoc();
16398
16399   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16400       isAllOnes(N0.getOperand(1)))
16401     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16402
16403   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16404       isAllOnes(N1.getOperand(1)))
16405     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16406
16407   return SDValue();
16408 }
16409
16410 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16411 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16412                                   TargetLowering::DAGCombinerInfo &DCI,
16413                                   const X86Subtarget *Subtarget) {
16414   LoadSDNode *Ld = cast<LoadSDNode>(N);
16415   EVT RegVT = Ld->getValueType(0);
16416   EVT MemVT = Ld->getMemoryVT();
16417   DebugLoc dl = Ld->getDebugLoc();
16418   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16419   unsigned RegSz = RegVT.getSizeInBits();
16420
16421   ISD::LoadExtType Ext = Ld->getExtensionType();
16422   unsigned Alignment = Ld->getAlignment();
16423   bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16424
16425   // On Sandybridge unaligned 256bit loads are inefficient.
16426   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16427       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16428     unsigned NumElems = RegVT.getVectorNumElements();
16429     if (NumElems < 2)
16430       return SDValue();
16431
16432     SDValue Ptr = Ld->getBasePtr();
16433     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16434
16435     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16436                                   NumElems/2);
16437     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16438                                 Ld->getPointerInfo(), Ld->isVolatile(),
16439                                 Ld->isNonTemporal(), Ld->isInvariant(),
16440                                 Alignment);
16441     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16442     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16443                                 Ld->getPointerInfo(), Ld->isVolatile(),
16444                                 Ld->isNonTemporal(), Ld->isInvariant(),
16445                                 std::max(Alignment/2U, 1U));
16446     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16447                              Load1.getValue(1),
16448                              Load2.getValue(1));
16449
16450     SDValue NewVec = DAG.getUNDEF(RegVT);
16451     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16452     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16453     return DCI.CombineTo(N, NewVec, TF, true);
16454   }
16455
16456   // If this is a vector EXT Load then attempt to optimize it using a
16457   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16458   // expansion is still better than scalar code.
16459   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16460   // emit a shuffle and a arithmetic shift.
16461   // TODO: It is possible to support ZExt by zeroing the undef values
16462   // during the shuffle phase or after the shuffle.
16463   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16464       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16465     assert(MemVT != RegVT && "Cannot extend to the same type");
16466     assert(MemVT.isVector() && "Must load a vector from memory");
16467
16468     unsigned NumElems = RegVT.getVectorNumElements();
16469     unsigned MemSz = MemVT.getSizeInBits();
16470     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16471
16472     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16473       return SDValue();
16474
16475     // All sizes must be a power of two.
16476     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16477       return SDValue();
16478
16479     // Attempt to load the original value using scalar loads.
16480     // Find the largest scalar type that divides the total loaded size.
16481     MVT SclrLoadTy = MVT::i8;
16482     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16483          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16484       MVT Tp = (MVT::SimpleValueType)tp;
16485       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16486         SclrLoadTy = Tp;
16487       }
16488     }
16489
16490     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16491     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16492         (64 <= MemSz))
16493       SclrLoadTy = MVT::f64;
16494
16495     // Calculate the number of scalar loads that we need to perform
16496     // in order to load our vector from memory.
16497     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16498     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16499       return SDValue();
16500
16501     unsigned loadRegZize = RegSz;
16502     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16503       loadRegZize /= 2;
16504
16505     // Represent our vector as a sequence of elements which are the
16506     // largest scalar that we can load.
16507     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16508       loadRegZize/SclrLoadTy.getSizeInBits());
16509
16510     // Represent the data using the same element type that is stored in
16511     // memory. In practice, we ''widen'' MemVT.
16512     EVT WideVecVT = 
16513           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16514                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16515
16516     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16517       "Invalid vector type");
16518
16519     // We can't shuffle using an illegal type.
16520     if (!TLI.isTypeLegal(WideVecVT))
16521       return SDValue();
16522
16523     SmallVector<SDValue, 8> Chains;
16524     SDValue Ptr = Ld->getBasePtr();
16525     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16526                                         TLI.getPointerTy());
16527     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16528
16529     for (unsigned i = 0; i < NumLoads; ++i) {
16530       // Perform a single load.
16531       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16532                                        Ptr, Ld->getPointerInfo(),
16533                                        Ld->isVolatile(), Ld->isNonTemporal(),
16534                                        Ld->isInvariant(), Ld->getAlignment());
16535       Chains.push_back(ScalarLoad.getValue(1));
16536       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16537       // another round of DAGCombining.
16538       if (i == 0)
16539         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16540       else
16541         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16542                           ScalarLoad, DAG.getIntPtrConstant(i));
16543
16544       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16545     }
16546
16547     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16548                                Chains.size());
16549
16550     // Bitcast the loaded value to a vector of the original element type, in
16551     // the size of the target vector type.
16552     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16553     unsigned SizeRatio = RegSz/MemSz;
16554
16555     if (Ext == ISD::SEXTLOAD) {
16556       // If we have SSE4.1 we can directly emit a VSEXT node.
16557       if (Subtarget->hasSSE41()) {
16558         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16559         return DCI.CombineTo(N, Sext, TF, true);
16560       }
16561
16562       // Otherwise we'll shuffle the small elements in the high bits of the
16563       // larger type and perform an arithmetic shift. If the shift is not legal
16564       // it's better to scalarize.
16565       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16566         return SDValue();
16567
16568       // Redistribute the loaded elements into the different locations.
16569       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16570       for (unsigned i = 0; i != NumElems; ++i)
16571         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16572
16573       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16574                                            DAG.getUNDEF(WideVecVT),
16575                                            &ShuffleVec[0]);
16576
16577       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16578
16579       // Build the arithmetic shift.
16580       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16581                      MemVT.getVectorElementType().getSizeInBits();
16582       SmallVector<SDValue, 8> C(NumElems,
16583                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16584       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16585       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16586
16587       return DCI.CombineTo(N, Shuff, TF, true);
16588     }
16589
16590     // Redistribute the loaded elements into the different locations.
16591     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16592     for (unsigned i = 0; i != NumElems; ++i)
16593       ShuffleVec[i*SizeRatio] = i;
16594
16595     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16596                                          DAG.getUNDEF(WideVecVT),
16597                                          &ShuffleVec[0]);
16598
16599     // Bitcast to the requested type.
16600     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16601     // Replace the original load with the new sequence
16602     // and return the new chain.
16603     return DCI.CombineTo(N, Shuff, TF, true);
16604   }
16605
16606   return SDValue();
16607 }
16608
16609 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16610 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16611                                    const X86Subtarget *Subtarget) {
16612   StoreSDNode *St = cast<StoreSDNode>(N);
16613   EVT VT = St->getValue().getValueType();
16614   EVT StVT = St->getMemoryVT();
16615   DebugLoc dl = St->getDebugLoc();
16616   SDValue StoredVal = St->getOperand(1);
16617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16618   unsigned Alignment = St->getAlignment();
16619   bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16620
16621   // If we are saving a concatenation of two XMM registers, perform two stores.
16622   // On Sandy Bridge, 256-bit memory operations are executed by two
16623   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16624   // memory  operation.
16625   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16626       StVT == VT && !IsAligned) {
16627     unsigned NumElems = VT.getVectorNumElements();
16628     if (NumElems < 2)
16629       return SDValue();
16630
16631     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16632     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16633
16634     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16635     SDValue Ptr0 = St->getBasePtr();
16636     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16637
16638     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16639                                 St->getPointerInfo(), St->isVolatile(),
16640                                 St->isNonTemporal(), Alignment);
16641     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16642                                 St->getPointerInfo(), St->isVolatile(),
16643                                 St->isNonTemporal(),
16644                                 std::max(Alignment/2U, 1U));
16645     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16646   }
16647
16648   // Optimize trunc store (of multiple scalars) to shuffle and store.
16649   // First, pack all of the elements in one place. Next, store to memory
16650   // in fewer chunks.
16651   if (St->isTruncatingStore() && VT.isVector()) {
16652     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16653     unsigned NumElems = VT.getVectorNumElements();
16654     assert(StVT != VT && "Cannot truncate to the same type");
16655     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16656     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16657
16658     // From, To sizes and ElemCount must be pow of two
16659     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16660     // We are going to use the original vector elt for storing.
16661     // Accumulated smaller vector elements must be a multiple of the store size.
16662     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16663
16664     unsigned SizeRatio  = FromSz / ToSz;
16665
16666     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16667
16668     // Create a type on which we perform the shuffle
16669     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16670             StVT.getScalarType(), NumElems*SizeRatio);
16671
16672     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16673
16674     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16675     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16676     for (unsigned i = 0; i != NumElems; ++i)
16677       ShuffleVec[i] = i * SizeRatio;
16678
16679     // Can't shuffle using an illegal type.
16680     if (!TLI.isTypeLegal(WideVecVT))
16681       return SDValue();
16682
16683     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16684                                          DAG.getUNDEF(WideVecVT),
16685                                          &ShuffleVec[0]);
16686     // At this point all of the data is stored at the bottom of the
16687     // register. We now need to save it to mem.
16688
16689     // Find the largest store unit
16690     MVT StoreType = MVT::i8;
16691     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16692          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16693       MVT Tp = (MVT::SimpleValueType)tp;
16694       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16695         StoreType = Tp;
16696     }
16697
16698     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16699     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16700         (64 <= NumElems * ToSz))
16701       StoreType = MVT::f64;
16702
16703     // Bitcast the original vector into a vector of store-size units
16704     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16705             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16706     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16707     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16708     SmallVector<SDValue, 8> Chains;
16709     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16710                                         TLI.getPointerTy());
16711     SDValue Ptr = St->getBasePtr();
16712
16713     // Perform one or more big stores into memory.
16714     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16715       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16716                                    StoreType, ShuffWide,
16717                                    DAG.getIntPtrConstant(i));
16718       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16719                                 St->getPointerInfo(), St->isVolatile(),
16720                                 St->isNonTemporal(), St->getAlignment());
16721       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16722       Chains.push_back(Ch);
16723     }
16724
16725     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16726                                Chains.size());
16727   }
16728
16729   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16730   // the FP state in cases where an emms may be missing.
16731   // A preferable solution to the general problem is to figure out the right
16732   // places to insert EMMS.  This qualifies as a quick hack.
16733
16734   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16735   if (VT.getSizeInBits() != 64)
16736     return SDValue();
16737
16738   const Function *F = DAG.getMachineFunction().getFunction();
16739   bool NoImplicitFloatOps = F->getAttributes().
16740     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16741   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16742                      && Subtarget->hasSSE2();
16743   if ((VT.isVector() ||
16744        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16745       isa<LoadSDNode>(St->getValue()) &&
16746       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16747       St->getChain().hasOneUse() && !St->isVolatile()) {
16748     SDNode* LdVal = St->getValue().getNode();
16749     LoadSDNode *Ld = 0;
16750     int TokenFactorIndex = -1;
16751     SmallVector<SDValue, 8> Ops;
16752     SDNode* ChainVal = St->getChain().getNode();
16753     // Must be a store of a load.  We currently handle two cases:  the load
16754     // is a direct child, and it's under an intervening TokenFactor.  It is
16755     // possible to dig deeper under nested TokenFactors.
16756     if (ChainVal == LdVal)
16757       Ld = cast<LoadSDNode>(St->getChain());
16758     else if (St->getValue().hasOneUse() &&
16759              ChainVal->getOpcode() == ISD::TokenFactor) {
16760       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16761         if (ChainVal->getOperand(i).getNode() == LdVal) {
16762           TokenFactorIndex = i;
16763           Ld = cast<LoadSDNode>(St->getValue());
16764         } else
16765           Ops.push_back(ChainVal->getOperand(i));
16766       }
16767     }
16768
16769     if (!Ld || !ISD::isNormalLoad(Ld))
16770       return SDValue();
16771
16772     // If this is not the MMX case, i.e. we are just turning i64 load/store
16773     // into f64 load/store, avoid the transformation if there are multiple
16774     // uses of the loaded value.
16775     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16776       return SDValue();
16777
16778     DebugLoc LdDL = Ld->getDebugLoc();
16779     DebugLoc StDL = N->getDebugLoc();
16780     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16781     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16782     // pair instead.
16783     if (Subtarget->is64Bit() || F64IsLegal) {
16784       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16785       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16786                                   Ld->getPointerInfo(), Ld->isVolatile(),
16787                                   Ld->isNonTemporal(), Ld->isInvariant(),
16788                                   Ld->getAlignment());
16789       SDValue NewChain = NewLd.getValue(1);
16790       if (TokenFactorIndex != -1) {
16791         Ops.push_back(NewChain);
16792         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16793                                Ops.size());
16794       }
16795       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16796                           St->getPointerInfo(),
16797                           St->isVolatile(), St->isNonTemporal(),
16798                           St->getAlignment());
16799     }
16800
16801     // Otherwise, lower to two pairs of 32-bit loads / stores.
16802     SDValue LoAddr = Ld->getBasePtr();
16803     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16804                                  DAG.getConstant(4, MVT::i32));
16805
16806     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16807                                Ld->getPointerInfo(),
16808                                Ld->isVolatile(), Ld->isNonTemporal(),
16809                                Ld->isInvariant(), Ld->getAlignment());
16810     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16811                                Ld->getPointerInfo().getWithOffset(4),
16812                                Ld->isVolatile(), Ld->isNonTemporal(),
16813                                Ld->isInvariant(),
16814                                MinAlign(Ld->getAlignment(), 4));
16815
16816     SDValue NewChain = LoLd.getValue(1);
16817     if (TokenFactorIndex != -1) {
16818       Ops.push_back(LoLd);
16819       Ops.push_back(HiLd);
16820       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16821                              Ops.size());
16822     }
16823
16824     LoAddr = St->getBasePtr();
16825     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16826                          DAG.getConstant(4, MVT::i32));
16827
16828     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16829                                 St->getPointerInfo(),
16830                                 St->isVolatile(), St->isNonTemporal(),
16831                                 St->getAlignment());
16832     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16833                                 St->getPointerInfo().getWithOffset(4),
16834                                 St->isVolatile(),
16835                                 St->isNonTemporal(),
16836                                 MinAlign(St->getAlignment(), 4));
16837     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16838   }
16839   return SDValue();
16840 }
16841
16842 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16843 /// and return the operands for the horizontal operation in LHS and RHS.  A
16844 /// horizontal operation performs the binary operation on successive elements
16845 /// of its first operand, then on successive elements of its second operand,
16846 /// returning the resulting values in a vector.  For example, if
16847 ///   A = < float a0, float a1, float a2, float a3 >
16848 /// and
16849 ///   B = < float b0, float b1, float b2, float b3 >
16850 /// then the result of doing a horizontal operation on A and B is
16851 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16852 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16853 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16854 /// set to A, RHS to B, and the routine returns 'true'.
16855 /// Note that the binary operation should have the property that if one of the
16856 /// operands is UNDEF then the result is UNDEF.
16857 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16858   // Look for the following pattern: if
16859   //   A = < float a0, float a1, float a2, float a3 >
16860   //   B = < float b0, float b1, float b2, float b3 >
16861   // and
16862   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16863   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16864   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16865   // which is A horizontal-op B.
16866
16867   // At least one of the operands should be a vector shuffle.
16868   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16869       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16870     return false;
16871
16872   EVT VT = LHS.getValueType();
16873
16874   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16875          "Unsupported vector type for horizontal add/sub");
16876
16877   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16878   // operate independently on 128-bit lanes.
16879   unsigned NumElts = VT.getVectorNumElements();
16880   unsigned NumLanes = VT.getSizeInBits()/128;
16881   unsigned NumLaneElts = NumElts / NumLanes;
16882   assert((NumLaneElts % 2 == 0) &&
16883          "Vector type should have an even number of elements in each lane");
16884   unsigned HalfLaneElts = NumLaneElts/2;
16885
16886   // View LHS in the form
16887   //   LHS = VECTOR_SHUFFLE A, B, LMask
16888   // If LHS is not a shuffle then pretend it is the shuffle
16889   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16890   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16891   // type VT.
16892   SDValue A, B;
16893   SmallVector<int, 16> LMask(NumElts);
16894   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16895     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16896       A = LHS.getOperand(0);
16897     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16898       B = LHS.getOperand(1);
16899     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16900     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16901   } else {
16902     if (LHS.getOpcode() != ISD::UNDEF)
16903       A = LHS;
16904     for (unsigned i = 0; i != NumElts; ++i)
16905       LMask[i] = i;
16906   }
16907
16908   // Likewise, view RHS in the form
16909   //   RHS = VECTOR_SHUFFLE C, D, RMask
16910   SDValue C, D;
16911   SmallVector<int, 16> RMask(NumElts);
16912   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16913     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16914       C = RHS.getOperand(0);
16915     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16916       D = RHS.getOperand(1);
16917     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16918     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16919   } else {
16920     if (RHS.getOpcode() != ISD::UNDEF)
16921       C = RHS;
16922     for (unsigned i = 0; i != NumElts; ++i)
16923       RMask[i] = i;
16924   }
16925
16926   // Check that the shuffles are both shuffling the same vectors.
16927   if (!(A == C && B == D) && !(A == D && B == C))
16928     return false;
16929
16930   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16931   if (!A.getNode() && !B.getNode())
16932     return false;
16933
16934   // If A and B occur in reverse order in RHS, then "swap" them (which means
16935   // rewriting the mask).
16936   if (A != C)
16937     CommuteVectorShuffleMask(RMask, NumElts);
16938
16939   // At this point LHS and RHS are equivalent to
16940   //   LHS = VECTOR_SHUFFLE A, B, LMask
16941   //   RHS = VECTOR_SHUFFLE A, B, RMask
16942   // Check that the masks correspond to performing a horizontal operation.
16943   for (unsigned i = 0; i != NumElts; ++i) {
16944     int LIdx = LMask[i], RIdx = RMask[i];
16945
16946     // Ignore any UNDEF components.
16947     if (LIdx < 0 || RIdx < 0 ||
16948         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16949         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16950       continue;
16951
16952     // Check that successive elements are being operated on.  If not, this is
16953     // not a horizontal operation.
16954     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16955     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16956     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16957     if (!(LIdx == Index && RIdx == Index + 1) &&
16958         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16959       return false;
16960   }
16961
16962   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16963   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16964   return true;
16965 }
16966
16967 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16968 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16969                                   const X86Subtarget *Subtarget) {
16970   EVT VT = N->getValueType(0);
16971   SDValue LHS = N->getOperand(0);
16972   SDValue RHS = N->getOperand(1);
16973
16974   // Try to synthesize horizontal adds from adds of shuffles.
16975   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16976        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16977       isHorizontalBinOp(LHS, RHS, true))
16978     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16979   return SDValue();
16980 }
16981
16982 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16983 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16984                                   const X86Subtarget *Subtarget) {
16985   EVT VT = N->getValueType(0);
16986   SDValue LHS = N->getOperand(0);
16987   SDValue RHS = N->getOperand(1);
16988
16989   // Try to synthesize horizontal subs from subs of shuffles.
16990   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16991        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16992       isHorizontalBinOp(LHS, RHS, false))
16993     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16994   return SDValue();
16995 }
16996
16997 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16998 /// X86ISD::FXOR nodes.
16999 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17000   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17001   // F[X]OR(0.0, x) -> x
17002   // F[X]OR(x, 0.0) -> x
17003   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17004     if (C->getValueAPF().isPosZero())
17005       return N->getOperand(1);
17006   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17007     if (C->getValueAPF().isPosZero())
17008       return N->getOperand(0);
17009   return SDValue();
17010 }
17011
17012 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17013 /// X86ISD::FMAX nodes.
17014 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17015   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17016
17017   // Only perform optimizations if UnsafeMath is used.
17018   if (!DAG.getTarget().Options.UnsafeFPMath)
17019     return SDValue();
17020
17021   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17022   // into FMINC and FMAXC, which are Commutative operations.
17023   unsigned NewOp = 0;
17024   switch (N->getOpcode()) {
17025     default: llvm_unreachable("unknown opcode");
17026     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17027     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17028   }
17029
17030   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17031                      N->getOperand(0), N->getOperand(1));
17032 }
17033
17034 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17035 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17036   // FAND(0.0, x) -> 0.0
17037   // FAND(x, 0.0) -> 0.0
17038   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17039     if (C->getValueAPF().isPosZero())
17040       return N->getOperand(0);
17041   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17042     if (C->getValueAPF().isPosZero())
17043       return N->getOperand(1);
17044   return SDValue();
17045 }
17046
17047 static SDValue PerformBTCombine(SDNode *N,
17048                                 SelectionDAG &DAG,
17049                                 TargetLowering::DAGCombinerInfo &DCI) {
17050   // BT ignores high bits in the bit index operand.
17051   SDValue Op1 = N->getOperand(1);
17052   if (Op1.hasOneUse()) {
17053     unsigned BitWidth = Op1.getValueSizeInBits();
17054     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17055     APInt KnownZero, KnownOne;
17056     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17057                                           !DCI.isBeforeLegalizeOps());
17058     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17059     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17060         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17061       DCI.CommitTargetLoweringOpt(TLO);
17062   }
17063   return SDValue();
17064 }
17065
17066 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17067   SDValue Op = N->getOperand(0);
17068   if (Op.getOpcode() == ISD::BITCAST)
17069     Op = Op.getOperand(0);
17070   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17071   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17072       VT.getVectorElementType().getSizeInBits() ==
17073       OpVT.getVectorElementType().getSizeInBits()) {
17074     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17075   }
17076   return SDValue();
17077 }
17078
17079 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17080                                   TargetLowering::DAGCombinerInfo &DCI,
17081                                   const X86Subtarget *Subtarget) {
17082   if (!DCI.isBeforeLegalizeOps())
17083     return SDValue();
17084
17085   if (!Subtarget->hasFp256())
17086     return SDValue();
17087
17088   EVT VT = N->getValueType(0);
17089   if (VT.isVector() && VT.getSizeInBits() == 256) {
17090     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17091     if (R.getNode())
17092       return R;
17093   }
17094
17095   return SDValue();
17096 }
17097
17098 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17099                                  const X86Subtarget* Subtarget) {
17100   DebugLoc dl = N->getDebugLoc();
17101   EVT VT = N->getValueType(0);
17102
17103   // Let legalize expand this if it isn't a legal type yet.
17104   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17105     return SDValue();
17106
17107   EVT ScalarVT = VT.getScalarType();
17108   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17109       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17110     return SDValue();
17111
17112   SDValue A = N->getOperand(0);
17113   SDValue B = N->getOperand(1);
17114   SDValue C = N->getOperand(2);
17115
17116   bool NegA = (A.getOpcode() == ISD::FNEG);
17117   bool NegB = (B.getOpcode() == ISD::FNEG);
17118   bool NegC = (C.getOpcode() == ISD::FNEG);
17119
17120   // Negative multiplication when NegA xor NegB
17121   bool NegMul = (NegA != NegB);
17122   if (NegA)
17123     A = A.getOperand(0);
17124   if (NegB)
17125     B = B.getOperand(0);
17126   if (NegC)
17127     C = C.getOperand(0);
17128
17129   unsigned Opcode;
17130   if (!NegMul)
17131     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17132   else
17133     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17134
17135   return DAG.getNode(Opcode, dl, VT, A, B, C);
17136 }
17137
17138 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17139                                   TargetLowering::DAGCombinerInfo &DCI,
17140                                   const X86Subtarget *Subtarget) {
17141   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17142   //           (and (i32 x86isd::setcc_carry), 1)
17143   // This eliminates the zext. This transformation is necessary because
17144   // ISD::SETCC is always legalized to i8.
17145   DebugLoc dl = N->getDebugLoc();
17146   SDValue N0 = N->getOperand(0);
17147   EVT VT = N->getValueType(0);
17148
17149   if (N0.getOpcode() == ISD::AND &&
17150       N0.hasOneUse() &&
17151       N0.getOperand(0).hasOneUse()) {
17152     SDValue N00 = N0.getOperand(0);
17153     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17154       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17155       if (!C || C->getZExtValue() != 1)
17156         return SDValue();
17157       return DAG.getNode(ISD::AND, dl, VT,
17158                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17159                                      N00.getOperand(0), N00.getOperand(1)),
17160                          DAG.getConstant(1, VT));
17161     }
17162   }
17163
17164   if (VT.is256BitVector()) {
17165     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17166     if (R.getNode())
17167       return R;
17168   }
17169
17170   return SDValue();
17171 }
17172
17173 // Optimize x == -y --> x+y == 0
17174 //          x != -y --> x+y != 0
17175 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17176   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17177   SDValue LHS = N->getOperand(0);
17178   SDValue RHS = N->getOperand(1);
17179
17180   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17181     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17182       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17183         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17184                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17185         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17186                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17187       }
17188   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17189     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17190       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17191         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17192                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17193         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17194                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17195       }
17196   return SDValue();
17197 }
17198
17199 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
17200 // as "sbb reg,reg", since it can be extended without zext and produces 
17201 // an all-ones bit which is more useful than 0/1 in some cases.
17202 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17203   return DAG.getNode(ISD::AND, DL, MVT::i8,
17204                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17205                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17206                      DAG.getConstant(1, MVT::i8));
17207 }
17208
17209 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17210 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17211                                    TargetLowering::DAGCombinerInfo &DCI,
17212                                    const X86Subtarget *Subtarget) {
17213   DebugLoc DL = N->getDebugLoc();
17214   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17215   SDValue EFLAGS = N->getOperand(1);
17216
17217   if (CC == X86::COND_A) {
17218     // Try to convert COND_A into COND_B in an attempt to facilitate 
17219     // materializing "setb reg".
17220     //
17221     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17222     // cannot take an immediate as its first operand.
17223     //
17224     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
17225         EFLAGS.getValueType().isInteger() &&
17226         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17227       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17228                                    EFLAGS.getNode()->getVTList(),
17229                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17230       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17231       return MaterializeSETB(DL, NewEFLAGS, DAG);
17232     }
17233   }
17234
17235   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17236   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17237   // cases.
17238   if (CC == X86::COND_B)
17239     return MaterializeSETB(DL, EFLAGS, DAG);
17240
17241   SDValue Flags;
17242
17243   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17244   if (Flags.getNode()) {
17245     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17246     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17247   }
17248
17249   return SDValue();
17250 }
17251
17252 // Optimize branch condition evaluation.
17253 //
17254 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17255                                     TargetLowering::DAGCombinerInfo &DCI,
17256                                     const X86Subtarget *Subtarget) {
17257   DebugLoc DL = N->getDebugLoc();
17258   SDValue Chain = N->getOperand(0);
17259   SDValue Dest = N->getOperand(1);
17260   SDValue EFLAGS = N->getOperand(3);
17261   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17262
17263   SDValue Flags;
17264
17265   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17266   if (Flags.getNode()) {
17267     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17268     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17269                        Flags);
17270   }
17271
17272   return SDValue();
17273 }
17274
17275 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17276                                         const X86TargetLowering *XTLI) {
17277   SDValue Op0 = N->getOperand(0);
17278   EVT InVT = Op0->getValueType(0);
17279
17280   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17281   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17282     DebugLoc dl = N->getDebugLoc();
17283     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17284     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17285     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17286   }
17287
17288   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17289   // a 32-bit target where SSE doesn't support i64->FP operations.
17290   if (Op0.getOpcode() == ISD::LOAD) {
17291     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17292     EVT VT = Ld->getValueType(0);
17293     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17294         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17295         !XTLI->getSubtarget()->is64Bit() &&
17296         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17297       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17298                                           Ld->getChain(), Op0, DAG);
17299       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17300       return FILDChain;
17301     }
17302   }
17303   return SDValue();
17304 }
17305
17306 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17307 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17308                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17309   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17310   // the result is either zero or one (depending on the input carry bit).
17311   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17312   if (X86::isZeroNode(N->getOperand(0)) &&
17313       X86::isZeroNode(N->getOperand(1)) &&
17314       // We don't have a good way to replace an EFLAGS use, so only do this when
17315       // dead right now.
17316       SDValue(N, 1).use_empty()) {
17317     DebugLoc DL = N->getDebugLoc();
17318     EVT VT = N->getValueType(0);
17319     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17320     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17321                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17322                                            DAG.getConstant(X86::COND_B,MVT::i8),
17323                                            N->getOperand(2)),
17324                                DAG.getConstant(1, VT));
17325     return DCI.CombineTo(N, Res1, CarryOut);
17326   }
17327
17328   return SDValue();
17329 }
17330
17331 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17332 //      (add Y, (setne X, 0)) -> sbb -1, Y
17333 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17334 //      (sub (setne X, 0), Y) -> adc -1, Y
17335 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17336   DebugLoc DL = N->getDebugLoc();
17337
17338   // Look through ZExts.
17339   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17340   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17341     return SDValue();
17342
17343   SDValue SetCC = Ext.getOperand(0);
17344   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17345     return SDValue();
17346
17347   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17348   if (CC != X86::COND_E && CC != X86::COND_NE)
17349     return SDValue();
17350
17351   SDValue Cmp = SetCC.getOperand(1);
17352   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17353       !X86::isZeroNode(Cmp.getOperand(1)) ||
17354       !Cmp.getOperand(0).getValueType().isInteger())
17355     return SDValue();
17356
17357   SDValue CmpOp0 = Cmp.getOperand(0);
17358   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17359                                DAG.getConstant(1, CmpOp0.getValueType()));
17360
17361   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17362   if (CC == X86::COND_NE)
17363     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17364                        DL, OtherVal.getValueType(), OtherVal,
17365                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17366   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17367                      DL, OtherVal.getValueType(), OtherVal,
17368                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17369 }
17370
17371 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17372 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17373                                  const X86Subtarget *Subtarget) {
17374   EVT VT = N->getValueType(0);
17375   SDValue Op0 = N->getOperand(0);
17376   SDValue Op1 = N->getOperand(1);
17377
17378   // Try to synthesize horizontal adds from adds of shuffles.
17379   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17380        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17381       isHorizontalBinOp(Op0, Op1, true))
17382     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17383
17384   return OptimizeConditionalInDecrement(N, DAG);
17385 }
17386
17387 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17388                                  const X86Subtarget *Subtarget) {
17389   SDValue Op0 = N->getOperand(0);
17390   SDValue Op1 = N->getOperand(1);
17391
17392   // X86 can't encode an immediate LHS of a sub. See if we can push the
17393   // negation into a preceding instruction.
17394   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17395     // If the RHS of the sub is a XOR with one use and a constant, invert the
17396     // immediate. Then add one to the LHS of the sub so we can turn
17397     // X-Y -> X+~Y+1, saving one register.
17398     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17399         isa<ConstantSDNode>(Op1.getOperand(1))) {
17400       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17401       EVT VT = Op0.getValueType();
17402       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17403                                    Op1.getOperand(0),
17404                                    DAG.getConstant(~XorC, VT));
17405       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17406                          DAG.getConstant(C->getAPIntValue()+1, VT));
17407     }
17408   }
17409
17410   // Try to synthesize horizontal adds from adds of shuffles.
17411   EVT VT = N->getValueType(0);
17412   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17413        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17414       isHorizontalBinOp(Op0, Op1, true))
17415     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17416
17417   return OptimizeConditionalInDecrement(N, DAG);
17418 }
17419
17420 /// performVZEXTCombine - Performs build vector combines
17421 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17422                                         TargetLowering::DAGCombinerInfo &DCI,
17423                                         const X86Subtarget *Subtarget) {
17424   // (vzext (bitcast (vzext (x)) -> (vzext x)
17425   SDValue In = N->getOperand(0);
17426   while (In.getOpcode() == ISD::BITCAST)
17427     In = In.getOperand(0);
17428
17429   if (In.getOpcode() != X86ISD::VZEXT)
17430     return SDValue();
17431
17432   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17433 }
17434
17435 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17436                                              DAGCombinerInfo &DCI) const {
17437   SelectionDAG &DAG = DCI.DAG;
17438   switch (N->getOpcode()) {
17439   default: break;
17440   case ISD::EXTRACT_VECTOR_ELT:
17441     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17442   case ISD::VSELECT:
17443   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17444   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17445   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17446   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17447   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17448   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17449   case ISD::SHL:
17450   case ISD::SRA:
17451   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17452   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17453   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17454   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17455   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17456   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17457   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17458   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17459   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17460   case X86ISD::FXOR:
17461   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17462   case X86ISD::FMIN:
17463   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17464   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17465   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17466   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17467   case ISD::ANY_EXTEND:
17468   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17469   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17470   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17471   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17472   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17473   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17474   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17475   case X86ISD::SHUFP:       // Handle all target specific shuffles
17476   case X86ISD::PALIGNR:
17477   case X86ISD::UNPCKH:
17478   case X86ISD::UNPCKL:
17479   case X86ISD::MOVHLPS:
17480   case X86ISD::MOVLHPS:
17481   case X86ISD::PSHUFD:
17482   case X86ISD::PSHUFHW:
17483   case X86ISD::PSHUFLW:
17484   case X86ISD::MOVSS:
17485   case X86ISD::MOVSD:
17486   case X86ISD::VPERMILP:
17487   case X86ISD::VPERM2X128:
17488   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17489   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17490   }
17491
17492   return SDValue();
17493 }
17494
17495 /// isTypeDesirableForOp - Return true if the target has native support for
17496 /// the specified value type and it is 'desirable' to use the type for the
17497 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17498 /// instruction encodings are longer and some i16 instructions are slow.
17499 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17500   if (!isTypeLegal(VT))
17501     return false;
17502   if (VT != MVT::i16)
17503     return true;
17504
17505   switch (Opc) {
17506   default:
17507     return true;
17508   case ISD::LOAD:
17509   case ISD::SIGN_EXTEND:
17510   case ISD::ZERO_EXTEND:
17511   case ISD::ANY_EXTEND:
17512   case ISD::SHL:
17513   case ISD::SRL:
17514   case ISD::SUB:
17515   case ISD::ADD:
17516   case ISD::MUL:
17517   case ISD::AND:
17518   case ISD::OR:
17519   case ISD::XOR:
17520     return false;
17521   }
17522 }
17523
17524 /// IsDesirableToPromoteOp - This method query the target whether it is
17525 /// beneficial for dag combiner to promote the specified node. If true, it
17526 /// should return the desired promotion type by reference.
17527 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17528   EVT VT = Op.getValueType();
17529   if (VT != MVT::i16)
17530     return false;
17531
17532   bool Promote = false;
17533   bool Commute = false;
17534   switch (Op.getOpcode()) {
17535   default: break;
17536   case ISD::LOAD: {
17537     LoadSDNode *LD = cast<LoadSDNode>(Op);
17538     // If the non-extending load has a single use and it's not live out, then it
17539     // might be folded.
17540     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17541                                                      Op.hasOneUse()*/) {
17542       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17543              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17544         // The only case where we'd want to promote LOAD (rather then it being
17545         // promoted as an operand is when it's only use is liveout.
17546         if (UI->getOpcode() != ISD::CopyToReg)
17547           return false;
17548       }
17549     }
17550     Promote = true;
17551     break;
17552   }
17553   case ISD::SIGN_EXTEND:
17554   case ISD::ZERO_EXTEND:
17555   case ISD::ANY_EXTEND:
17556     Promote = true;
17557     break;
17558   case ISD::SHL:
17559   case ISD::SRL: {
17560     SDValue N0 = Op.getOperand(0);
17561     // Look out for (store (shl (load), x)).
17562     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17563       return false;
17564     Promote = true;
17565     break;
17566   }
17567   case ISD::ADD:
17568   case ISD::MUL:
17569   case ISD::AND:
17570   case ISD::OR:
17571   case ISD::XOR:
17572     Commute = true;
17573     // fallthrough
17574   case ISD::SUB: {
17575     SDValue N0 = Op.getOperand(0);
17576     SDValue N1 = Op.getOperand(1);
17577     if (!Commute && MayFoldLoad(N1))
17578       return false;
17579     // Avoid disabling potential load folding opportunities.
17580     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17581       return false;
17582     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17583       return false;
17584     Promote = true;
17585   }
17586   }
17587
17588   PVT = MVT::i32;
17589   return Promote;
17590 }
17591
17592 //===----------------------------------------------------------------------===//
17593 //                           X86 Inline Assembly Support
17594 //===----------------------------------------------------------------------===//
17595
17596 namespace {
17597   // Helper to match a string separated by whitespace.
17598   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17599     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17600
17601     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17602       StringRef piece(*args[i]);
17603       if (!s.startswith(piece)) // Check if the piece matches.
17604         return false;
17605
17606       s = s.substr(piece.size());
17607       StringRef::size_type pos = s.find_first_not_of(" \t");
17608       if (pos == 0) // We matched a prefix.
17609         return false;
17610
17611       s = s.substr(pos);
17612     }
17613
17614     return s.empty();
17615   }
17616   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17617 }
17618
17619 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17620   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17621
17622   std::string AsmStr = IA->getAsmString();
17623
17624   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17625   if (!Ty || Ty->getBitWidth() % 16 != 0)
17626     return false;
17627
17628   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17629   SmallVector<StringRef, 4> AsmPieces;
17630   SplitString(AsmStr, AsmPieces, ";\n");
17631
17632   switch (AsmPieces.size()) {
17633   default: return false;
17634   case 1:
17635     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17636     // we will turn this bswap into something that will be lowered to logical
17637     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17638     // lower so don't worry about this.
17639     // bswap $0
17640     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17641         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17642         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17643         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17644         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17645         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17646       // No need to check constraints, nothing other than the equivalent of
17647       // "=r,0" would be valid here.
17648       return IntrinsicLowering::LowerToByteSwap(CI);
17649     }
17650
17651     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17652     if (CI->getType()->isIntegerTy(16) &&
17653         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17654         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17655          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17656       AsmPieces.clear();
17657       const std::string &ConstraintsStr = IA->getConstraintString();
17658       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17659       std::sort(AsmPieces.begin(), AsmPieces.end());
17660       if (AsmPieces.size() == 4 &&
17661           AsmPieces[0] == "~{cc}" &&
17662           AsmPieces[1] == "~{dirflag}" &&
17663           AsmPieces[2] == "~{flags}" &&
17664           AsmPieces[3] == "~{fpsr}")
17665       return IntrinsicLowering::LowerToByteSwap(CI);
17666     }
17667     break;
17668   case 3:
17669     if (CI->getType()->isIntegerTy(32) &&
17670         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17671         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17672         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17673         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17674       AsmPieces.clear();
17675       const std::string &ConstraintsStr = IA->getConstraintString();
17676       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17677       std::sort(AsmPieces.begin(), AsmPieces.end());
17678       if (AsmPieces.size() == 4 &&
17679           AsmPieces[0] == "~{cc}" &&
17680           AsmPieces[1] == "~{dirflag}" &&
17681           AsmPieces[2] == "~{flags}" &&
17682           AsmPieces[3] == "~{fpsr}")
17683         return IntrinsicLowering::LowerToByteSwap(CI);
17684     }
17685
17686     if (CI->getType()->isIntegerTy(64)) {
17687       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17688       if (Constraints.size() >= 2 &&
17689           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17690           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17691         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17692         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17693             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17694             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17695           return IntrinsicLowering::LowerToByteSwap(CI);
17696       }
17697     }
17698     break;
17699   }
17700   return false;
17701 }
17702
17703 /// getConstraintType - Given a constraint letter, return the type of
17704 /// constraint it is for this target.
17705 X86TargetLowering::ConstraintType
17706 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17707   if (Constraint.size() == 1) {
17708     switch (Constraint[0]) {
17709     case 'R':
17710     case 'q':
17711     case 'Q':
17712     case 'f':
17713     case 't':
17714     case 'u':
17715     case 'y':
17716     case 'x':
17717     case 'Y':
17718     case 'l':
17719       return C_RegisterClass;
17720     case 'a':
17721     case 'b':
17722     case 'c':
17723     case 'd':
17724     case 'S':
17725     case 'D':
17726     case 'A':
17727       return C_Register;
17728     case 'I':
17729     case 'J':
17730     case 'K':
17731     case 'L':
17732     case 'M':
17733     case 'N':
17734     case 'G':
17735     case 'C':
17736     case 'e':
17737     case 'Z':
17738       return C_Other;
17739     default:
17740       break;
17741     }
17742   }
17743   return TargetLowering::getConstraintType(Constraint);
17744 }
17745
17746 /// Examine constraint type and operand type and determine a weight value.
17747 /// This object must already have been set up with the operand type
17748 /// and the current alternative constraint selected.
17749 TargetLowering::ConstraintWeight
17750   X86TargetLowering::getSingleConstraintMatchWeight(
17751     AsmOperandInfo &info, const char *constraint) const {
17752   ConstraintWeight weight = CW_Invalid;
17753   Value *CallOperandVal = info.CallOperandVal;
17754     // If we don't have a value, we can't do a match,
17755     // but allow it at the lowest weight.
17756   if (CallOperandVal == NULL)
17757     return CW_Default;
17758   Type *type = CallOperandVal->getType();
17759   // Look at the constraint type.
17760   switch (*constraint) {
17761   default:
17762     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17763   case 'R':
17764   case 'q':
17765   case 'Q':
17766   case 'a':
17767   case 'b':
17768   case 'c':
17769   case 'd':
17770   case 'S':
17771   case 'D':
17772   case 'A':
17773     if (CallOperandVal->getType()->isIntegerTy())
17774       weight = CW_SpecificReg;
17775     break;
17776   case 'f':
17777   case 't':
17778   case 'u':
17779     if (type->isFloatingPointTy())
17780       weight = CW_SpecificReg;
17781     break;
17782   case 'y':
17783     if (type->isX86_MMXTy() && Subtarget->hasMMX())
17784       weight = CW_SpecificReg;
17785     break;
17786   case 'x':
17787   case 'Y':
17788     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17789         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17790       weight = CW_Register;
17791     break;
17792   case 'I':
17793     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17794       if (C->getZExtValue() <= 31)
17795         weight = CW_Constant;
17796     }
17797     break;
17798   case 'J':
17799     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17800       if (C->getZExtValue() <= 63)
17801         weight = CW_Constant;
17802     }
17803     break;
17804   case 'K':
17805     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17806       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17807         weight = CW_Constant;
17808     }
17809     break;
17810   case 'L':
17811     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17812       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17813         weight = CW_Constant;
17814     }
17815     break;
17816   case 'M':
17817     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17818       if (C->getZExtValue() <= 3)
17819         weight = CW_Constant;
17820     }
17821     break;
17822   case 'N':
17823     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17824       if (C->getZExtValue() <= 0xff)
17825         weight = CW_Constant;
17826     }
17827     break;
17828   case 'G':
17829   case 'C':
17830     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17831       weight = CW_Constant;
17832     }
17833     break;
17834   case 'e':
17835     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17836       if ((C->getSExtValue() >= -0x80000000LL) &&
17837           (C->getSExtValue() <= 0x7fffffffLL))
17838         weight = CW_Constant;
17839     }
17840     break;
17841   case 'Z':
17842     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17843       if (C->getZExtValue() <= 0xffffffff)
17844         weight = CW_Constant;
17845     }
17846     break;
17847   }
17848   return weight;
17849 }
17850
17851 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17852 /// with another that has more specific requirements based on the type of the
17853 /// corresponding operand.
17854 const char *X86TargetLowering::
17855 LowerXConstraint(EVT ConstraintVT) const {
17856   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17857   // 'f' like normal targets.
17858   if (ConstraintVT.isFloatingPoint()) {
17859     if (Subtarget->hasSSE2())
17860       return "Y";
17861     if (Subtarget->hasSSE1())
17862       return "x";
17863   }
17864
17865   return TargetLowering::LowerXConstraint(ConstraintVT);
17866 }
17867
17868 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17869 /// vector.  If it is invalid, don't add anything to Ops.
17870 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17871                                                      std::string &Constraint,
17872                                                      std::vector<SDValue>&Ops,
17873                                                      SelectionDAG &DAG) const {
17874   SDValue Result(0, 0);
17875
17876   // Only support length 1 constraints for now.
17877   if (Constraint.length() > 1) return;
17878
17879   char ConstraintLetter = Constraint[0];
17880   switch (ConstraintLetter) {
17881   default: break;
17882   case 'I':
17883     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17884       if (C->getZExtValue() <= 31) {
17885         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17886         break;
17887       }
17888     }
17889     return;
17890   case 'J':
17891     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17892       if (C->getZExtValue() <= 63) {
17893         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17894         break;
17895       }
17896     }
17897     return;
17898   case 'K':
17899     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17900       if (isInt<8>(C->getSExtValue())) {
17901         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17902         break;
17903       }
17904     }
17905     return;
17906   case 'N':
17907     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17908       if (C->getZExtValue() <= 255) {
17909         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17910         break;
17911       }
17912     }
17913     return;
17914   case 'e': {
17915     // 32-bit signed value
17916     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17917       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17918                                            C->getSExtValue())) {
17919         // Widen to 64 bits here to get it sign extended.
17920         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17921         break;
17922       }
17923     // FIXME gcc accepts some relocatable values here too, but only in certain
17924     // memory models; it's complicated.
17925     }
17926     return;
17927   }
17928   case 'Z': {
17929     // 32-bit unsigned value
17930     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17931       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17932                                            C->getZExtValue())) {
17933         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17934         break;
17935       }
17936     }
17937     // FIXME gcc accepts some relocatable values here too, but only in certain
17938     // memory models; it's complicated.
17939     return;
17940   }
17941   case 'i': {
17942     // Literal immediates are always ok.
17943     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17944       // Widen to 64 bits here to get it sign extended.
17945       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17946       break;
17947     }
17948
17949     // In any sort of PIC mode addresses need to be computed at runtime by
17950     // adding in a register or some sort of table lookup.  These can't
17951     // be used as immediates.
17952     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17953       return;
17954
17955     // If we are in non-pic codegen mode, we allow the address of a global (with
17956     // an optional displacement) to be used with 'i'.
17957     GlobalAddressSDNode *GA = 0;
17958     int64_t Offset = 0;
17959
17960     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17961     while (1) {
17962       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17963         Offset += GA->getOffset();
17964         break;
17965       } else if (Op.getOpcode() == ISD::ADD) {
17966         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17967           Offset += C->getZExtValue();
17968           Op = Op.getOperand(0);
17969           continue;
17970         }
17971       } else if (Op.getOpcode() == ISD::SUB) {
17972         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17973           Offset += -C->getZExtValue();
17974           Op = Op.getOperand(0);
17975           continue;
17976         }
17977       }
17978
17979       // Otherwise, this isn't something we can handle, reject it.
17980       return;
17981     }
17982
17983     const GlobalValue *GV = GA->getGlobal();
17984     // If we require an extra load to get this address, as in PIC mode, we
17985     // can't accept it.
17986     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17987                                                         getTargetMachine())))
17988       return;
17989
17990     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17991                                         GA->getValueType(0), Offset);
17992     break;
17993   }
17994   }
17995
17996   if (Result.getNode()) {
17997     Ops.push_back(Result);
17998     return;
17999   }
18000   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18001 }
18002
18003 std::pair<unsigned, const TargetRegisterClass*>
18004 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18005                                                 EVT VT) const {
18006   // First, see if this is a constraint that directly corresponds to an LLVM
18007   // register class.
18008   if (Constraint.size() == 1) {
18009     // GCC Constraint Letters
18010     switch (Constraint[0]) {
18011     default: break;
18012       // TODO: Slight differences here in allocation order and leaving
18013       // RIP in the class. Do they matter any more here than they do
18014       // in the normal allocation?
18015     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18016       if (Subtarget->is64Bit()) {
18017         if (VT == MVT::i32 || VT == MVT::f32)
18018           return std::make_pair(0U, &X86::GR32RegClass);
18019         if (VT == MVT::i16)
18020           return std::make_pair(0U, &X86::GR16RegClass);
18021         if (VT == MVT::i8 || VT == MVT::i1)
18022           return std::make_pair(0U, &X86::GR8RegClass);
18023         if (VT == MVT::i64 || VT == MVT::f64)
18024           return std::make_pair(0U, &X86::GR64RegClass);
18025         break;
18026       }
18027       // 32-bit fallthrough
18028     case 'Q':   // Q_REGS
18029       if (VT == MVT::i32 || VT == MVT::f32)
18030         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18031       if (VT == MVT::i16)
18032         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18033       if (VT == MVT::i8 || VT == MVT::i1)
18034         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18035       if (VT == MVT::i64)
18036         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18037       break;
18038     case 'r':   // GENERAL_REGS
18039     case 'l':   // INDEX_REGS
18040       if (VT == MVT::i8 || VT == MVT::i1)
18041         return std::make_pair(0U, &X86::GR8RegClass);
18042       if (VT == MVT::i16)
18043         return std::make_pair(0U, &X86::GR16RegClass);
18044       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18045         return std::make_pair(0U, &X86::GR32RegClass);
18046       return std::make_pair(0U, &X86::GR64RegClass);
18047     case 'R':   // LEGACY_REGS
18048       if (VT == MVT::i8 || VT == MVT::i1)
18049         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18050       if (VT == MVT::i16)
18051         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18052       if (VT == MVT::i32 || !Subtarget->is64Bit())
18053         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18054       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18055     case 'f':  // FP Stack registers.
18056       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18057       // value to the correct fpstack register class.
18058       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18059         return std::make_pair(0U, &X86::RFP32RegClass);
18060       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18061         return std::make_pair(0U, &X86::RFP64RegClass);
18062       return std::make_pair(0U, &X86::RFP80RegClass);
18063     case 'y':   // MMX_REGS if MMX allowed.
18064       if (!Subtarget->hasMMX()) break;
18065       return std::make_pair(0U, &X86::VR64RegClass);
18066     case 'Y':   // SSE_REGS if SSE2 allowed
18067       if (!Subtarget->hasSSE2()) break;
18068       // FALL THROUGH.
18069     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18070       if (!Subtarget->hasSSE1()) break;
18071
18072       switch (VT.getSimpleVT().SimpleTy) {
18073       default: break;
18074       // Scalar SSE types.
18075       case MVT::f32:
18076       case MVT::i32:
18077         return std::make_pair(0U, &X86::FR32RegClass);
18078       case MVT::f64:
18079       case MVT::i64:
18080         return std::make_pair(0U, &X86::FR64RegClass);
18081       // Vector types.
18082       case MVT::v16i8:
18083       case MVT::v8i16:
18084       case MVT::v4i32:
18085       case MVT::v2i64:
18086       case MVT::v4f32:
18087       case MVT::v2f64:
18088         return std::make_pair(0U, &X86::VR128RegClass);
18089       // AVX types.
18090       case MVT::v32i8:
18091       case MVT::v16i16:
18092       case MVT::v8i32:
18093       case MVT::v4i64:
18094       case MVT::v8f32:
18095       case MVT::v4f64:
18096         return std::make_pair(0U, &X86::VR256RegClass);
18097       }
18098       break;
18099     }
18100   }
18101
18102   // Use the default implementation in TargetLowering to convert the register
18103   // constraint into a member of a register class.
18104   std::pair<unsigned, const TargetRegisterClass*> Res;
18105   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18106
18107   // Not found as a standard register?
18108   if (Res.second == 0) {
18109     // Map st(0) -> st(7) -> ST0
18110     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18111         tolower(Constraint[1]) == 's' &&
18112         tolower(Constraint[2]) == 't' &&
18113         Constraint[3] == '(' &&
18114         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18115         Constraint[5] == ')' &&
18116         Constraint[6] == '}') {
18117
18118       Res.first = X86::ST0+Constraint[4]-'0';
18119       Res.second = &X86::RFP80RegClass;
18120       return Res;
18121     }
18122
18123     // GCC allows "st(0)" to be called just plain "st".
18124     if (StringRef("{st}").equals_lower(Constraint)) {
18125       Res.first = X86::ST0;
18126       Res.second = &X86::RFP80RegClass;
18127       return Res;
18128     }
18129
18130     // flags -> EFLAGS
18131     if (StringRef("{flags}").equals_lower(Constraint)) {
18132       Res.first = X86::EFLAGS;
18133       Res.second = &X86::CCRRegClass;
18134       return Res;
18135     }
18136
18137     // 'A' means EAX + EDX.
18138     if (Constraint == "A") {
18139       Res.first = X86::EAX;
18140       Res.second = &X86::GR32_ADRegClass;
18141       return Res;
18142     }
18143     return Res;
18144   }
18145
18146   // Otherwise, check to see if this is a register class of the wrong value
18147   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18148   // turn into {ax},{dx}.
18149   if (Res.second->hasType(VT))
18150     return Res;   // Correct type already, nothing to do.
18151
18152   // All of the single-register GCC register classes map their values onto
18153   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18154   // really want an 8-bit or 32-bit register, map to the appropriate register
18155   // class and return the appropriate register.
18156   if (Res.second == &X86::GR16RegClass) {
18157     if (VT == MVT::i8) {
18158       unsigned DestReg = 0;
18159       switch (Res.first) {
18160       default: break;
18161       case X86::AX: DestReg = X86::AL; break;
18162       case X86::DX: DestReg = X86::DL; break;
18163       case X86::CX: DestReg = X86::CL; break;
18164       case X86::BX: DestReg = X86::BL; break;
18165       }
18166       if (DestReg) {
18167         Res.first = DestReg;
18168         Res.second = &X86::GR8RegClass;
18169       }
18170     } else if (VT == MVT::i32) {
18171       unsigned DestReg = 0;
18172       switch (Res.first) {
18173       default: break;
18174       case X86::AX: DestReg = X86::EAX; break;
18175       case X86::DX: DestReg = X86::EDX; break;
18176       case X86::CX: DestReg = X86::ECX; break;
18177       case X86::BX: DestReg = X86::EBX; break;
18178       case X86::SI: DestReg = X86::ESI; break;
18179       case X86::DI: DestReg = X86::EDI; break;
18180       case X86::BP: DestReg = X86::EBP; break;
18181       case X86::SP: DestReg = X86::ESP; break;
18182       }
18183       if (DestReg) {
18184         Res.first = DestReg;
18185         Res.second = &X86::GR32RegClass;
18186       }
18187     } else if (VT == MVT::i64) {
18188       unsigned DestReg = 0;
18189       switch (Res.first) {
18190       default: break;
18191       case X86::AX: DestReg = X86::RAX; break;
18192       case X86::DX: DestReg = X86::RDX; break;
18193       case X86::CX: DestReg = X86::RCX; break;
18194       case X86::BX: DestReg = X86::RBX; break;
18195       case X86::SI: DestReg = X86::RSI; break;
18196       case X86::DI: DestReg = X86::RDI; break;
18197       case X86::BP: DestReg = X86::RBP; break;
18198       case X86::SP: DestReg = X86::RSP; break;
18199       }
18200       if (DestReg) {
18201         Res.first = DestReg;
18202         Res.second = &X86::GR64RegClass;
18203       }
18204     }
18205   } else if (Res.second == &X86::FR32RegClass ||
18206              Res.second == &X86::FR64RegClass ||
18207              Res.second == &X86::VR128RegClass) {
18208     // Handle references to XMM physical registers that got mapped into the
18209     // wrong class.  This can happen with constraints like {xmm0} where the
18210     // target independent register mapper will just pick the first match it can
18211     // find, ignoring the required type.
18212
18213     if (VT == MVT::f32 || VT == MVT::i32)
18214       Res.second = &X86::FR32RegClass;
18215     else if (VT == MVT::f64 || VT == MVT::i64)
18216       Res.second = &X86::FR64RegClass;
18217     else if (X86::VR128RegClass.hasType(VT))
18218       Res.second = &X86::VR128RegClass;
18219     else if (X86::VR256RegClass.hasType(VT))
18220       Res.second = &X86::VR256RegClass;
18221   }
18222
18223   return Res;
18224 }