add X86-specific DAG optimization to simplify boolean test
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #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.getSizeInBits() == 256 && "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.getConstant(NormalizedIdxVal, MVT::i32);
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.getSizeInBits() == 128 && "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.getConstant(NormalizedIdxVal, MVT::i32);
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   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getTargetData();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186     // Setup Windows compiler runtime calls.
187     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189     setLibcallName(RTLIB::SREM_I64, "_allrem");
190     setLibcallName(RTLIB::UREM_I64, "_aullrem");
191     setLibcallName(RTLIB::MUL_I64, "_allmul");
192     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
197
198     // The _ftol2 runtime function has an unusual calling conv, which
199     // is modeled by a special pseudo-instruction.
200     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
204   }
205
206   if (Subtarget->isTargetDarwin()) {
207     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208     setUseUnderscoreSetJmp(false);
209     setUseUnderscoreLongJmp(false);
210   } else if (Subtarget->isTargetMingw()) {
211     // MS runtime is weird: it exports _setjmp, but longjmp!
212     setUseUnderscoreSetJmp(true);
213     setUseUnderscoreLongJmp(false);
214   } else {
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(true);
217   }
218
219   // Set up the register classes.
220   addRegisterClass(MVT::i8, &X86::GR8RegClass);
221   addRegisterClass(MVT::i16, &X86::GR16RegClass);
222   addRegisterClass(MVT::i32, &X86::GR32RegClass);
223   if (Subtarget->is64Bit())
224     addRegisterClass(MVT::i64, &X86::GR64RegClass);
225
226   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
227
228   // We don't accept any truncstore of integer registers.
229   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
235
236   // SETOEQ and SETUNE require checking two conditions.
237   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
243
244   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
245   // operation.
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
248   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
249
250   if (Subtarget->is64Bit()) {
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
252     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
253   } else if (!TM.Options.UseSoftFloat) {
254     // We have an algorithm for SSE2->double, and we turn this into a
255     // 64-bit FILD followed by conditional FADD for other targets.
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257     // We have an algorithm for SSE2, and we turn this into a 64-bit
258     // FILD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
260   }
261
262   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
263   // this operation.
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
265   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
266
267   if (!TM.Options.UseSoftFloat) {
268     // SSE has no i16 to fp conversion, only i32
269     if (X86ScalarSSEf32) {
270       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
271       // f32 and f64 cases are Legal, f80 case is not
272       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
273     } else {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     }
277   } else {
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
279     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
280   }
281
282   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
283   // are Legal, f80 is custom lowered.
284   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
285   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
286
287   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
288   // this operation.
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
290   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
291
292   if (X86ScalarSSEf32) {
293     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
294     // f32 and f64 cases are Legal, f80 case is not
295     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
296   } else {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   }
300
301   // Handle FP_TO_UINT by promoting the destination to a larger signed
302   // conversion.
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
305   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
306
307   if (Subtarget->is64Bit()) {
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
309     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
310   } else if (!TM.Options.UseSoftFloat) {
311     // Since AVX is a superset of SSE3, only check for SSE here.
312     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313       // Expand FP_TO_UINT into a select.
314       // FIXME: We would like to use a Custom expander here eventually to do
315       // the optimal thing for SSE vs. the default expansion in the legalizer.
316       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
317     else
318       // With SSE3 we can use fisttpll to convert to a signed i64; without
319       // SSE, we're stuck with a fistpll.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
321   }
322
323   if (isTargetFTOL()) {
324     // Use the _ftol2 runtime function, which has a pseudo-instruction
325     // to handle its weird calling convention.
326     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   // Promote the i8 variants and force them on up to i32 which has a shorter
382   // encoding.
383   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
384   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
385   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
386   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
387   if (Subtarget->hasBMI()) {
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
389     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
390     if (Subtarget->is64Bit())
391       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
392   } else {
393     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
394     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
397   }
398
399   if (Subtarget->hasLZCNT()) {
400     // When promoting the i8 variants, force them to i32 for a shorter
401     // encoding.
402     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
403     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
404     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
405     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410   } else {
411     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
413     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
419       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
420     }
421   }
422
423   if (Subtarget->hasPOPCNT()) {
424     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
425   } else {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
429     if (Subtarget->is64Bit())
430       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
431   }
432
433   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
434   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
435
436   // These should be promoted to a larger select which is supported.
437   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
438   // X86 wants to expand cmov itself.
439   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
453     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
454   }
455   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
456
457   // Darwin ABI issue.
458   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
459   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
462   if (Subtarget->is64Bit())
463     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
465   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
466   if (Subtarget->is64Bit()) {
467     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
468     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
469     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
470     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
471     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
472   }
473   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
481   }
482
483   if (Subtarget->hasSSE1())
484     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
485
486   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
487   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
488
489   // On X86 and X86-64, atomic operations are lowered to locked instructions.
490   // Locked instructions, in turn, have implicit fence semantics (all memory
491   // operations are flushed before issuing the locked instruction, and they
492   // are not buffered), so we can fold away the common pattern of
493   // fence-atomic-fence.
494   setShouldFoldAtomicFences(true);
495
496   // Expand certain atomics
497   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
498     MVT VT = IntVTs[i];
499     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   if (Subtarget->hasCmpxchg16b()) {
516     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
517   }
518
519   // FIXME - use subtarget debug flags
520   if (!Subtarget->isTargetDarwin() &&
521       !Subtarget->isTargetELF() &&
522       !Subtarget->isTargetCygMing()) {
523     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
524   }
525
526   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
528   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
530   if (Subtarget->is64Bit()) {
531     setExceptionPointerRegister(X86::RAX);
532     setExceptionSelectorRegister(X86::RDX);
533   } else {
534     setExceptionPointerRegister(X86::EAX);
535     setExceptionSelectorRegister(X86::EDX);
536   }
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
539
540   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
542
543   setOperationAction(ISD::TRAP, MVT::Other, Legal);
544
545   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
547   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
548   if (Subtarget->is64Bit()) {
549     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
550     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
551   } else {
552     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
553     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
554   }
555
556   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
557   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
558
559   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Custom);
562   else if (TM.Options.EnableSegmentedStacks)
563     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564                        MVT::i64 : MVT::i32, Custom);
565   else
566     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567                        MVT::i64 : MVT::i32, Expand);
568
569   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570     // f32 and f64 use SSE.
571     // Set up the FP register classes.
572     addRegisterClass(MVT::f32, &X86::FR32RegClass);
573     addRegisterClass(MVT::f64, &X86::FR64RegClass);
574
575     // Use ANDPD to simulate FABS.
576     setOperationAction(ISD::FABS , MVT::f64, Custom);
577     setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579     // Use XORP to simulate FNEG.
580     setOperationAction(ISD::FNEG , MVT::f64, Custom);
581     setOperationAction(ISD::FNEG , MVT::f32, Custom);
582
583     // Use ANDPD and ORPD to simulate FCOPYSIGN.
584     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
586
587     // Lower this to FGETSIGNx86 plus an AND.
588     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590
591     // We don't support sin/cos/fmod
592     setOperationAction(ISD::FSIN , MVT::f64, Expand);
593     setOperationAction(ISD::FCOS , MVT::f64, Expand);
594     setOperationAction(ISD::FSIN , MVT::f32, Expand);
595     setOperationAction(ISD::FCOS , MVT::f32, Expand);
596
597     // Expand FP immediates into loads from the stack, except for the special
598     // cases we handle.
599     addLegalFPImmediate(APFloat(+0.0)); // xorpd
600     addLegalFPImmediate(APFloat(+0.0f)); // xorps
601   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602     // Use SSE for f32, x87 for f64.
603     // Set up the FP register classes.
604     addRegisterClass(MVT::f32, &X86::FR32RegClass);
605     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
606
607     // Use ANDPS to simulate FABS.
608     setOperationAction(ISD::FABS , MVT::f32, Custom);
609
610     // Use XORP to simulate FNEG.
611     setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
614
615     // Use ANDPS and ORPS to simulate FCOPYSIGN.
616     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618
619     // We don't support sin/cos/fmod
620     setOperationAction(ISD::FSIN , MVT::f32, Expand);
621     setOperationAction(ISD::FCOS , MVT::f32, Expand);
622
623     // Special cases we handle for FP constants.
624     addLegalFPImmediate(APFloat(+0.0f)); // xorps
625     addLegalFPImmediate(APFloat(+0.0)); // FLD0
626     addLegalFPImmediate(APFloat(+1.0)); // FLD1
627     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
629
630     if (!TM.Options.UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634   } else if (!TM.Options.UseSoftFloat) {
635     // f32 and f64 in x87.
636     // Set up the FP register classes.
637     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
639
640     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
641     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
644
645     if (!TM.Options.UnsafeFPMath) {
646       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
647       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
648     }
649     addLegalFPImmediate(APFloat(+0.0)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
657   }
658
659   // We don't support FMA.
660   setOperationAction(ISD::FMA, MVT::f64, Expand);
661   setOperationAction(ISD::FMA, MVT::f32, Expand);
662
663   // Long double always uses X87.
664   if (!TM.Options.UseSoftFloat) {
665     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
667     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
668     {
669       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670       addLegalFPImmediate(TmpFlt);  // FLD0
671       TmpFlt.changeSign();
672       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
673
674       bool ignored;
675       APFloat TmpFlt2(+1.0);
676       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
677                       &ignored);
678       addLegalFPImmediate(TmpFlt2);  // FLD1
679       TmpFlt2.changeSign();
680       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
681     }
682
683     if (!TM.Options.UnsafeFPMath) {
684       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
685       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
686     }
687
688     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
690     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
692     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693     setOperationAction(ISD::FMA, MVT::f80, Expand);
694   }
695
696   // Always use a library call for pow.
697   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
699   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
700
701   setOperationAction(ISD::FLOG, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP, MVT::f80, Expand);
705   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
706
707   // First set operation action for all vector types to either promote
708   // (for widening) or expand (for scalarization). Then we will selectively
709   // turn on ones that can be effectively codegen'd.
710   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
770     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772       setTruncStoreAction((MVT::SimpleValueType)VT,
773                           (MVT::SimpleValueType)InnerVT, Expand);
774     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
777   }
778
779   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780   // with -msoft-float, disable use of MMX as well.
781   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
783     // No operations on x86mmx supported, everything uses intrinsics.
784   }
785
786   // MMX-sized vectors (other than x86mmx) are expected to be expanded
787   // into smaller operations.
788   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
789   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
790   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
791   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
792   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
793   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
794   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
795   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
796   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
797   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
798   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
799   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
800   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
801   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
802   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
803   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
806   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
807   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
808   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
810   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
811   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
812   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
815   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
816   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
817
818   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
819     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
820
821     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
827     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
828     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
829     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
830     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
833   }
834
835   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
836     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
837
838     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
839     // registers cannot be used even for integer operations.
840     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
841     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
842     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
843     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
844
845     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
846     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
847     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
848     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
849     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
850     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
851     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
852     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
853     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
854     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
855     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
858     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
859     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
860     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
861
862     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
864     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
865     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
866
867     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
868     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
872
873     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
874     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
875     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
876     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
877     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
878
879     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881       EVT VT = (MVT::SimpleValueType)i;
882       // Do not attempt to custom lower non-power-of-2 vectors
883       if (!isPowerOf2_32(VT.getVectorNumElements()))
884         continue;
885       // Do not attempt to custom lower non-128-bit vectors
886       if (!VT.is128BitVector())
887         continue;
888       setOperationAction(ISD::BUILD_VECTOR,
889                          VT.getSimpleVT().SimpleTy, Custom);
890       setOperationAction(ISD::VECTOR_SHUFFLE,
891                          VT.getSimpleVT().SimpleTy, Custom);
892       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
893                          VT.getSimpleVT().SimpleTy, Custom);
894     }
895
896     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
897     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
898     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
899     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
900     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
901     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
902
903     if (Subtarget->is64Bit()) {
904       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
906     }
907
908     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
911       EVT VT = SVT;
912
913       // Do not attempt to promote non-128-bit vectors
914       if (!VT.is128BitVector())
915         continue;
916
917       setOperationAction(ISD::AND,    SVT, Promote);
918       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
919       setOperationAction(ISD::OR,     SVT, Promote);
920       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
921       setOperationAction(ISD::XOR,    SVT, Promote);
922       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
923       setOperationAction(ISD::LOAD,   SVT, Promote);
924       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
925       setOperationAction(ISD::SELECT, SVT, Promote);
926       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
927     }
928
929     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
930
931     // Custom lower v2i64 and v2f64 selects.
932     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
933     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
934     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
935     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
936
937     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
938     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
939   }
940
941   if (Subtarget->hasSSE41()) {
942     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
943     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
944     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
945     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
946     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
947     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
948     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
949     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
950     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
951     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
952
953     // FIXME: Do we need to handle scalar-to-vector here?
954     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
955
956     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
957     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
958     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
959     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
960     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
961
962     // i8 and i16 vectors are custom , because the source register and source
963     // source memory operand types are not the same width.  f32 vectors are
964     // custom since the immediate controlling the insert encodes additional
965     // information.
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
970
971     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
973     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
974     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
975
976     // FIXME: these should be Legal but thats only for the case where
977     // the index is constant.  For now custom expand to deal with that.
978     if (Subtarget->is64Bit()) {
979       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
980       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
981     }
982   }
983
984   if (Subtarget->hasSSE2()) {
985     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
986     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
987
988     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
989     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
990
991     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
992     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
993
994     if (Subtarget->hasAVX2()) {
995       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
996       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
997
998       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
999       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1000
1001       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1002     } else {
1003       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1004       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1005
1006       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1007       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1008
1009       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE42())
1014     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1015
1016   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1017     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1019     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1021     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1023
1024     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1026     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1027
1028     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1033     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1034
1035     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1036     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1038     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1039     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1040     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1041
1042     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1043     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1044     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1045
1046     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1047     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1048     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1049     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1050     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1051     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1052
1053     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1054     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1055
1056     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1057     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1058
1059     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1060     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1061
1062     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1063     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1064     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1065     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1066
1067     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1068     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1069     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1070
1071     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1072     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1073     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1074     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1075
1076     if (Subtarget->hasFMA()) {
1077       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1078       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1079       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1080       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1081       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1082       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1083     }
1084     if (Subtarget->hasAVX2()) {
1085       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1086       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1087       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1088       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1089
1090       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1091       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1092       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1093       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1094
1095       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1097       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1098       // Don't lower v32i8 because there is no 128-bit byte mul
1099
1100       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1101
1102       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1103       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1104
1105       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1106       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1107
1108       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1109     } else {
1110       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1112       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1113       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1114
1115       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1117       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1118       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1119
1120       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1121       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1122       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1123       // Don't lower v32i8 because there is no 128-bit byte mul
1124
1125       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1126       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1127
1128       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1129       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1130
1131       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1132     }
1133
1134     // Custom lower several nodes for 256-bit types.
1135     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1136              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1137       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1138       EVT VT = SVT;
1139
1140       // Extract subvector is special because the value type
1141       // (result) is 128-bit but the source is 256-bit wide.
1142       if (VT.is128BitVector())
1143         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1144
1145       // Do not attempt to custom lower other non-256-bit vectors
1146       if (!VT.is256BitVector())
1147         continue;
1148
1149       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1150       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1151       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1152       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1153       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1154       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1155     }
1156
1157     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1158     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1159       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1160       EVT VT = SVT;
1161
1162       // Do not attempt to promote non-256-bit vectors
1163       if (!VT.is256BitVector())
1164         continue;
1165
1166       setOperationAction(ISD::AND,    SVT, Promote);
1167       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1168       setOperationAction(ISD::OR,     SVT, Promote);
1169       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1170       setOperationAction(ISD::XOR,    SVT, Promote);
1171       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1172       setOperationAction(ISD::LOAD,   SVT, Promote);
1173       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1174       setOperationAction(ISD::SELECT, SVT, Promote);
1175       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1176     }
1177   }
1178
1179   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1180   // of this type with custom code.
1181   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1182            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1183     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1184                        Custom);
1185   }
1186
1187   // We want to custom lower some of our intrinsics.
1188   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1189   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1190
1191
1192   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1193   // handle type legalization for these operations here.
1194   //
1195   // FIXME: We really should do custom legalization for addition and
1196   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1197   // than generic legalization for 64-bit multiplication-with-overflow, though.
1198   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1199     // Add/Sub/Mul with overflow operations are custom lowered.
1200     MVT VT = IntVTs[i];
1201     setOperationAction(ISD::SADDO, VT, Custom);
1202     setOperationAction(ISD::UADDO, VT, Custom);
1203     setOperationAction(ISD::SSUBO, VT, Custom);
1204     setOperationAction(ISD::USUBO, VT, Custom);
1205     setOperationAction(ISD::SMULO, VT, Custom);
1206     setOperationAction(ISD::UMULO, VT, Custom);
1207   }
1208
1209   // There are no 8-bit 3-address imul/mul instructions
1210   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1211   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1212
1213   if (!Subtarget->is64Bit()) {
1214     // These libcalls are not available in 32-bit.
1215     setLibcallName(RTLIB::SHL_I128, 0);
1216     setLibcallName(RTLIB::SRL_I128, 0);
1217     setLibcallName(RTLIB::SRA_I128, 0);
1218   }
1219
1220   // We have target-specific dag combine patterns for the following nodes:
1221   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1222   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1223   setTargetDAGCombine(ISD::VSELECT);
1224   setTargetDAGCombine(ISD::SELECT);
1225   setTargetDAGCombine(ISD::SHL);
1226   setTargetDAGCombine(ISD::SRA);
1227   setTargetDAGCombine(ISD::SRL);
1228   setTargetDAGCombine(ISD::OR);
1229   setTargetDAGCombine(ISD::AND);
1230   setTargetDAGCombine(ISD::ADD);
1231   setTargetDAGCombine(ISD::FADD);
1232   setTargetDAGCombine(ISD::FSUB);
1233   setTargetDAGCombine(ISD::FMA);
1234   setTargetDAGCombine(ISD::SUB);
1235   setTargetDAGCombine(ISD::LOAD);
1236   setTargetDAGCombine(ISD::STORE);
1237   setTargetDAGCombine(ISD::ZERO_EXTEND);
1238   setTargetDAGCombine(ISD::ANY_EXTEND);
1239   setTargetDAGCombine(ISD::SIGN_EXTEND);
1240   setTargetDAGCombine(ISD::TRUNCATE);
1241   setTargetDAGCombine(ISD::UINT_TO_FP);
1242   setTargetDAGCombine(ISD::SINT_TO_FP);
1243   setTargetDAGCombine(ISD::SETCC);
1244   setTargetDAGCombine(ISD::FP_TO_SINT);
1245   if (Subtarget->is64Bit())
1246     setTargetDAGCombine(ISD::MUL);
1247   setTargetDAGCombine(ISD::XOR);
1248
1249   computeRegisterProperties();
1250
1251   // On Darwin, -Os means optimize for size without hurting performance,
1252   // do not reduce the limit.
1253   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1254   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1255   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1256   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1257   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1258   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1259   setPrefLoopAlignment(4); // 2^4 bytes.
1260   benefitFromCodePlacementOpt = true;
1261
1262   // Predictable cmov don't hurt on atom because it's in-order.
1263   predictableSelectIsExpensive = !Subtarget->isAtom();
1264
1265   setPrefFunctionAlignment(4); // 2^4 bytes.
1266 }
1267
1268
1269 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1270   if (!VT.isVector()) return MVT::i8;
1271   return VT.changeVectorElementTypeToInteger();
1272 }
1273
1274
1275 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1276 /// the desired ByVal argument alignment.
1277 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1278   if (MaxAlign == 16)
1279     return;
1280   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1281     if (VTy->getBitWidth() == 128)
1282       MaxAlign = 16;
1283   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1284     unsigned EltAlign = 0;
1285     getMaxByValAlign(ATy->getElementType(), EltAlign);
1286     if (EltAlign > MaxAlign)
1287       MaxAlign = EltAlign;
1288   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1289     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1290       unsigned EltAlign = 0;
1291       getMaxByValAlign(STy->getElementType(i), EltAlign);
1292       if (EltAlign > MaxAlign)
1293         MaxAlign = EltAlign;
1294       if (MaxAlign == 16)
1295         break;
1296     }
1297   }
1298 }
1299
1300 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1301 /// function arguments in the caller parameter area. For X86, aggregates
1302 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1303 /// are at 4-byte boundaries.
1304 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1305   if (Subtarget->is64Bit()) {
1306     // Max of 8 and alignment of type.
1307     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1308     if (TyAlign > 8)
1309       return TyAlign;
1310     return 8;
1311   }
1312
1313   unsigned Align = 4;
1314   if (Subtarget->hasSSE1())
1315     getMaxByValAlign(Ty, Align);
1316   return Align;
1317 }
1318
1319 /// getOptimalMemOpType - Returns the target specific optimal type for load
1320 /// and store operations as a result of memset, memcpy, and memmove
1321 /// lowering. If DstAlign is zero that means it's safe to destination
1322 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1323 /// means there isn't a need to check it against alignment requirement,
1324 /// probably because the source does not need to be loaded. If
1325 /// 'IsZeroVal' is true, that means it's safe to return a
1326 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1327 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1328 /// constant so it does not need to be loaded.
1329 /// It returns EVT::Other if the type should be determined using generic
1330 /// target-independent logic.
1331 EVT
1332 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1333                                        unsigned DstAlign, unsigned SrcAlign,
1334                                        bool IsZeroVal,
1335                                        bool MemcpyStrSrc,
1336                                        MachineFunction &MF) const {
1337   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1338   // linux.  This is because the stack realignment code can't handle certain
1339   // cases like PR2962.  This should be removed when PR2962 is fixed.
1340   const Function *F = MF.getFunction();
1341   if (IsZeroVal &&
1342       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1343     if (Size >= 16 &&
1344         (Subtarget->isUnalignedMemAccessFast() ||
1345          ((DstAlign == 0 || DstAlign >= 16) &&
1346           (SrcAlign == 0 || SrcAlign >= 16))) &&
1347         Subtarget->getStackAlignment() >= 16) {
1348       if (Subtarget->getStackAlignment() >= 32) {
1349         if (Subtarget->hasAVX2())
1350           return MVT::v8i32;
1351         if (Subtarget->hasAVX())
1352           return MVT::v8f32;
1353       }
1354       if (Subtarget->hasSSE2())
1355         return MVT::v4i32;
1356       if (Subtarget->hasSSE1())
1357         return MVT::v4f32;
1358     } else if (!MemcpyStrSrc && Size >= 8 &&
1359                !Subtarget->is64Bit() &&
1360                Subtarget->getStackAlignment() >= 8 &&
1361                Subtarget->hasSSE2()) {
1362       // Do not use f64 to lower memcpy if source is string constant. It's
1363       // better to use i32 to avoid the loads.
1364       return MVT::f64;
1365     }
1366   }
1367   if (Subtarget->is64Bit() && Size >= 8)
1368     return MVT::i64;
1369   return MVT::i32;
1370 }
1371
1372 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1373 /// current function.  The returned value is a member of the
1374 /// MachineJumpTableInfo::JTEntryKind enum.
1375 unsigned X86TargetLowering::getJumpTableEncoding() const {
1376   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1377   // symbol.
1378   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379       Subtarget->isPICStyleGOT())
1380     return MachineJumpTableInfo::EK_Custom32;
1381
1382   // Otherwise, use the normal jump table encoding heuristics.
1383   return TargetLowering::getJumpTableEncoding();
1384 }
1385
1386 const MCExpr *
1387 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1388                                              const MachineBasicBlock *MBB,
1389                                              unsigned uid,MCContext &Ctx) const{
1390   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1391          Subtarget->isPICStyleGOT());
1392   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1393   // entries.
1394   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1395                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1396 }
1397
1398 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1399 /// jumptable.
1400 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1401                                                     SelectionDAG &DAG) const {
1402   if (!Subtarget->is64Bit())
1403     // This doesn't have DebugLoc associated with it, but is not really the
1404     // same as a Register.
1405     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1406   return Table;
1407 }
1408
1409 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1410 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1411 /// MCExpr.
1412 const MCExpr *X86TargetLowering::
1413 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1414                              MCContext &Ctx) const {
1415   // X86-64 uses RIP relative addressing based on the jump table label.
1416   if (Subtarget->isPICStyleRIPRel())
1417     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1418
1419   // Otherwise, the reference is relative to the PIC base.
1420   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1421 }
1422
1423 // FIXME: Why this routine is here? Move to RegInfo!
1424 std::pair<const TargetRegisterClass*, uint8_t>
1425 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1426   const TargetRegisterClass *RRC = 0;
1427   uint8_t Cost = 1;
1428   switch (VT.getSimpleVT().SimpleTy) {
1429   default:
1430     return TargetLowering::findRepresentativeClass(VT);
1431   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1432     RRC = Subtarget->is64Bit() ?
1433       (const TargetRegisterClass*)&X86::GR64RegClass :
1434       (const TargetRegisterClass*)&X86::GR32RegClass;
1435     break;
1436   case MVT::x86mmx:
1437     RRC = &X86::VR64RegClass;
1438     break;
1439   case MVT::f32: case MVT::f64:
1440   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1441   case MVT::v4f32: case MVT::v2f64:
1442   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1443   case MVT::v4f64:
1444     RRC = &X86::VR128RegClass;
1445     break;
1446   }
1447   return std::make_pair(RRC, Cost);
1448 }
1449
1450 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1451                                                unsigned &Offset) const {
1452   if (!Subtarget->isTargetLinux())
1453     return false;
1454
1455   if (Subtarget->is64Bit()) {
1456     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1457     Offset = 0x28;
1458     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1459       AddressSpace = 256;
1460     else
1461       AddressSpace = 257;
1462   } else {
1463     // %gs:0x14 on i386
1464     Offset = 0x14;
1465     AddressSpace = 256;
1466   }
1467   return true;
1468 }
1469
1470
1471 //===----------------------------------------------------------------------===//
1472 //               Return Value Calling Convention Implementation
1473 //===----------------------------------------------------------------------===//
1474
1475 #include "X86GenCallingConv.inc"
1476
1477 bool
1478 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1479                                   MachineFunction &MF, bool isVarArg,
1480                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1481                         LLVMContext &Context) const {
1482   SmallVector<CCValAssign, 16> RVLocs;
1483   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1484                  RVLocs, Context);
1485   return CCInfo.CheckReturn(Outs, RetCC_X86);
1486 }
1487
1488 SDValue
1489 X86TargetLowering::LowerReturn(SDValue Chain,
1490                                CallingConv::ID CallConv, bool isVarArg,
1491                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1492                                const SmallVectorImpl<SDValue> &OutVals,
1493                                DebugLoc dl, SelectionDAG &DAG) const {
1494   MachineFunction &MF = DAG.getMachineFunction();
1495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1496
1497   SmallVector<CCValAssign, 16> RVLocs;
1498   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1499                  RVLocs, *DAG.getContext());
1500   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1501
1502   // Add the regs to the liveout set for the function.
1503   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1504   for (unsigned i = 0; i != RVLocs.size(); ++i)
1505     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1506       MRI.addLiveOut(RVLocs[i].getLocReg());
1507
1508   SDValue Flag;
1509
1510   SmallVector<SDValue, 6> RetOps;
1511   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1512   // Operand #1 = Bytes To Pop
1513   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1514                    MVT::i16));
1515
1516   // Copy the result values into the output registers.
1517   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1518     CCValAssign &VA = RVLocs[i];
1519     assert(VA.isRegLoc() && "Can only return in registers!");
1520     SDValue ValToCopy = OutVals[i];
1521     EVT ValVT = ValToCopy.getValueType();
1522
1523     // Promote values to the appropriate types
1524     if (VA.getLocInfo() == CCValAssign::SExt)
1525       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1526     else if (VA.getLocInfo() == CCValAssign::ZExt)
1527       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1528     else if (VA.getLocInfo() == CCValAssign::AExt)
1529       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1530     else if (VA.getLocInfo() == CCValAssign::BCvt)
1531       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1532
1533     // If this is x86-64, and we disabled SSE, we can't return FP values,
1534     // or SSE or MMX vectors.
1535     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1536          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1537           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1538       report_fatal_error("SSE register return with SSE disabled");
1539     }
1540     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1541     // llvm-gcc has never done it right and no one has noticed, so this
1542     // should be OK for now.
1543     if (ValVT == MVT::f64 &&
1544         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1545       report_fatal_error("SSE2 register return with SSE2 disabled");
1546
1547     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1548     // the RET instruction and handled by the FP Stackifier.
1549     if (VA.getLocReg() == X86::ST0 ||
1550         VA.getLocReg() == X86::ST1) {
1551       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1552       // change the value to the FP stack register class.
1553       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1554         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1555       RetOps.push_back(ValToCopy);
1556       // Don't emit a copytoreg.
1557       continue;
1558     }
1559
1560     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1561     // which is returned in RAX / RDX.
1562     if (Subtarget->is64Bit()) {
1563       if (ValVT == MVT::x86mmx) {
1564         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1565           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1566           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1567                                   ValToCopy);
1568           // If we don't have SSE2 available, convert to v4f32 so the generated
1569           // register is legal.
1570           if (!Subtarget->hasSSE2())
1571             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1572         }
1573       }
1574     }
1575
1576     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1577     Flag = Chain.getValue(1);
1578   }
1579
1580   // The x86-64 ABI for returning structs by value requires that we copy
1581   // the sret argument into %rax for the return. We saved the argument into
1582   // a virtual register in the entry block, so now we copy the value out
1583   // and into %rax.
1584   if (Subtarget->is64Bit() &&
1585       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1586     MachineFunction &MF = DAG.getMachineFunction();
1587     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1588     unsigned Reg = FuncInfo->getSRetReturnReg();
1589     assert(Reg &&
1590            "SRetReturnReg should have been set in LowerFormalArguments().");
1591     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1592
1593     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1594     Flag = Chain.getValue(1);
1595
1596     // RAX now acts like a return value.
1597     MRI.addLiveOut(X86::RAX);
1598   }
1599
1600   RetOps[0] = Chain;  // Update chain.
1601
1602   // Add the flag if we have it.
1603   if (Flag.getNode())
1604     RetOps.push_back(Flag);
1605
1606   return DAG.getNode(X86ISD::RET_FLAG, dl,
1607                      MVT::Other, &RetOps[0], RetOps.size());
1608 }
1609
1610 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1611   if (N->getNumValues() != 1)
1612     return false;
1613   if (!N->hasNUsesOfValue(1, 0))
1614     return false;
1615
1616   SDValue TCChain = Chain;
1617   SDNode *Copy = *N->use_begin();
1618   if (Copy->getOpcode() == ISD::CopyToReg) {
1619     // If the copy has a glue operand, we conservatively assume it isn't safe to
1620     // perform a tail call.
1621     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1622       return false;
1623     TCChain = Copy->getOperand(0);
1624   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1625     return false;
1626
1627   bool HasRet = false;
1628   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1629        UI != UE; ++UI) {
1630     if (UI->getOpcode() != X86ISD::RET_FLAG)
1631       return false;
1632     HasRet = true;
1633   }
1634
1635   if (!HasRet)
1636     return false;
1637
1638   Chain = TCChain;
1639   return true;
1640 }
1641
1642 EVT
1643 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1644                                             ISD::NodeType ExtendKind) const {
1645   MVT ReturnMVT;
1646   // TODO: Is this also valid on 32-bit?
1647   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1648     ReturnMVT = MVT::i8;
1649   else
1650     ReturnMVT = MVT::i32;
1651
1652   EVT MinVT = getRegisterType(Context, ReturnMVT);
1653   return VT.bitsLT(MinVT) ? MinVT : VT;
1654 }
1655
1656 /// LowerCallResult - Lower the result values of a call into the
1657 /// appropriate copies out of appropriate physical registers.
1658 ///
1659 SDValue
1660 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1661                                    CallingConv::ID CallConv, bool isVarArg,
1662                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1663                                    DebugLoc dl, SelectionDAG &DAG,
1664                                    SmallVectorImpl<SDValue> &InVals) const {
1665
1666   // Assign locations to each value returned by this call.
1667   SmallVector<CCValAssign, 16> RVLocs;
1668   bool Is64Bit = Subtarget->is64Bit();
1669   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1670                  getTargetMachine(), RVLocs, *DAG.getContext());
1671   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1672
1673   // Copy all of the result registers out of their specified physreg.
1674   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1675     CCValAssign &VA = RVLocs[i];
1676     EVT CopyVT = VA.getValVT();
1677
1678     // If this is x86-64, and we disabled SSE, we can't return FP values
1679     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1680         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1681       report_fatal_error("SSE register return with SSE disabled");
1682     }
1683
1684     SDValue Val;
1685
1686     // If this is a call to a function that returns an fp value on the floating
1687     // point stack, we must guarantee the value is popped from the stack, so
1688     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1689     // if the return value is not used. We use the FpPOP_RETVAL instruction
1690     // instead.
1691     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1692       // If we prefer to use the value in xmm registers, copy it out as f80 and
1693       // use a truncate to move it from fp stack reg to xmm reg.
1694       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1695       SDValue Ops[] = { Chain, InFlag };
1696       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1697                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1698       Val = Chain.getValue(0);
1699
1700       // Round the f80 to the right size, which also moves it to the appropriate
1701       // xmm register.
1702       if (CopyVT != VA.getValVT())
1703         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1704                           // This truncation won't change the value.
1705                           DAG.getIntPtrConstant(1));
1706     } else {
1707       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1708                                  CopyVT, InFlag).getValue(1);
1709       Val = Chain.getValue(0);
1710     }
1711     InFlag = Chain.getValue(2);
1712     InVals.push_back(Val);
1713   }
1714
1715   return Chain;
1716 }
1717
1718
1719 //===----------------------------------------------------------------------===//
1720 //                C & StdCall & Fast Calling Convention implementation
1721 //===----------------------------------------------------------------------===//
1722 //  StdCall calling convention seems to be standard for many Windows' API
1723 //  routines and around. It differs from C calling convention just a little:
1724 //  callee should clean up the stack, not caller. Symbols should be also
1725 //  decorated in some fancy way :) It doesn't support any vector arguments.
1726 //  For info on fast calling convention see Fast Calling Convention (tail call)
1727 //  implementation LowerX86_32FastCCCallTo.
1728
1729 /// CallIsStructReturn - Determines whether a call uses struct return
1730 /// semantics.
1731 enum StructReturnType {
1732   NotStructReturn,
1733   RegStructReturn,
1734   StackStructReturn
1735 };
1736 static StructReturnType
1737 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1738   if (Outs.empty())
1739     return NotStructReturn;
1740
1741   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1742   if (!Flags.isSRet())
1743     return NotStructReturn;
1744   if (Flags.isInReg())
1745     return RegStructReturn;
1746   return StackStructReturn;
1747 }
1748
1749 /// ArgsAreStructReturn - Determines whether a function uses struct
1750 /// return semantics.
1751 static StructReturnType
1752 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1753   if (Ins.empty())
1754     return NotStructReturn;
1755
1756   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1757   if (!Flags.isSRet())
1758     return NotStructReturn;
1759   if (Flags.isInReg())
1760     return RegStructReturn;
1761   return StackStructReturn;
1762 }
1763
1764 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1765 /// by "Src" to address "Dst" with size and alignment information specified by
1766 /// the specific parameter attribute. The copy will be passed as a byval
1767 /// function parameter.
1768 static SDValue
1769 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1770                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1771                           DebugLoc dl) {
1772   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1773
1774   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1775                        /*isVolatile*/false, /*AlwaysInline=*/true,
1776                        MachinePointerInfo(), MachinePointerInfo());
1777 }
1778
1779 /// IsTailCallConvention - Return true if the calling convention is one that
1780 /// supports tail call optimization.
1781 static bool IsTailCallConvention(CallingConv::ID CC) {
1782   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1783 }
1784
1785 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1786   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1787     return false;
1788
1789   CallSite CS(CI);
1790   CallingConv::ID CalleeCC = CS.getCallingConv();
1791   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1792     return false;
1793
1794   return true;
1795 }
1796
1797 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1798 /// a tailcall target by changing its ABI.
1799 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1800                                    bool GuaranteedTailCallOpt) {
1801   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1802 }
1803
1804 SDValue
1805 X86TargetLowering::LowerMemArgument(SDValue Chain,
1806                                     CallingConv::ID CallConv,
1807                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1808                                     DebugLoc dl, SelectionDAG &DAG,
1809                                     const CCValAssign &VA,
1810                                     MachineFrameInfo *MFI,
1811                                     unsigned i) const {
1812   // Create the nodes corresponding to a load from this parameter slot.
1813   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1814   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1815                               getTargetMachine().Options.GuaranteedTailCallOpt);
1816   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1817   EVT ValVT;
1818
1819   // If value is passed by pointer we have address passed instead of the value
1820   // itself.
1821   if (VA.getLocInfo() == CCValAssign::Indirect)
1822     ValVT = VA.getLocVT();
1823   else
1824     ValVT = VA.getValVT();
1825
1826   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1827   // changed with more analysis.
1828   // In case of tail call optimization mark all arguments mutable. Since they
1829   // could be overwritten by lowering of arguments in case of a tail call.
1830   if (Flags.isByVal()) {
1831     unsigned Bytes = Flags.getByValSize();
1832     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1833     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1834     return DAG.getFrameIndex(FI, getPointerTy());
1835   } else {
1836     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1837                                     VA.getLocMemOffset(), isImmutable);
1838     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1839     return DAG.getLoad(ValVT, dl, Chain, FIN,
1840                        MachinePointerInfo::getFixedStack(FI),
1841                        false, false, false, 0);
1842   }
1843 }
1844
1845 SDValue
1846 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1847                                         CallingConv::ID CallConv,
1848                                         bool isVarArg,
1849                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1850                                         DebugLoc dl,
1851                                         SelectionDAG &DAG,
1852                                         SmallVectorImpl<SDValue> &InVals)
1853                                           const {
1854   MachineFunction &MF = DAG.getMachineFunction();
1855   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1856
1857   const Function* Fn = MF.getFunction();
1858   if (Fn->hasExternalLinkage() &&
1859       Subtarget->isTargetCygMing() &&
1860       Fn->getName() == "main")
1861     FuncInfo->setForceFramePointer(true);
1862
1863   MachineFrameInfo *MFI = MF.getFrameInfo();
1864   bool Is64Bit = Subtarget->is64Bit();
1865   bool IsWindows = Subtarget->isTargetWindows();
1866   bool IsWin64 = Subtarget->isTargetWin64();
1867
1868   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1869          "Var args not supported with calling convention fastcc or ghc");
1870
1871   // Assign locations to all of the incoming arguments.
1872   SmallVector<CCValAssign, 16> ArgLocs;
1873   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1874                  ArgLocs, *DAG.getContext());
1875
1876   // Allocate shadow area for Win64
1877   if (IsWin64) {
1878     CCInfo.AllocateStack(32, 8);
1879   }
1880
1881   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1882
1883   unsigned LastVal = ~0U;
1884   SDValue ArgValue;
1885   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1886     CCValAssign &VA = ArgLocs[i];
1887     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1888     // places.
1889     assert(VA.getValNo() != LastVal &&
1890            "Don't support value assigned to multiple locs yet");
1891     (void)LastVal;
1892     LastVal = VA.getValNo();
1893
1894     if (VA.isRegLoc()) {
1895       EVT RegVT = VA.getLocVT();
1896       const TargetRegisterClass *RC;
1897       if (RegVT == MVT::i32)
1898         RC = &X86::GR32RegClass;
1899       else if (Is64Bit && RegVT == MVT::i64)
1900         RC = &X86::GR64RegClass;
1901       else if (RegVT == MVT::f32)
1902         RC = &X86::FR32RegClass;
1903       else if (RegVT == MVT::f64)
1904         RC = &X86::FR64RegClass;
1905       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1906         RC = &X86::VR256RegClass;
1907       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1908         RC = &X86::VR128RegClass;
1909       else if (RegVT == MVT::x86mmx)
1910         RC = &X86::VR64RegClass;
1911       else
1912         llvm_unreachable("Unknown argument type!");
1913
1914       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1915       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1916
1917       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1918       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1919       // right size.
1920       if (VA.getLocInfo() == CCValAssign::SExt)
1921         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1922                                DAG.getValueType(VA.getValVT()));
1923       else if (VA.getLocInfo() == CCValAssign::ZExt)
1924         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1925                                DAG.getValueType(VA.getValVT()));
1926       else if (VA.getLocInfo() == CCValAssign::BCvt)
1927         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1928
1929       if (VA.isExtInLoc()) {
1930         // Handle MMX values passed in XMM regs.
1931         if (RegVT.isVector()) {
1932           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1933                                  ArgValue);
1934         } else
1935           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1936       }
1937     } else {
1938       assert(VA.isMemLoc());
1939       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1940     }
1941
1942     // If value is passed via pointer - do a load.
1943     if (VA.getLocInfo() == CCValAssign::Indirect)
1944       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1945                              MachinePointerInfo(), false, false, false, 0);
1946
1947     InVals.push_back(ArgValue);
1948   }
1949
1950   // The x86-64 ABI for returning structs by value requires that we copy
1951   // the sret argument into %rax for the return. Save the argument into
1952   // a virtual register so that we can access it from the return points.
1953   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1954     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1955     unsigned Reg = FuncInfo->getSRetReturnReg();
1956     if (!Reg) {
1957       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1958       FuncInfo->setSRetReturnReg(Reg);
1959     }
1960     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1961     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1962   }
1963
1964   unsigned StackSize = CCInfo.getNextStackOffset();
1965   // Align stack specially for tail calls.
1966   if (FuncIsMadeTailCallSafe(CallConv,
1967                              MF.getTarget().Options.GuaranteedTailCallOpt))
1968     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1969
1970   // If the function takes variable number of arguments, make a frame index for
1971   // the start of the first vararg value... for expansion of llvm.va_start.
1972   if (isVarArg) {
1973     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1974                     CallConv != CallingConv::X86_ThisCall)) {
1975       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1976     }
1977     if (Is64Bit) {
1978       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1979
1980       // FIXME: We should really autogenerate these arrays
1981       static const uint16_t GPR64ArgRegsWin64[] = {
1982         X86::RCX, X86::RDX, X86::R8,  X86::R9
1983       };
1984       static const uint16_t GPR64ArgRegs64Bit[] = {
1985         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1986       };
1987       static const uint16_t XMMArgRegs64Bit[] = {
1988         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1989         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1990       };
1991       const uint16_t *GPR64ArgRegs;
1992       unsigned NumXMMRegs = 0;
1993
1994       if (IsWin64) {
1995         // The XMM registers which might contain var arg parameters are shadowed
1996         // in their paired GPR.  So we only need to save the GPR to their home
1997         // slots.
1998         TotalNumIntRegs = 4;
1999         GPR64ArgRegs = GPR64ArgRegsWin64;
2000       } else {
2001         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2002         GPR64ArgRegs = GPR64ArgRegs64Bit;
2003
2004         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2005                                                 TotalNumXMMRegs);
2006       }
2007       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2008                                                        TotalNumIntRegs);
2009
2010       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2011       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2012              "SSE register cannot be used when SSE is disabled!");
2013       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2014                NoImplicitFloatOps) &&
2015              "SSE register cannot be used when SSE is disabled!");
2016       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2017           !Subtarget->hasSSE1())
2018         // Kernel mode asks for SSE to be disabled, so don't push them
2019         // on the stack.
2020         TotalNumXMMRegs = 0;
2021
2022       if (IsWin64) {
2023         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2024         // Get to the caller-allocated home save location.  Add 8 to account
2025         // for the return address.
2026         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2027         FuncInfo->setRegSaveFrameIndex(
2028           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2029         // Fixup to set vararg frame on shadow area (4 x i64).
2030         if (NumIntRegs < 4)
2031           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2032       } else {
2033         // For X86-64, if there are vararg parameters that are passed via
2034         // registers, then we must store them to their spots on the stack so
2035         // they may be loaded by deferencing the result of va_next.
2036         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2037         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2038         FuncInfo->setRegSaveFrameIndex(
2039           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2040                                false));
2041       }
2042
2043       // Store the integer parameter registers.
2044       SmallVector<SDValue, 8> MemOps;
2045       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2046                                         getPointerTy());
2047       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2048       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2049         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2050                                   DAG.getIntPtrConstant(Offset));
2051         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2052                                      &X86::GR64RegClass);
2053         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2054         SDValue Store =
2055           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2056                        MachinePointerInfo::getFixedStack(
2057                          FuncInfo->getRegSaveFrameIndex(), Offset),
2058                        false, false, 0);
2059         MemOps.push_back(Store);
2060         Offset += 8;
2061       }
2062
2063       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2064         // Now store the XMM (fp + vector) parameter registers.
2065         SmallVector<SDValue, 11> SaveXMMOps;
2066         SaveXMMOps.push_back(Chain);
2067
2068         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2069         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2070         SaveXMMOps.push_back(ALVal);
2071
2072         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2073                                FuncInfo->getRegSaveFrameIndex()));
2074         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2075                                FuncInfo->getVarArgsFPOffset()));
2076
2077         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2078           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2079                                        &X86::VR128RegClass);
2080           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2081           SaveXMMOps.push_back(Val);
2082         }
2083         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2084                                      MVT::Other,
2085                                      &SaveXMMOps[0], SaveXMMOps.size()));
2086       }
2087
2088       if (!MemOps.empty())
2089         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2090                             &MemOps[0], MemOps.size());
2091     }
2092   }
2093
2094   // Some CCs need callee pop.
2095   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2096                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2097     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2098   } else {
2099     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2100     // If this is an sret function, the return should pop the hidden pointer.
2101     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2102         argsAreStructReturn(Ins) == StackStructReturn)
2103       FuncInfo->setBytesToPopOnReturn(4);
2104   }
2105
2106   if (!Is64Bit) {
2107     // RegSaveFrameIndex is X86-64 only.
2108     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2109     if (CallConv == CallingConv::X86_FastCall ||
2110         CallConv == CallingConv::X86_ThisCall)
2111       // fastcc functions can't have varargs.
2112       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2113   }
2114
2115   FuncInfo->setArgumentStackSize(StackSize);
2116
2117   return Chain;
2118 }
2119
2120 SDValue
2121 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2122                                     SDValue StackPtr, SDValue Arg,
2123                                     DebugLoc dl, SelectionDAG &DAG,
2124                                     const CCValAssign &VA,
2125                                     ISD::ArgFlagsTy Flags) const {
2126   unsigned LocMemOffset = VA.getLocMemOffset();
2127   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2128   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2129   if (Flags.isByVal())
2130     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2131
2132   return DAG.getStore(Chain, dl, Arg, PtrOff,
2133                       MachinePointerInfo::getStack(LocMemOffset),
2134                       false, false, 0);
2135 }
2136
2137 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2138 /// optimization is performed and it is required.
2139 SDValue
2140 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2141                                            SDValue &OutRetAddr, SDValue Chain,
2142                                            bool IsTailCall, bool Is64Bit,
2143                                            int FPDiff, DebugLoc dl) const {
2144   // Adjust the Return address stack slot.
2145   EVT VT = getPointerTy();
2146   OutRetAddr = getReturnAddressFrameIndex(DAG);
2147
2148   // Load the "old" Return address.
2149   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2150                            false, false, false, 0);
2151   return SDValue(OutRetAddr.getNode(), 1);
2152 }
2153
2154 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2155 /// optimization is performed and it is required (FPDiff!=0).
2156 static SDValue
2157 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2158                          SDValue Chain, SDValue RetAddrFrIdx,
2159                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2160   // Store the return address to the appropriate stack slot.
2161   if (!FPDiff) return Chain;
2162   // Calculate the new stack slot for the return address.
2163   int SlotSize = Is64Bit ? 8 : 4;
2164   int NewReturnAddrFI =
2165     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2166   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2167   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2168   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2169                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2170                        false, false, 0);
2171   return Chain;
2172 }
2173
2174 SDValue
2175 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2176                              SmallVectorImpl<SDValue> &InVals) const {
2177   SelectionDAG &DAG                     = CLI.DAG;
2178   DebugLoc &dl                          = CLI.DL;
2179   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2180   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2181   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2182   SDValue Chain                         = CLI.Chain;
2183   SDValue Callee                        = CLI.Callee;
2184   CallingConv::ID CallConv              = CLI.CallConv;
2185   bool &isTailCall                      = CLI.IsTailCall;
2186   bool isVarArg                         = CLI.IsVarArg;
2187
2188   MachineFunction &MF = DAG.getMachineFunction();
2189   bool Is64Bit        = Subtarget->is64Bit();
2190   bool IsWin64        = Subtarget->isTargetWin64();
2191   bool IsWindows      = Subtarget->isTargetWindows();
2192   StructReturnType SR = callIsStructReturn(Outs);
2193   bool IsSibcall      = false;
2194
2195   if (MF.getTarget().Options.DisableTailCalls)
2196     isTailCall = false;
2197
2198   if (isTailCall) {
2199     // Check if it's really possible to do a tail call.
2200     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2201                     isVarArg, SR != NotStructReturn,
2202                     MF.getFunction()->hasStructRetAttr(),
2203                     Outs, OutVals, Ins, DAG);
2204
2205     // Sibcalls are automatically detected tailcalls which do not require
2206     // ABI changes.
2207     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2208       IsSibcall = true;
2209
2210     if (isTailCall)
2211       ++NumTailCalls;
2212   }
2213
2214   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2215          "Var args not supported with calling convention fastcc or ghc");
2216
2217   // Analyze operands of the call, assigning locations to each operand.
2218   SmallVector<CCValAssign, 16> ArgLocs;
2219   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2220                  ArgLocs, *DAG.getContext());
2221
2222   // Allocate shadow area for Win64
2223   if (IsWin64) {
2224     CCInfo.AllocateStack(32, 8);
2225   }
2226
2227   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2228
2229   // Get a count of how many bytes are to be pushed on the stack.
2230   unsigned NumBytes = CCInfo.getNextStackOffset();
2231   if (IsSibcall)
2232     // This is a sibcall. The memory operands are available in caller's
2233     // own caller's stack.
2234     NumBytes = 0;
2235   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2236            IsTailCallConvention(CallConv))
2237     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2238
2239   int FPDiff = 0;
2240   if (isTailCall && !IsSibcall) {
2241     // Lower arguments at fp - stackoffset + fpdiff.
2242     unsigned NumBytesCallerPushed =
2243       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2244     FPDiff = NumBytesCallerPushed - NumBytes;
2245
2246     // Set the delta of movement of the returnaddr stackslot.
2247     // But only set if delta is greater than previous delta.
2248     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2249       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2250   }
2251
2252   if (!IsSibcall)
2253     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2254
2255   SDValue RetAddrFrIdx;
2256   // Load return address for tail calls.
2257   if (isTailCall && FPDiff)
2258     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2259                                     Is64Bit, FPDiff, dl);
2260
2261   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2262   SmallVector<SDValue, 8> MemOpChains;
2263   SDValue StackPtr;
2264
2265   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2266   // of tail call optimization arguments are handle later.
2267   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2268     CCValAssign &VA = ArgLocs[i];
2269     EVT RegVT = VA.getLocVT();
2270     SDValue Arg = OutVals[i];
2271     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2272     bool isByVal = Flags.isByVal();
2273
2274     // Promote the value if needed.
2275     switch (VA.getLocInfo()) {
2276     default: llvm_unreachable("Unknown loc info!");
2277     case CCValAssign::Full: break;
2278     case CCValAssign::SExt:
2279       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2280       break;
2281     case CCValAssign::ZExt:
2282       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2283       break;
2284     case CCValAssign::AExt:
2285       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2286         // Special case: passing MMX values in XMM registers.
2287         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2288         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2289         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2290       } else
2291         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2292       break;
2293     case CCValAssign::BCvt:
2294       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2295       break;
2296     case CCValAssign::Indirect: {
2297       // Store the argument.
2298       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2299       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2300       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2301                            MachinePointerInfo::getFixedStack(FI),
2302                            false, false, 0);
2303       Arg = SpillSlot;
2304       break;
2305     }
2306     }
2307
2308     if (VA.isRegLoc()) {
2309       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2310       if (isVarArg && IsWin64) {
2311         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2312         // shadow reg if callee is a varargs function.
2313         unsigned ShadowReg = 0;
2314         switch (VA.getLocReg()) {
2315         case X86::XMM0: ShadowReg = X86::RCX; break;
2316         case X86::XMM1: ShadowReg = X86::RDX; break;
2317         case X86::XMM2: ShadowReg = X86::R8; break;
2318         case X86::XMM3: ShadowReg = X86::R9; break;
2319         }
2320         if (ShadowReg)
2321           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2322       }
2323     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2324       assert(VA.isMemLoc());
2325       if (StackPtr.getNode() == 0)
2326         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2327       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2328                                              dl, DAG, VA, Flags));
2329     }
2330   }
2331
2332   if (!MemOpChains.empty())
2333     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2334                         &MemOpChains[0], MemOpChains.size());
2335
2336   if (Subtarget->isPICStyleGOT()) {
2337     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2338     // GOT pointer.
2339     if (!isTailCall) {
2340       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2341                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2342     } else {
2343       // If we are tail calling and generating PIC/GOT style code load the
2344       // address of the callee into ECX. The value in ecx is used as target of
2345       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2346       // for tail calls on PIC/GOT architectures. Normally we would just put the
2347       // address of GOT into ebx and then call target@PLT. But for tail calls
2348       // ebx would be restored (since ebx is callee saved) before jumping to the
2349       // target@PLT.
2350
2351       // Note: The actual moving to ECX is done further down.
2352       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2353       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2354           !G->getGlobal()->hasProtectedVisibility())
2355         Callee = LowerGlobalAddress(Callee, DAG);
2356       else if (isa<ExternalSymbolSDNode>(Callee))
2357         Callee = LowerExternalSymbol(Callee, DAG);
2358     }
2359   }
2360
2361   if (Is64Bit && isVarArg && !IsWin64) {
2362     // From AMD64 ABI document:
2363     // For calls that may call functions that use varargs or stdargs
2364     // (prototype-less calls or calls to functions containing ellipsis (...) in
2365     // the declaration) %al is used as hidden argument to specify the number
2366     // of SSE registers used. The contents of %al do not need to match exactly
2367     // the number of registers, but must be an ubound on the number of SSE
2368     // registers used and is in the range 0 - 8 inclusive.
2369
2370     // Count the number of XMM registers allocated.
2371     static const uint16_t XMMArgRegs[] = {
2372       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2373       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2374     };
2375     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2376     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2377            && "SSE registers cannot be used when SSE is disabled");
2378
2379     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2380                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2381   }
2382
2383   // For tail calls lower the arguments to the 'real' stack slot.
2384   if (isTailCall) {
2385     // Force all the incoming stack arguments to be loaded from the stack
2386     // before any new outgoing arguments are stored to the stack, because the
2387     // outgoing stack slots may alias the incoming argument stack slots, and
2388     // the alias isn't otherwise explicit. This is slightly more conservative
2389     // than necessary, because it means that each store effectively depends
2390     // on every argument instead of just those arguments it would clobber.
2391     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2392
2393     SmallVector<SDValue, 8> MemOpChains2;
2394     SDValue FIN;
2395     int FI = 0;
2396     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2397       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2398         CCValAssign &VA = ArgLocs[i];
2399         if (VA.isRegLoc())
2400           continue;
2401         assert(VA.isMemLoc());
2402         SDValue Arg = OutVals[i];
2403         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2404         // Create frame index.
2405         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2406         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2407         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2408         FIN = DAG.getFrameIndex(FI, getPointerTy());
2409
2410         if (Flags.isByVal()) {
2411           // Copy relative to framepointer.
2412           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2413           if (StackPtr.getNode() == 0)
2414             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2415                                           getPointerTy());
2416           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2417
2418           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2419                                                            ArgChain,
2420                                                            Flags, DAG, dl));
2421         } else {
2422           // Store relative to framepointer.
2423           MemOpChains2.push_back(
2424             DAG.getStore(ArgChain, dl, Arg, FIN,
2425                          MachinePointerInfo::getFixedStack(FI),
2426                          false, false, 0));
2427         }
2428       }
2429     }
2430
2431     if (!MemOpChains2.empty())
2432       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433                           &MemOpChains2[0], MemOpChains2.size());
2434
2435     // Store the return address to the appropriate stack slot.
2436     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2437                                      FPDiff, dl);
2438   }
2439
2440   // Build a sequence of copy-to-reg nodes chained together with token chain
2441   // and flag operands which copy the outgoing args into registers.
2442   SDValue InFlag;
2443   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2444     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2445                              RegsToPass[i].second, InFlag);
2446     InFlag = Chain.getValue(1);
2447   }
2448
2449   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2450     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2451     // In the 64-bit large code model, we have to make all calls
2452     // through a register, since the call instruction's 32-bit
2453     // pc-relative offset may not be large enough to hold the whole
2454     // address.
2455   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2456     // If the callee is a GlobalAddress node (quite common, every direct call
2457     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2458     // it.
2459
2460     // We should use extra load for direct calls to dllimported functions in
2461     // non-JIT mode.
2462     const GlobalValue *GV = G->getGlobal();
2463     if (!GV->hasDLLImportLinkage()) {
2464       unsigned char OpFlags = 0;
2465       bool ExtraLoad = false;
2466       unsigned WrapperKind = ISD::DELETED_NODE;
2467
2468       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2469       // external symbols most go through the PLT in PIC mode.  If the symbol
2470       // has hidden or protected visibility, or if it is static or local, then
2471       // we don't need to use the PLT - we can directly call it.
2472       if (Subtarget->isTargetELF() &&
2473           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2474           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2475         OpFlags = X86II::MO_PLT;
2476       } else if (Subtarget->isPICStyleStubAny() &&
2477                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2478                  (!Subtarget->getTargetTriple().isMacOSX() ||
2479                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2480         // PC-relative references to external symbols should go through $stub,
2481         // unless we're building with the leopard linker or later, which
2482         // automatically synthesizes these stubs.
2483         OpFlags = X86II::MO_DARWIN_STUB;
2484       } else if (Subtarget->isPICStyleRIPRel() &&
2485                  isa<Function>(GV) &&
2486                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2487         // If the function is marked as non-lazy, generate an indirect call
2488         // which loads from the GOT directly. This avoids runtime overhead
2489         // at the cost of eager binding (and one extra byte of encoding).
2490         OpFlags = X86II::MO_GOTPCREL;
2491         WrapperKind = X86ISD::WrapperRIP;
2492         ExtraLoad = true;
2493       }
2494
2495       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2496                                           G->getOffset(), OpFlags);
2497
2498       // Add a wrapper if needed.
2499       if (WrapperKind != ISD::DELETED_NODE)
2500         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2501       // Add extra indirection if needed.
2502       if (ExtraLoad)
2503         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2504                              MachinePointerInfo::getGOT(),
2505                              false, false, false, 0);
2506     }
2507   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2508     unsigned char OpFlags = 0;
2509
2510     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2511     // external symbols should go through the PLT.
2512     if (Subtarget->isTargetELF() &&
2513         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2514       OpFlags = X86II::MO_PLT;
2515     } else if (Subtarget->isPICStyleStubAny() &&
2516                (!Subtarget->getTargetTriple().isMacOSX() ||
2517                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2518       // PC-relative references to external symbols should go through $stub,
2519       // unless we're building with the leopard linker or later, which
2520       // automatically synthesizes these stubs.
2521       OpFlags = X86II::MO_DARWIN_STUB;
2522     }
2523
2524     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2525                                          OpFlags);
2526   }
2527
2528   // Returns a chain & a flag for retval copy to use.
2529   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2530   SmallVector<SDValue, 8> Ops;
2531
2532   if (!IsSibcall && isTailCall) {
2533     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2534                            DAG.getIntPtrConstant(0, true), InFlag);
2535     InFlag = Chain.getValue(1);
2536   }
2537
2538   Ops.push_back(Chain);
2539   Ops.push_back(Callee);
2540
2541   if (isTailCall)
2542     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2543
2544   // Add argument registers to the end of the list so that they are known live
2545   // into the call.
2546   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2547     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2548                                   RegsToPass[i].second.getValueType()));
2549
2550   // Add a register mask operand representing the call-preserved registers.
2551   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2552   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2553   assert(Mask && "Missing call preserved mask for calling convention");
2554   Ops.push_back(DAG.getRegisterMask(Mask));
2555
2556   if (InFlag.getNode())
2557     Ops.push_back(InFlag);
2558
2559   if (isTailCall) {
2560     // We used to do:
2561     //// If this is the first return lowered for this function, add the regs
2562     //// to the liveout set for the function.
2563     // This isn't right, although it's probably harmless on x86; liveouts
2564     // should be computed from returns not tail calls.  Consider a void
2565     // function making a tail call to a function returning int.
2566     return DAG.getNode(X86ISD::TC_RETURN, dl,
2567                        NodeTys, &Ops[0], Ops.size());
2568   }
2569
2570   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2571   InFlag = Chain.getValue(1);
2572
2573   // Create the CALLSEQ_END node.
2574   unsigned NumBytesForCalleeToPush;
2575   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2576                        getTargetMachine().Options.GuaranteedTailCallOpt))
2577     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2578   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2579            SR == StackStructReturn)
2580     // If this is a call to a struct-return function, the callee
2581     // pops the hidden struct pointer, so we have to push it back.
2582     // This is common for Darwin/X86, Linux & Mingw32 targets.
2583     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2584     NumBytesForCalleeToPush = 4;
2585   else
2586     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2587
2588   // Returns a flag for retval copy to use.
2589   if (!IsSibcall) {
2590     Chain = DAG.getCALLSEQ_END(Chain,
2591                                DAG.getIntPtrConstant(NumBytes, true),
2592                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2593                                                      true),
2594                                InFlag);
2595     InFlag = Chain.getValue(1);
2596   }
2597
2598   // Handle result values, copying them out of physregs into vregs that we
2599   // return.
2600   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2601                          Ins, dl, DAG, InVals);
2602 }
2603
2604
2605 //===----------------------------------------------------------------------===//
2606 //                Fast Calling Convention (tail call) implementation
2607 //===----------------------------------------------------------------------===//
2608
2609 //  Like std call, callee cleans arguments, convention except that ECX is
2610 //  reserved for storing the tail called function address. Only 2 registers are
2611 //  free for argument passing (inreg). Tail call optimization is performed
2612 //  provided:
2613 //                * tailcallopt is enabled
2614 //                * caller/callee are fastcc
2615 //  On X86_64 architecture with GOT-style position independent code only local
2616 //  (within module) calls are supported at the moment.
2617 //  To keep the stack aligned according to platform abi the function
2618 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2619 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2620 //  If a tail called function callee has more arguments than the caller the
2621 //  caller needs to make sure that there is room to move the RETADDR to. This is
2622 //  achieved by reserving an area the size of the argument delta right after the
2623 //  original REtADDR, but before the saved framepointer or the spilled registers
2624 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2625 //  stack layout:
2626 //    arg1
2627 //    arg2
2628 //    RETADDR
2629 //    [ new RETADDR
2630 //      move area ]
2631 //    (possible EBP)
2632 //    ESI
2633 //    EDI
2634 //    local1 ..
2635
2636 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2637 /// for a 16 byte align requirement.
2638 unsigned
2639 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2640                                                SelectionDAG& DAG) const {
2641   MachineFunction &MF = DAG.getMachineFunction();
2642   const TargetMachine &TM = MF.getTarget();
2643   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2644   unsigned StackAlignment = TFI.getStackAlignment();
2645   uint64_t AlignMask = StackAlignment - 1;
2646   int64_t Offset = StackSize;
2647   uint64_t SlotSize = TD->getPointerSize();
2648   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2649     // Number smaller than 12 so just add the difference.
2650     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2651   } else {
2652     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2653     Offset = ((~AlignMask) & Offset) + StackAlignment +
2654       (StackAlignment-SlotSize);
2655   }
2656   return Offset;
2657 }
2658
2659 /// MatchingStackOffset - Return true if the given stack call argument is
2660 /// already available in the same position (relatively) of the caller's
2661 /// incoming argument stack.
2662 static
2663 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2664                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2665                          const X86InstrInfo *TII) {
2666   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2667   int FI = INT_MAX;
2668   if (Arg.getOpcode() == ISD::CopyFromReg) {
2669     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2670     if (!TargetRegisterInfo::isVirtualRegister(VR))
2671       return false;
2672     MachineInstr *Def = MRI->getVRegDef(VR);
2673     if (!Def)
2674       return false;
2675     if (!Flags.isByVal()) {
2676       if (!TII->isLoadFromStackSlot(Def, FI))
2677         return false;
2678     } else {
2679       unsigned Opcode = Def->getOpcode();
2680       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2681           Def->getOperand(1).isFI()) {
2682         FI = Def->getOperand(1).getIndex();
2683         Bytes = Flags.getByValSize();
2684       } else
2685         return false;
2686     }
2687   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2688     if (Flags.isByVal())
2689       // ByVal argument is passed in as a pointer but it's now being
2690       // dereferenced. e.g.
2691       // define @foo(%struct.X* %A) {
2692       //   tail call @bar(%struct.X* byval %A)
2693       // }
2694       return false;
2695     SDValue Ptr = Ld->getBasePtr();
2696     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2697     if (!FINode)
2698       return false;
2699     FI = FINode->getIndex();
2700   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2701     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2702     FI = FINode->getIndex();
2703     Bytes = Flags.getByValSize();
2704   } else
2705     return false;
2706
2707   assert(FI != INT_MAX);
2708   if (!MFI->isFixedObjectIndex(FI))
2709     return false;
2710   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2711 }
2712
2713 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2714 /// for tail call optimization. Targets which want to do tail call
2715 /// optimization should implement this function.
2716 bool
2717 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2718                                                      CallingConv::ID CalleeCC,
2719                                                      bool isVarArg,
2720                                                      bool isCalleeStructRet,
2721                                                      bool isCallerStructRet,
2722                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2723                                     const SmallVectorImpl<SDValue> &OutVals,
2724                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2725                                                      SelectionDAG& DAG) const {
2726   if (!IsTailCallConvention(CalleeCC) &&
2727       CalleeCC != CallingConv::C)
2728     return false;
2729
2730   // If -tailcallopt is specified, make fastcc functions tail-callable.
2731   const MachineFunction &MF = DAG.getMachineFunction();
2732   const Function *CallerF = DAG.getMachineFunction().getFunction();
2733   CallingConv::ID CallerCC = CallerF->getCallingConv();
2734   bool CCMatch = CallerCC == CalleeCC;
2735
2736   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2737     if (IsTailCallConvention(CalleeCC) && CCMatch)
2738       return true;
2739     return false;
2740   }
2741
2742   // Look for obvious safe cases to perform tail call optimization that do not
2743   // require ABI changes. This is what gcc calls sibcall.
2744
2745   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2746   // emit a special epilogue.
2747   if (RegInfo->needsStackRealignment(MF))
2748     return false;
2749
2750   // Also avoid sibcall optimization if either caller or callee uses struct
2751   // return semantics.
2752   if (isCalleeStructRet || isCallerStructRet)
2753     return false;
2754
2755   // An stdcall caller is expected to clean up its arguments; the callee
2756   // isn't going to do that.
2757   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2758     return false;
2759
2760   // Do not sibcall optimize vararg calls unless all arguments are passed via
2761   // registers.
2762   if (isVarArg && !Outs.empty()) {
2763
2764     // Optimizing for varargs on Win64 is unlikely to be safe without
2765     // additional testing.
2766     if (Subtarget->isTargetWin64())
2767       return false;
2768
2769     SmallVector<CCValAssign, 16> ArgLocs;
2770     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2771                    getTargetMachine(), ArgLocs, *DAG.getContext());
2772
2773     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2774     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2775       if (!ArgLocs[i].isRegLoc())
2776         return false;
2777   }
2778
2779   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2780   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2781   // this into a sibcall.
2782   bool Unused = false;
2783   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2784     if (!Ins[i].Used) {
2785       Unused = true;
2786       break;
2787     }
2788   }
2789   if (Unused) {
2790     SmallVector<CCValAssign, 16> RVLocs;
2791     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2792                    getTargetMachine(), RVLocs, *DAG.getContext());
2793     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2794     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2795       CCValAssign &VA = RVLocs[i];
2796       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2797         return false;
2798     }
2799   }
2800
2801   // If the calling conventions do not match, then we'd better make sure the
2802   // results are returned in the same way as what the caller expects.
2803   if (!CCMatch) {
2804     SmallVector<CCValAssign, 16> RVLocs1;
2805     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2806                     getTargetMachine(), RVLocs1, *DAG.getContext());
2807     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2808
2809     SmallVector<CCValAssign, 16> RVLocs2;
2810     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2811                     getTargetMachine(), RVLocs2, *DAG.getContext());
2812     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2813
2814     if (RVLocs1.size() != RVLocs2.size())
2815       return false;
2816     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2817       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2818         return false;
2819       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2820         return false;
2821       if (RVLocs1[i].isRegLoc()) {
2822         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2823           return false;
2824       } else {
2825         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2826           return false;
2827       }
2828     }
2829   }
2830
2831   // If the callee takes no arguments then go on to check the results of the
2832   // call.
2833   if (!Outs.empty()) {
2834     // Check if stack adjustment is needed. For now, do not do this if any
2835     // argument is passed on the stack.
2836     SmallVector<CCValAssign, 16> ArgLocs;
2837     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2838                    getTargetMachine(), ArgLocs, *DAG.getContext());
2839
2840     // Allocate shadow area for Win64
2841     if (Subtarget->isTargetWin64()) {
2842       CCInfo.AllocateStack(32, 8);
2843     }
2844
2845     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2846     if (CCInfo.getNextStackOffset()) {
2847       MachineFunction &MF = DAG.getMachineFunction();
2848       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2849         return false;
2850
2851       // Check if the arguments are already laid out in the right way as
2852       // the caller's fixed stack objects.
2853       MachineFrameInfo *MFI = MF.getFrameInfo();
2854       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2855       const X86InstrInfo *TII =
2856         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2857       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2858         CCValAssign &VA = ArgLocs[i];
2859         SDValue Arg = OutVals[i];
2860         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2861         if (VA.getLocInfo() == CCValAssign::Indirect)
2862           return false;
2863         if (!VA.isRegLoc()) {
2864           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2865                                    MFI, MRI, TII))
2866             return false;
2867         }
2868       }
2869     }
2870
2871     // If the tailcall address may be in a register, then make sure it's
2872     // possible to register allocate for it. In 32-bit, the call address can
2873     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2874     // callee-saved registers are restored. These happen to be the same
2875     // registers used to pass 'inreg' arguments so watch out for those.
2876     if (!Subtarget->is64Bit() &&
2877         !isa<GlobalAddressSDNode>(Callee) &&
2878         !isa<ExternalSymbolSDNode>(Callee)) {
2879       unsigned NumInRegs = 0;
2880       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2881         CCValAssign &VA = ArgLocs[i];
2882         if (!VA.isRegLoc())
2883           continue;
2884         unsigned Reg = VA.getLocReg();
2885         switch (Reg) {
2886         default: break;
2887         case X86::EAX: case X86::EDX: case X86::ECX:
2888           if (++NumInRegs == 3)
2889             return false;
2890           break;
2891         }
2892       }
2893     }
2894   }
2895
2896   return true;
2897 }
2898
2899 FastISel *
2900 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2901                                   const TargetLibraryInfo *libInfo) const {
2902   return X86::createFastISel(funcInfo, libInfo);
2903 }
2904
2905
2906 //===----------------------------------------------------------------------===//
2907 //                           Other Lowering Hooks
2908 //===----------------------------------------------------------------------===//
2909
2910 static bool MayFoldLoad(SDValue Op) {
2911   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2912 }
2913
2914 static bool MayFoldIntoStore(SDValue Op) {
2915   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2916 }
2917
2918 static bool isTargetShuffle(unsigned Opcode) {
2919   switch(Opcode) {
2920   default: return false;
2921   case X86ISD::PSHUFD:
2922   case X86ISD::PSHUFHW:
2923   case X86ISD::PSHUFLW:
2924   case X86ISD::SHUFP:
2925   case X86ISD::PALIGN:
2926   case X86ISD::MOVLHPS:
2927   case X86ISD::MOVLHPD:
2928   case X86ISD::MOVHLPS:
2929   case X86ISD::MOVLPS:
2930   case X86ISD::MOVLPD:
2931   case X86ISD::MOVSHDUP:
2932   case X86ISD::MOVSLDUP:
2933   case X86ISD::MOVDDUP:
2934   case X86ISD::MOVSS:
2935   case X86ISD::MOVSD:
2936   case X86ISD::UNPCKL:
2937   case X86ISD::UNPCKH:
2938   case X86ISD::VPERMILP:
2939   case X86ISD::VPERM2X128:
2940   case X86ISD::VPERMI:
2941     return true;
2942   }
2943 }
2944
2945 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2946                                     SDValue V1, SelectionDAG &DAG) {
2947   switch(Opc) {
2948   default: llvm_unreachable("Unknown x86 shuffle node");
2949   case X86ISD::MOVSHDUP:
2950   case X86ISD::MOVSLDUP:
2951   case X86ISD::MOVDDUP:
2952     return DAG.getNode(Opc, dl, VT, V1);
2953   }
2954 }
2955
2956 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2957                                     SDValue V1, unsigned TargetMask,
2958                                     SelectionDAG &DAG) {
2959   switch(Opc) {
2960   default: llvm_unreachable("Unknown x86 shuffle node");
2961   case X86ISD::PSHUFD:
2962   case X86ISD::PSHUFHW:
2963   case X86ISD::PSHUFLW:
2964   case X86ISD::VPERMILP:
2965   case X86ISD::VPERMI:
2966     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2967   }
2968 }
2969
2970 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2971                                     SDValue V1, SDValue V2, unsigned TargetMask,
2972                                     SelectionDAG &DAG) {
2973   switch(Opc) {
2974   default: llvm_unreachable("Unknown x86 shuffle node");
2975   case X86ISD::PALIGN:
2976   case X86ISD::SHUFP:
2977   case X86ISD::VPERM2X128:
2978     return DAG.getNode(Opc, dl, VT, V1, V2,
2979                        DAG.getConstant(TargetMask, MVT::i8));
2980   }
2981 }
2982
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2985   switch(Opc) {
2986   default: llvm_unreachable("Unknown x86 shuffle node");
2987   case X86ISD::MOVLHPS:
2988   case X86ISD::MOVLHPD:
2989   case X86ISD::MOVHLPS:
2990   case X86ISD::MOVLPS:
2991   case X86ISD::MOVLPD:
2992   case X86ISD::MOVSS:
2993   case X86ISD::MOVSD:
2994   case X86ISD::UNPCKL:
2995   case X86ISD::UNPCKH:
2996     return DAG.getNode(Opc, dl, VT, V1, V2);
2997   }
2998 }
2999
3000 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3001   MachineFunction &MF = DAG.getMachineFunction();
3002   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3003   int ReturnAddrIndex = FuncInfo->getRAIndex();
3004
3005   if (ReturnAddrIndex == 0) {
3006     // Set up a frame object for the return address.
3007     uint64_t SlotSize = TD->getPointerSize();
3008     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3009                                                            false);
3010     FuncInfo->setRAIndex(ReturnAddrIndex);
3011   }
3012
3013   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3014 }
3015
3016
3017 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3018                                        bool hasSymbolicDisplacement) {
3019   // Offset should fit into 32 bit immediate field.
3020   if (!isInt<32>(Offset))
3021     return false;
3022
3023   // If we don't have a symbolic displacement - we don't have any extra
3024   // restrictions.
3025   if (!hasSymbolicDisplacement)
3026     return true;
3027
3028   // FIXME: Some tweaks might be needed for medium code model.
3029   if (M != CodeModel::Small && M != CodeModel::Kernel)
3030     return false;
3031
3032   // For small code model we assume that latest object is 16MB before end of 31
3033   // bits boundary. We may also accept pretty large negative constants knowing
3034   // that all objects are in the positive half of address space.
3035   if (M == CodeModel::Small && Offset < 16*1024*1024)
3036     return true;
3037
3038   // For kernel code model we know that all object resist in the negative half
3039   // of 32bits address space. We may not accept negative offsets, since they may
3040   // be just off and we may accept pretty large positive ones.
3041   if (M == CodeModel::Kernel && Offset > 0)
3042     return true;
3043
3044   return false;
3045 }
3046
3047 /// isCalleePop - Determines whether the callee is required to pop its
3048 /// own arguments. Callee pop is necessary to support tail calls.
3049 bool X86::isCalleePop(CallingConv::ID CallingConv,
3050                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3051   if (IsVarArg)
3052     return false;
3053
3054   switch (CallingConv) {
3055   default:
3056     return false;
3057   case CallingConv::X86_StdCall:
3058     return !is64Bit;
3059   case CallingConv::X86_FastCall:
3060     return !is64Bit;
3061   case CallingConv::X86_ThisCall:
3062     return !is64Bit;
3063   case CallingConv::Fast:
3064     return TailCallOpt;
3065   case CallingConv::GHC:
3066     return TailCallOpt;
3067   }
3068 }
3069
3070 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3071 /// specific condition code, returning the condition code and the LHS/RHS of the
3072 /// comparison to make.
3073 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3074                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3075   if (!isFP) {
3076     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3077       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3078         // X > -1   -> X == 0, jump !sign.
3079         RHS = DAG.getConstant(0, RHS.getValueType());
3080         return X86::COND_NS;
3081       }
3082       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3083         // X < 0   -> X == 0, jump on sign.
3084         return X86::COND_S;
3085       }
3086       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3087         // X < 1   -> X <= 0
3088         RHS = DAG.getConstant(0, RHS.getValueType());
3089         return X86::COND_LE;
3090       }
3091     }
3092
3093     switch (SetCCOpcode) {
3094     default: llvm_unreachable("Invalid integer condition!");
3095     case ISD::SETEQ:  return X86::COND_E;
3096     case ISD::SETGT:  return X86::COND_G;
3097     case ISD::SETGE:  return X86::COND_GE;
3098     case ISD::SETLT:  return X86::COND_L;
3099     case ISD::SETLE:  return X86::COND_LE;
3100     case ISD::SETNE:  return X86::COND_NE;
3101     case ISD::SETULT: return X86::COND_B;
3102     case ISD::SETUGT: return X86::COND_A;
3103     case ISD::SETULE: return X86::COND_BE;
3104     case ISD::SETUGE: return X86::COND_AE;
3105     }
3106   }
3107
3108   // First determine if it is required or is profitable to flip the operands.
3109
3110   // If LHS is a foldable load, but RHS is not, flip the condition.
3111   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3112       !ISD::isNON_EXTLoad(RHS.getNode())) {
3113     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3114     std::swap(LHS, RHS);
3115   }
3116
3117   switch (SetCCOpcode) {
3118   default: break;
3119   case ISD::SETOLT:
3120   case ISD::SETOLE:
3121   case ISD::SETUGT:
3122   case ISD::SETUGE:
3123     std::swap(LHS, RHS);
3124     break;
3125   }
3126
3127   // On a floating point condition, the flags are set as follows:
3128   // ZF  PF  CF   op
3129   //  0 | 0 | 0 | X > Y
3130   //  0 | 0 | 1 | X < Y
3131   //  1 | 0 | 0 | X == Y
3132   //  1 | 1 | 1 | unordered
3133   switch (SetCCOpcode) {
3134   default: llvm_unreachable("Condcode should be pre-legalized away");
3135   case ISD::SETUEQ:
3136   case ISD::SETEQ:   return X86::COND_E;
3137   case ISD::SETOLT:              // flipped
3138   case ISD::SETOGT:
3139   case ISD::SETGT:   return X86::COND_A;
3140   case ISD::SETOLE:              // flipped
3141   case ISD::SETOGE:
3142   case ISD::SETGE:   return X86::COND_AE;
3143   case ISD::SETUGT:              // flipped
3144   case ISD::SETULT:
3145   case ISD::SETLT:   return X86::COND_B;
3146   case ISD::SETUGE:              // flipped
3147   case ISD::SETULE:
3148   case ISD::SETLE:   return X86::COND_BE;
3149   case ISD::SETONE:
3150   case ISD::SETNE:   return X86::COND_NE;
3151   case ISD::SETUO:   return X86::COND_P;
3152   case ISD::SETO:    return X86::COND_NP;
3153   case ISD::SETOEQ:
3154   case ISD::SETUNE:  return X86::COND_INVALID;
3155   }
3156 }
3157
3158 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3159 /// code. Current x86 isa includes the following FP cmov instructions:
3160 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3161 static bool hasFPCMov(unsigned X86CC) {
3162   switch (X86CC) {
3163   default:
3164     return false;
3165   case X86::COND_B:
3166   case X86::COND_BE:
3167   case X86::COND_E:
3168   case X86::COND_P:
3169   case X86::COND_A:
3170   case X86::COND_AE:
3171   case X86::COND_NE:
3172   case X86::COND_NP:
3173     return true;
3174   }
3175 }
3176
3177 /// isFPImmLegal - Returns true if the target can instruction select the
3178 /// specified FP immediate natively. If false, the legalizer will
3179 /// materialize the FP immediate as a load from a constant pool.
3180 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3181   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3182     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3183       return true;
3184   }
3185   return false;
3186 }
3187
3188 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3189 /// the specified range (L, H].
3190 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3191   return (Val < 0) || (Val >= Low && Val < Hi);
3192 }
3193
3194 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3195 /// specified value.
3196 static bool isUndefOrEqual(int Val, int CmpVal) {
3197   if (Val < 0 || Val == CmpVal)
3198     return true;
3199   return false;
3200 }
3201
3202 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3203 /// from position Pos and ending in Pos+Size, falls within the specified
3204 /// sequential range (L, L+Pos]. or is undef.
3205 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3206                                        unsigned Pos, unsigned Size, int Low) {
3207   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3208     if (!isUndefOrEqual(Mask[i], Low))
3209       return false;
3210   return true;
3211 }
3212
3213 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3214 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3215 /// the second operand.
3216 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3217   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3218     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3219   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3220     return (Mask[0] < 2 && Mask[1] < 2);
3221   return false;
3222 }
3223
3224 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3225 /// is suitable for input to PSHUFHW.
3226 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3227   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3228     return false;
3229
3230   // Lower quadword copied in order or undef.
3231   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3232     return false;
3233
3234   // Upper quadword shuffled.
3235   for (unsigned i = 4; i != 8; ++i)
3236     if (!isUndefOrInRange(Mask[i], 4, 8))
3237       return false;
3238
3239   if (VT == MVT::v16i16) {
3240     // Lower quadword copied in order or undef.
3241     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3242       return false;
3243
3244     // Upper quadword shuffled.
3245     for (unsigned i = 12; i != 16; ++i)
3246       if (!isUndefOrInRange(Mask[i], 12, 16))
3247         return false;
3248   }
3249
3250   return true;
3251 }
3252
3253 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3254 /// is suitable for input to PSHUFLW.
3255 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3256   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3257     return false;
3258
3259   // Upper quadword copied in order.
3260   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3261     return false;
3262
3263   // Lower quadword shuffled.
3264   for (unsigned i = 0; i != 4; ++i)
3265     if (!isUndefOrInRange(Mask[i], 0, 4))
3266       return false;
3267
3268   if (VT == MVT::v16i16) {
3269     // Upper quadword copied in order.
3270     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3271       return false;
3272
3273     // Lower quadword shuffled.
3274     for (unsigned i = 8; i != 12; ++i)
3275       if (!isUndefOrInRange(Mask[i], 8, 12))
3276         return false;
3277   }
3278
3279   return true;
3280 }
3281
3282 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3283 /// is suitable for input to PALIGNR.
3284 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3285                           const X86Subtarget *Subtarget) {
3286   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3287       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3288     return false;
3289
3290   unsigned NumElts = VT.getVectorNumElements();
3291   unsigned NumLanes = VT.getSizeInBits()/128;
3292   unsigned NumLaneElts = NumElts/NumLanes;
3293
3294   // Do not handle 64-bit element shuffles with palignr.
3295   if (NumLaneElts == 2)
3296     return false;
3297
3298   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3299     unsigned i;
3300     for (i = 0; i != NumLaneElts; ++i) {
3301       if (Mask[i+l] >= 0)
3302         break;
3303     }
3304
3305     // Lane is all undef, go to next lane
3306     if (i == NumLaneElts)
3307       continue;
3308
3309     int Start = Mask[i+l];
3310
3311     // Make sure its in this lane in one of the sources
3312     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3313         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3314       return false;
3315
3316     // If not lane 0, then we must match lane 0
3317     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3318       return false;
3319
3320     // Correct second source to be contiguous with first source
3321     if (Start >= (int)NumElts)
3322       Start -= NumElts - NumLaneElts;
3323
3324     // Make sure we're shifting in the right direction.
3325     if (Start <= (int)(i+l))
3326       return false;
3327
3328     Start -= i;
3329
3330     // Check the rest of the elements to see if they are consecutive.
3331     for (++i; i != NumLaneElts; ++i) {
3332       int Idx = Mask[i+l];
3333
3334       // Make sure its in this lane
3335       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3336           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3337         return false;
3338
3339       // If not lane 0, then we must match lane 0
3340       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3341         return false;
3342
3343       if (Idx >= (int)NumElts)
3344         Idx -= NumElts - NumLaneElts;
3345
3346       if (!isUndefOrEqual(Idx, Start+i))
3347         return false;
3348
3349     }
3350   }
3351
3352   return true;
3353 }
3354
3355 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3356 /// the two vector operands have swapped position.
3357 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3358                                      unsigned NumElems) {
3359   for (unsigned i = 0; i != NumElems; ++i) {
3360     int idx = Mask[i];
3361     if (idx < 0)
3362       continue;
3363     else if (idx < (int)NumElems)
3364       Mask[i] = idx + NumElems;
3365     else
3366       Mask[i] = idx - NumElems;
3367   }
3368 }
3369
3370 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3371 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3372 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3373 /// reverse of what x86 shuffles want.
3374 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3375                         bool Commuted = false) {
3376   if (!HasAVX && VT.getSizeInBits() == 256)
3377     return false;
3378
3379   unsigned NumElems = VT.getVectorNumElements();
3380   unsigned NumLanes = VT.getSizeInBits()/128;
3381   unsigned NumLaneElems = NumElems/NumLanes;
3382
3383   if (NumLaneElems != 2 && NumLaneElems != 4)
3384     return false;
3385
3386   // VSHUFPSY divides the resulting vector into 4 chunks.
3387   // The sources are also splitted into 4 chunks, and each destination
3388   // chunk must come from a different source chunk.
3389   //
3390   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3391   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3392   //
3393   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3394   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3395   //
3396   // VSHUFPDY divides the resulting vector into 4 chunks.
3397   // The sources are also splitted into 4 chunks, and each destination
3398   // chunk must come from a different source chunk.
3399   //
3400   //  SRC1 =>      X3       X2       X1       X0
3401   //  SRC2 =>      Y3       Y2       Y1       Y0
3402   //
3403   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3404   //
3405   unsigned HalfLaneElems = NumLaneElems/2;
3406   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3407     for (unsigned i = 0; i != NumLaneElems; ++i) {
3408       int Idx = Mask[i+l];
3409       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3410       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3411         return false;
3412       // For VSHUFPSY, the mask of the second half must be the same as the
3413       // first but with the appropriate offsets. This works in the same way as
3414       // VPERMILPS works with masks.
3415       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3416         continue;
3417       if (!isUndefOrEqual(Idx, Mask[i]+l))
3418         return false;
3419     }
3420   }
3421
3422   return true;
3423 }
3424
3425 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3426 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3427 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3428   unsigned NumElems = VT.getVectorNumElements();
3429
3430   if (VT.getSizeInBits() != 128)
3431     return false;
3432
3433   if (NumElems != 4)
3434     return false;
3435
3436   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3437   return isUndefOrEqual(Mask[0], 6) &&
3438          isUndefOrEqual(Mask[1], 7) &&
3439          isUndefOrEqual(Mask[2], 2) &&
3440          isUndefOrEqual(Mask[3], 3);
3441 }
3442
3443 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3444 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3445 /// <2, 3, 2, 3>
3446 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3447   unsigned NumElems = VT.getVectorNumElements();
3448
3449   if (VT.getSizeInBits() != 128)
3450     return false;
3451
3452   if (NumElems != 4)
3453     return false;
3454
3455   return isUndefOrEqual(Mask[0], 2) &&
3456          isUndefOrEqual(Mask[1], 3) &&
3457          isUndefOrEqual(Mask[2], 2) &&
3458          isUndefOrEqual(Mask[3], 3);
3459 }
3460
3461 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3462 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3463 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3464   if (VT.getSizeInBits() != 128)
3465     return false;
3466
3467   unsigned NumElems = VT.getVectorNumElements();
3468
3469   if (NumElems != 2 && NumElems != 4)
3470     return false;
3471
3472   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3473     if (!isUndefOrEqual(Mask[i], i + NumElems))
3474       return false;
3475
3476   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3477     if (!isUndefOrEqual(Mask[i], i))
3478       return false;
3479
3480   return true;
3481 }
3482
3483 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3484 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3485 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3486   unsigned NumElems = VT.getVectorNumElements();
3487
3488   if ((NumElems != 2 && NumElems != 4)
3489       || VT.getSizeInBits() > 128)
3490     return false;
3491
3492   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3493     if (!isUndefOrEqual(Mask[i], i))
3494       return false;
3495
3496   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3497     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3498       return false;
3499
3500   return true;
3501 }
3502
3503 //
3504 // Some special combinations that can be optimized.
3505 //
3506 static
3507 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3508                                SelectionDAG &DAG) {
3509   EVT VT = SVOp->getValueType(0);
3510   DebugLoc dl = SVOp->getDebugLoc();
3511
3512   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3513     return SDValue();
3514
3515   ArrayRef<int> Mask = SVOp->getMask();
3516
3517   // These are the special masks that may be optimized.
3518   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3519   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3520   bool MatchEvenMask = true;
3521   bool MatchOddMask  = true;
3522   for (int i=0; i<8; ++i) {
3523     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3524       MatchEvenMask = false;
3525     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3526       MatchOddMask = false;
3527   }
3528   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3529   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3530
3531   const int *CompactionMask;
3532   if (MatchEvenMask)
3533     CompactionMask = CompactionMaskEven;
3534   else if (MatchOddMask)
3535     CompactionMask = CompactionMaskOdd;
3536   else
3537     return SDValue();
3538
3539   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3540
3541   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3542                                      UndefNode, CompactionMask);
3543   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3544                                      UndefNode, CompactionMask);
3545   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3546   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3547 }
3548
3549 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3550 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3551 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3552                          bool HasAVX2, bool V2IsSplat = false) {
3553   unsigned NumElts = VT.getVectorNumElements();
3554
3555   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3556          "Unsupported vector type for unpckh");
3557
3558   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3559       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3560     return false;
3561
3562   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3563   // independently on 128-bit lanes.
3564   unsigned NumLanes = VT.getSizeInBits()/128;
3565   unsigned NumLaneElts = NumElts/NumLanes;
3566
3567   for (unsigned l = 0; l != NumLanes; ++l) {
3568     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3569          i != (l+1)*NumLaneElts;
3570          i += 2, ++j) {
3571       int BitI  = Mask[i];
3572       int BitI1 = Mask[i+1];
3573       if (!isUndefOrEqual(BitI, j))
3574         return false;
3575       if (V2IsSplat) {
3576         if (!isUndefOrEqual(BitI1, NumElts))
3577           return false;
3578       } else {
3579         if (!isUndefOrEqual(BitI1, j + NumElts))
3580           return false;
3581       }
3582     }
3583   }
3584
3585   return true;
3586 }
3587
3588 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3590 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3591                          bool HasAVX2, bool V2IsSplat = false) {
3592   unsigned NumElts = VT.getVectorNumElements();
3593
3594   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3595          "Unsupported vector type for unpckh");
3596
3597   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3598       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3599     return false;
3600
3601   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3602   // independently on 128-bit lanes.
3603   unsigned NumLanes = VT.getSizeInBits()/128;
3604   unsigned NumLaneElts = NumElts/NumLanes;
3605
3606   for (unsigned l = 0; l != NumLanes; ++l) {
3607     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3608          i != (l+1)*NumLaneElts; i += 2, ++j) {
3609       int BitI  = Mask[i];
3610       int BitI1 = Mask[i+1];
3611       if (!isUndefOrEqual(BitI, j))
3612         return false;
3613       if (V2IsSplat) {
3614         if (isUndefOrEqual(BitI1, NumElts))
3615           return false;
3616       } else {
3617         if (!isUndefOrEqual(BitI1, j+NumElts))
3618           return false;
3619       }
3620     }
3621   }
3622   return true;
3623 }
3624
3625 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3626 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3627 /// <0, 0, 1, 1>
3628 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3629                                   bool HasAVX2) {
3630   unsigned NumElts = VT.getVectorNumElements();
3631
3632   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3633          "Unsupported vector type for unpckh");
3634
3635   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3636       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3637     return false;
3638
3639   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3640   // FIXME: Need a better way to get rid of this, there's no latency difference
3641   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3642   // the former later. We should also remove the "_undef" special mask.
3643   if (NumElts == 4 && VT.getSizeInBits() == 256)
3644     return false;
3645
3646   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3647   // independently on 128-bit lanes.
3648   unsigned NumLanes = VT.getSizeInBits()/128;
3649   unsigned NumLaneElts = NumElts/NumLanes;
3650
3651   for (unsigned l = 0; l != NumLanes; ++l) {
3652     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3653          i != (l+1)*NumLaneElts;
3654          i += 2, ++j) {
3655       int BitI  = Mask[i];
3656       int BitI1 = Mask[i+1];
3657
3658       if (!isUndefOrEqual(BitI, j))
3659         return false;
3660       if (!isUndefOrEqual(BitI1, j))
3661         return false;
3662     }
3663   }
3664
3665   return true;
3666 }
3667
3668 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3669 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3670 /// <2, 2, 3, 3>
3671 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3672   unsigned NumElts = VT.getVectorNumElements();
3673
3674   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3675          "Unsupported vector type for unpckh");
3676
3677   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3678       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3679     return false;
3680
3681   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3682   // independently on 128-bit lanes.
3683   unsigned NumLanes = VT.getSizeInBits()/128;
3684   unsigned NumLaneElts = NumElts/NumLanes;
3685
3686   for (unsigned l = 0; l != NumLanes; ++l) {
3687     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3688          i != (l+1)*NumLaneElts; i += 2, ++j) {
3689       int BitI  = Mask[i];
3690       int BitI1 = Mask[i+1];
3691       if (!isUndefOrEqual(BitI, j))
3692         return false;
3693       if (!isUndefOrEqual(BitI1, j))
3694         return false;
3695     }
3696   }
3697   return true;
3698 }
3699
3700 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3701 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3702 /// MOVSD, and MOVD, i.e. setting the lowest element.
3703 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3704   if (VT.getVectorElementType().getSizeInBits() < 32)
3705     return false;
3706   if (VT.getSizeInBits() == 256)
3707     return false;
3708
3709   unsigned NumElts = VT.getVectorNumElements();
3710
3711   if (!isUndefOrEqual(Mask[0], NumElts))
3712     return false;
3713
3714   for (unsigned i = 1; i != NumElts; ++i)
3715     if (!isUndefOrEqual(Mask[i], i))
3716       return false;
3717
3718   return true;
3719 }
3720
3721 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3722 /// as permutations between 128-bit chunks or halves. As an example: this
3723 /// shuffle bellow:
3724 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3725 /// The first half comes from the second half of V1 and the second half from the
3726 /// the second half of V2.
3727 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3728   if (!HasAVX || VT.getSizeInBits() != 256)
3729     return false;
3730
3731   // The shuffle result is divided into half A and half B. In total the two
3732   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3733   // B must come from C, D, E or F.
3734   unsigned HalfSize = VT.getVectorNumElements()/2;
3735   bool MatchA = false, MatchB = false;
3736
3737   // Check if A comes from one of C, D, E, F.
3738   for (unsigned Half = 0; Half != 4; ++Half) {
3739     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3740       MatchA = true;
3741       break;
3742     }
3743   }
3744
3745   // Check if B comes from one of C, D, E, F.
3746   for (unsigned Half = 0; Half != 4; ++Half) {
3747     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3748       MatchB = true;
3749       break;
3750     }
3751   }
3752
3753   return MatchA && MatchB;
3754 }
3755
3756 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3757 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3758 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3759   EVT VT = SVOp->getValueType(0);
3760
3761   unsigned HalfSize = VT.getVectorNumElements()/2;
3762
3763   unsigned FstHalf = 0, SndHalf = 0;
3764   for (unsigned i = 0; i < HalfSize; ++i) {
3765     if (SVOp->getMaskElt(i) > 0) {
3766       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3767       break;
3768     }
3769   }
3770   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3771     if (SVOp->getMaskElt(i) > 0) {
3772       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3773       break;
3774     }
3775   }
3776
3777   return (FstHalf | (SndHalf << 4));
3778 }
3779
3780 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3782 /// Note that VPERMIL mask matching is different depending whether theunderlying
3783 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3784 /// to the same elements of the low, but to the higher half of the source.
3785 /// In VPERMILPD the two lanes could be shuffled independently of each other
3786 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3787 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3788   if (!HasAVX)
3789     return false;
3790
3791   unsigned NumElts = VT.getVectorNumElements();
3792   // Only match 256-bit with 32/64-bit types
3793   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3794     return false;
3795
3796   unsigned NumLanes = VT.getSizeInBits()/128;
3797   unsigned LaneSize = NumElts/NumLanes;
3798   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3799     for (unsigned i = 0; i != LaneSize; ++i) {
3800       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3801         return false;
3802       if (NumElts != 8 || l == 0)
3803         continue;
3804       // VPERMILPS handling
3805       if (Mask[i] < 0)
3806         continue;
3807       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3808         return false;
3809     }
3810   }
3811
3812   return true;
3813 }
3814
3815 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3816 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3817 /// element of vector 2 and the other elements to come from vector 1 in order.
3818 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3819                                bool V2IsSplat = false, bool V2IsUndef = false) {
3820   unsigned NumOps = VT.getVectorNumElements();
3821   if (VT.getSizeInBits() == 256)
3822     return false;
3823   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3824     return false;
3825
3826   if (!isUndefOrEqual(Mask[0], 0))
3827     return false;
3828
3829   for (unsigned i = 1; i != NumOps; ++i)
3830     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3831           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3832           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3833       return false;
3834
3835   return true;
3836 }
3837
3838 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3839 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3840 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3841 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3842                            const X86Subtarget *Subtarget) {
3843   if (!Subtarget->hasSSE3())
3844     return false;
3845
3846   unsigned NumElems = VT.getVectorNumElements();
3847
3848   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3849       (VT.getSizeInBits() == 256 && NumElems != 8))
3850     return false;
3851
3852   // "i+1" is the value the indexed mask element must have
3853   for (unsigned i = 0; i != NumElems; i += 2)
3854     if (!isUndefOrEqual(Mask[i], i+1) ||
3855         !isUndefOrEqual(Mask[i+1], i+1))
3856       return false;
3857
3858   return true;
3859 }
3860
3861 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3862 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3863 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3864 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3865                            const X86Subtarget *Subtarget) {
3866   if (!Subtarget->hasSSE3())
3867     return false;
3868
3869   unsigned NumElems = VT.getVectorNumElements();
3870
3871   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3872       (VT.getSizeInBits() == 256 && NumElems != 8))
3873     return false;
3874
3875   // "i" is the value the indexed mask element must have
3876   for (unsigned i = 0; i != NumElems; i += 2)
3877     if (!isUndefOrEqual(Mask[i], i) ||
3878         !isUndefOrEqual(Mask[i+1], i))
3879       return false;
3880
3881   return true;
3882 }
3883
3884 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to 256-bit
3886 /// version of MOVDDUP.
3887 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3888   unsigned NumElts = VT.getVectorNumElements();
3889
3890   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3891     return false;
3892
3893   for (unsigned i = 0; i != NumElts/2; ++i)
3894     if (!isUndefOrEqual(Mask[i], 0))
3895       return false;
3896   for (unsigned i = NumElts/2; i != NumElts; ++i)
3897     if (!isUndefOrEqual(Mask[i], NumElts/2))
3898       return false;
3899   return true;
3900 }
3901
3902 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3903 /// specifies a shuffle of elements that is suitable for input to 128-bit
3904 /// version of MOVDDUP.
3905 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3906   if (VT.getSizeInBits() != 128)
3907     return false;
3908
3909   unsigned e = VT.getVectorNumElements() / 2;
3910   for (unsigned i = 0; i != e; ++i)
3911     if (!isUndefOrEqual(Mask[i], i))
3912       return false;
3913   for (unsigned i = 0; i != e; ++i)
3914     if (!isUndefOrEqual(Mask[e+i], i))
3915       return false;
3916   return true;
3917 }
3918
3919 /// isVEXTRACTF128Index - Return true if the specified
3920 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3921 /// suitable for input to VEXTRACTF128.
3922 bool X86::isVEXTRACTF128Index(SDNode *N) {
3923   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3924     return false;
3925
3926   // The index should be aligned on a 128-bit boundary.
3927   uint64_t Index =
3928     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3929
3930   unsigned VL = N->getValueType(0).getVectorNumElements();
3931   unsigned VBits = N->getValueType(0).getSizeInBits();
3932   unsigned ElSize = VBits / VL;
3933   bool Result = (Index * ElSize) % 128 == 0;
3934
3935   return Result;
3936 }
3937
3938 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3939 /// operand specifies a subvector insert that is suitable for input to
3940 /// VINSERTF128.
3941 bool X86::isVINSERTF128Index(SDNode *N) {
3942   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3943     return false;
3944
3945   // The index should be aligned on a 128-bit boundary.
3946   uint64_t Index =
3947     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3948
3949   unsigned VL = N->getValueType(0).getVectorNumElements();
3950   unsigned VBits = N->getValueType(0).getSizeInBits();
3951   unsigned ElSize = VBits / VL;
3952   bool Result = (Index * ElSize) % 128 == 0;
3953
3954   return Result;
3955 }
3956
3957 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3958 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3959 /// Handles 128-bit and 256-bit.
3960 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3961   EVT VT = N->getValueType(0);
3962
3963   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3964          "Unsupported vector type for PSHUF/SHUFP");
3965
3966   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3967   // independently on 128-bit lanes.
3968   unsigned NumElts = VT.getVectorNumElements();
3969   unsigned NumLanes = VT.getSizeInBits()/128;
3970   unsigned NumLaneElts = NumElts/NumLanes;
3971
3972   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3973          "Only supports 2 or 4 elements per lane");
3974
3975   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3976   unsigned Mask = 0;
3977   for (unsigned i = 0; i != NumElts; ++i) {
3978     int Elt = N->getMaskElt(i);
3979     if (Elt < 0) continue;
3980     Elt &= NumLaneElts - 1;
3981     unsigned ShAmt = (i << Shift) % 8;
3982     Mask |= Elt << ShAmt;
3983   }
3984
3985   return Mask;
3986 }
3987
3988 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3989 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3990 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3991   EVT VT = N->getValueType(0);
3992
3993   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3994          "Unsupported vector type for PSHUFHW");
3995
3996   unsigned NumElts = VT.getVectorNumElements();
3997
3998   unsigned Mask = 0;
3999   for (unsigned l = 0; l != NumElts; l += 8) {
4000     // 8 nodes per lane, but we only care about the last 4.
4001     for (unsigned i = 0; i < 4; ++i) {
4002       int Elt = N->getMaskElt(l+i+4);
4003       if (Elt < 0) continue;
4004       Elt &= 0x3; // only 2-bits.
4005       Mask |= Elt << (i * 2);
4006     }
4007   }
4008
4009   return Mask;
4010 }
4011
4012 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4013 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4014 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4015   EVT VT = N->getValueType(0);
4016
4017   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4018          "Unsupported vector type for PSHUFHW");
4019
4020   unsigned NumElts = VT.getVectorNumElements();
4021
4022   unsigned Mask = 0;
4023   for (unsigned l = 0; l != NumElts; l += 8) {
4024     // 8 nodes per lane, but we only care about the first 4.
4025     for (unsigned i = 0; i < 4; ++i) {
4026       int Elt = N->getMaskElt(l+i);
4027       if (Elt < 0) continue;
4028       Elt &= 0x3; // only 2-bits
4029       Mask |= Elt << (i * 2);
4030     }
4031   }
4032
4033   return Mask;
4034 }
4035
4036 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4037 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4038 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4039   EVT VT = SVOp->getValueType(0);
4040   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4041
4042   unsigned NumElts = VT.getVectorNumElements();
4043   unsigned NumLanes = VT.getSizeInBits()/128;
4044   unsigned NumLaneElts = NumElts/NumLanes;
4045
4046   int Val = 0;
4047   unsigned i;
4048   for (i = 0; i != NumElts; ++i) {
4049     Val = SVOp->getMaskElt(i);
4050     if (Val >= 0)
4051       break;
4052   }
4053   if (Val >= (int)NumElts)
4054     Val -= NumElts - NumLaneElts;
4055
4056   assert(Val - i > 0 && "PALIGNR imm should be positive");
4057   return (Val - i) * EltSize;
4058 }
4059
4060 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4061 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4062 /// instructions.
4063 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4064   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4065     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4066
4067   uint64_t Index =
4068     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4069
4070   EVT VecVT = N->getOperand(0).getValueType();
4071   EVT ElVT = VecVT.getVectorElementType();
4072
4073   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4074   return Index / NumElemsPerChunk;
4075 }
4076
4077 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4078 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4079 /// instructions.
4080 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4081   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4082     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4083
4084   uint64_t Index =
4085     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4086
4087   EVT VecVT = N->getValueType(0);
4088   EVT ElVT = VecVT.getVectorElementType();
4089
4090   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4091   return Index / NumElemsPerChunk;
4092 }
4093
4094 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4095 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4096 /// Handles 256-bit.
4097 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4098   EVT VT = N->getValueType(0);
4099
4100   unsigned NumElts = VT.getVectorNumElements();
4101
4102   assert((VT.is256BitVector() && NumElts == 4) &&
4103          "Unsupported vector type for VPERMQ/VPERMPD");
4104
4105   unsigned Mask = 0;
4106   for (unsigned i = 0; i != NumElts; ++i) {
4107     int Elt = N->getMaskElt(i);
4108     if (Elt < 0)
4109       continue;
4110     Mask |= Elt << (i*2);
4111   }
4112
4113   return Mask;
4114 }
4115 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4116 /// constant +0.0.
4117 bool X86::isZeroNode(SDValue Elt) {
4118   return ((isa<ConstantSDNode>(Elt) &&
4119            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4120           (isa<ConstantFPSDNode>(Elt) &&
4121            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4122 }
4123
4124 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4125 /// their permute mask.
4126 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4127                                     SelectionDAG &DAG) {
4128   EVT VT = SVOp->getValueType(0);
4129   unsigned NumElems = VT.getVectorNumElements();
4130   SmallVector<int, 8> MaskVec;
4131
4132   for (unsigned i = 0; i != NumElems; ++i) {
4133     int Idx = SVOp->getMaskElt(i);
4134     if (Idx >= 0) {
4135       if (Idx < (int)NumElems)
4136         Idx += NumElems;
4137       else
4138         Idx -= NumElems;
4139     }
4140     MaskVec.push_back(Idx);
4141   }
4142   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4143                               SVOp->getOperand(0), &MaskVec[0]);
4144 }
4145
4146 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4147 /// match movhlps. The lower half elements should come from upper half of
4148 /// V1 (and in order), and the upper half elements should come from the upper
4149 /// half of V2 (and in order).
4150 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4151   if (VT.getSizeInBits() != 128)
4152     return false;
4153   if (VT.getVectorNumElements() != 4)
4154     return false;
4155   for (unsigned i = 0, e = 2; i != e; ++i)
4156     if (!isUndefOrEqual(Mask[i], i+2))
4157       return false;
4158   for (unsigned i = 2; i != 4; ++i)
4159     if (!isUndefOrEqual(Mask[i], i+4))
4160       return false;
4161   return true;
4162 }
4163
4164 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4165 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4166 /// required.
4167 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4168   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4169     return false;
4170   N = N->getOperand(0).getNode();
4171   if (!ISD::isNON_EXTLoad(N))
4172     return false;
4173   if (LD)
4174     *LD = cast<LoadSDNode>(N);
4175   return true;
4176 }
4177
4178 // Test whether the given value is a vector value which will be legalized
4179 // into a load.
4180 static bool WillBeConstantPoolLoad(SDNode *N) {
4181   if (N->getOpcode() != ISD::BUILD_VECTOR)
4182     return false;
4183
4184   // Check for any non-constant elements.
4185   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4186     switch (N->getOperand(i).getNode()->getOpcode()) {
4187     case ISD::UNDEF:
4188     case ISD::ConstantFP:
4189     case ISD::Constant:
4190       break;
4191     default:
4192       return false;
4193     }
4194
4195   // Vectors of all-zeros and all-ones are materialized with special
4196   // instructions rather than being loaded.
4197   return !ISD::isBuildVectorAllZeros(N) &&
4198          !ISD::isBuildVectorAllOnes(N);
4199 }
4200
4201 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4202 /// match movlp{s|d}. The lower half elements should come from lower half of
4203 /// V1 (and in order), and the upper half elements should come from the upper
4204 /// half of V2 (and in order). And since V1 will become the source of the
4205 /// MOVLP, it must be either a vector load or a scalar load to vector.
4206 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4207                                ArrayRef<int> Mask, EVT VT) {
4208   if (VT.getSizeInBits() != 128)
4209     return false;
4210
4211   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4212     return false;
4213   // Is V2 is a vector load, don't do this transformation. We will try to use
4214   // load folding shufps op.
4215   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4216     return false;
4217
4218   unsigned NumElems = VT.getVectorNumElements();
4219
4220   if (NumElems != 2 && NumElems != 4)
4221     return false;
4222   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4223     if (!isUndefOrEqual(Mask[i], i))
4224       return false;
4225   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4226     if (!isUndefOrEqual(Mask[i], i+NumElems))
4227       return false;
4228   return true;
4229 }
4230
4231 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4232 /// all the same.
4233 static bool isSplatVector(SDNode *N) {
4234   if (N->getOpcode() != ISD::BUILD_VECTOR)
4235     return false;
4236
4237   SDValue SplatValue = N->getOperand(0);
4238   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4239     if (N->getOperand(i) != SplatValue)
4240       return false;
4241   return true;
4242 }
4243
4244 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4245 /// to an zero vector.
4246 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4247 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4248   SDValue V1 = N->getOperand(0);
4249   SDValue V2 = N->getOperand(1);
4250   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4251   for (unsigned i = 0; i != NumElems; ++i) {
4252     int Idx = N->getMaskElt(i);
4253     if (Idx >= (int)NumElems) {
4254       unsigned Opc = V2.getOpcode();
4255       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4256         continue;
4257       if (Opc != ISD::BUILD_VECTOR ||
4258           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4259         return false;
4260     } else if (Idx >= 0) {
4261       unsigned Opc = V1.getOpcode();
4262       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4263         continue;
4264       if (Opc != ISD::BUILD_VECTOR ||
4265           !X86::isZeroNode(V1.getOperand(Idx)))
4266         return false;
4267     }
4268   }
4269   return true;
4270 }
4271
4272 /// getZeroVector - Returns a vector of specified type with all zero elements.
4273 ///
4274 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4275                              SelectionDAG &DAG, DebugLoc dl) {
4276   assert(VT.isVector() && "Expected a vector type");
4277   unsigned Size = VT.getSizeInBits();
4278
4279   // Always build SSE zero vectors as <4 x i32> bitcasted
4280   // to their dest type. This ensures they get CSE'd.
4281   SDValue Vec;
4282   if (Size == 128) {  // SSE
4283     if (Subtarget->hasSSE2()) {  // SSE2
4284       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4285       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4286     } else { // SSE1
4287       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4288       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4289     }
4290   } else if (Size == 256) { // AVX
4291     if (Subtarget->hasAVX2()) { // AVX2
4292       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4293       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4294       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4295     } else {
4296       // 256-bit logic and arithmetic instructions in AVX are all
4297       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4298       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4299       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4300       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4301     }
4302   } else
4303     llvm_unreachable("Unexpected vector type");
4304
4305   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4306 }
4307
4308 /// getOnesVector - Returns a vector of specified type with all bits set.
4309 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4310 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4311 /// Then bitcast to their original type, ensuring they get CSE'd.
4312 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4313                              DebugLoc dl) {
4314   assert(VT.isVector() && "Expected a vector type");
4315   unsigned Size = VT.getSizeInBits();
4316
4317   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4318   SDValue Vec;
4319   if (Size == 256) {
4320     if (HasAVX2) { // AVX2
4321       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4322       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4323     } else { // AVX
4324       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4325       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4326     }
4327   } else if (Size == 128) {
4328     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4329   } else
4330     llvm_unreachable("Unexpected vector type");
4331
4332   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4333 }
4334
4335 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4336 /// that point to V2 points to its first element.
4337 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4338   for (unsigned i = 0; i != NumElems; ++i) {
4339     if (Mask[i] > (int)NumElems) {
4340       Mask[i] = NumElems;
4341     }
4342   }
4343 }
4344
4345 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4346 /// operation of specified width.
4347 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4348                        SDValue V2) {
4349   unsigned NumElems = VT.getVectorNumElements();
4350   SmallVector<int, 8> Mask;
4351   Mask.push_back(NumElems);
4352   for (unsigned i = 1; i != NumElems; ++i)
4353     Mask.push_back(i);
4354   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4355 }
4356
4357 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4358 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4359                           SDValue V2) {
4360   unsigned NumElems = VT.getVectorNumElements();
4361   SmallVector<int, 8> Mask;
4362   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4363     Mask.push_back(i);
4364     Mask.push_back(i + NumElems);
4365   }
4366   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4367 }
4368
4369 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4370 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4371                           SDValue V2) {
4372   unsigned NumElems = VT.getVectorNumElements();
4373   SmallVector<int, 8> Mask;
4374   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4375     Mask.push_back(i + Half);
4376     Mask.push_back(i + NumElems + Half);
4377   }
4378   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4379 }
4380
4381 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4382 // a generic shuffle instruction because the target has no such instructions.
4383 // Generate shuffles which repeat i16 and i8 several times until they can be
4384 // represented by v4f32 and then be manipulated by target suported shuffles.
4385 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4386   EVT VT = V.getValueType();
4387   int NumElems = VT.getVectorNumElements();
4388   DebugLoc dl = V.getDebugLoc();
4389
4390   while (NumElems > 4) {
4391     if (EltNo < NumElems/2) {
4392       V = getUnpackl(DAG, dl, VT, V, V);
4393     } else {
4394       V = getUnpackh(DAG, dl, VT, V, V);
4395       EltNo -= NumElems/2;
4396     }
4397     NumElems >>= 1;
4398   }
4399   return V;
4400 }
4401
4402 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4403 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4404   EVT VT = V.getValueType();
4405   DebugLoc dl = V.getDebugLoc();
4406   unsigned Size = VT.getSizeInBits();
4407
4408   if (Size == 128) {
4409     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4410     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4411     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4412                              &SplatMask[0]);
4413   } else if (Size == 256) {
4414     // To use VPERMILPS to splat scalars, the second half of indicies must
4415     // refer to the higher part, which is a duplication of the lower one,
4416     // because VPERMILPS can only handle in-lane permutations.
4417     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4418                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4419
4420     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4421     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4422                              &SplatMask[0]);
4423   } else
4424     llvm_unreachable("Vector size not supported");
4425
4426   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4427 }
4428
4429 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4430 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4431   EVT SrcVT = SV->getValueType(0);
4432   SDValue V1 = SV->getOperand(0);
4433   DebugLoc dl = SV->getDebugLoc();
4434
4435   int EltNo = SV->getSplatIndex();
4436   int NumElems = SrcVT.getVectorNumElements();
4437   unsigned Size = SrcVT.getSizeInBits();
4438
4439   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4440           "Unknown how to promote splat for type");
4441
4442   // Extract the 128-bit part containing the splat element and update
4443   // the splat element index when it refers to the higher register.
4444   if (Size == 256) {
4445     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4446     if (EltNo >= NumElems/2)
4447       EltNo -= NumElems/2;
4448   }
4449
4450   // All i16 and i8 vector types can't be used directly by a generic shuffle
4451   // instruction because the target has no such instruction. Generate shuffles
4452   // which repeat i16 and i8 several times until they fit in i32, and then can
4453   // be manipulated by target suported shuffles.
4454   EVT EltVT = SrcVT.getVectorElementType();
4455   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4456     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4457
4458   // Recreate the 256-bit vector and place the same 128-bit vector
4459   // into the low and high part. This is necessary because we want
4460   // to use VPERM* to shuffle the vectors
4461   if (Size == 256) {
4462     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4463   }
4464
4465   return getLegalSplat(DAG, V1, EltNo);
4466 }
4467
4468 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4469 /// vector of zero or undef vector.  This produces a shuffle where the low
4470 /// element of V2 is swizzled into the zero/undef vector, landing at element
4471 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4472 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4473                                            bool IsZero,
4474                                            const X86Subtarget *Subtarget,
4475                                            SelectionDAG &DAG) {
4476   EVT VT = V2.getValueType();
4477   SDValue V1 = IsZero
4478     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SmallVector<int, 16> MaskVec;
4481   for (unsigned i = 0; i != NumElems; ++i)
4482     // If this is the insertion idx, put the low elt of V2 here.
4483     MaskVec.push_back(i == Idx ? NumElems : i);
4484   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4485 }
4486
4487 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4488 /// target specific opcode. Returns true if the Mask could be calculated.
4489 /// Sets IsUnary to true if only uses one source.
4490 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4491                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4492   unsigned NumElems = VT.getVectorNumElements();
4493   SDValue ImmN;
4494
4495   IsUnary = false;
4496   switch(N->getOpcode()) {
4497   case X86ISD::SHUFP:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     break;
4501   case X86ISD::UNPCKH:
4502     DecodeUNPCKHMask(VT, Mask);
4503     break;
4504   case X86ISD::UNPCKL:
4505     DecodeUNPCKLMask(VT, Mask);
4506     break;
4507   case X86ISD::MOVHLPS:
4508     DecodeMOVHLPSMask(NumElems, Mask);
4509     break;
4510   case X86ISD::MOVLHPS:
4511     DecodeMOVLHPSMask(NumElems, Mask);
4512     break;
4513   case X86ISD::PSHUFD:
4514   case X86ISD::VPERMILP:
4515     ImmN = N->getOperand(N->getNumOperands()-1);
4516     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4517     IsUnary = true;
4518     break;
4519   case X86ISD::PSHUFHW:
4520     ImmN = N->getOperand(N->getNumOperands()-1);
4521     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4522     IsUnary = true;
4523     break;
4524   case X86ISD::PSHUFLW:
4525     ImmN = N->getOperand(N->getNumOperands()-1);
4526     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4527     IsUnary = true;
4528     break;
4529   case X86ISD::VPERMI:
4530     ImmN = N->getOperand(N->getNumOperands()-1);
4531     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4532     IsUnary = true;
4533     break;
4534   case X86ISD::MOVSS:
4535   case X86ISD::MOVSD: {
4536     // The index 0 always comes from the first element of the second source,
4537     // this is why MOVSS and MOVSD are used in the first place. The other
4538     // elements come from the other positions of the first source vector
4539     Mask.push_back(NumElems);
4540     for (unsigned i = 1; i != NumElems; ++i) {
4541       Mask.push_back(i);
4542     }
4543     break;
4544   }
4545   case X86ISD::VPERM2X128:
4546     ImmN = N->getOperand(N->getNumOperands()-1);
4547     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4548     if (Mask.empty()) return false;
4549     break;
4550   case X86ISD::MOVDDUP:
4551   case X86ISD::MOVLHPD:
4552   case X86ISD::MOVLPD:
4553   case X86ISD::MOVLPS:
4554   case X86ISD::MOVSHDUP:
4555   case X86ISD::MOVSLDUP:
4556   case X86ISD::PALIGN:
4557     // Not yet implemented
4558     return false;
4559   default: llvm_unreachable("unknown target shuffle node");
4560   }
4561
4562   return true;
4563 }
4564
4565 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4566 /// element of the result of the vector shuffle.
4567 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4568                                    unsigned Depth) {
4569   if (Depth == 6)
4570     return SDValue();  // Limit search depth.
4571
4572   SDValue V = SDValue(N, 0);
4573   EVT VT = V.getValueType();
4574   unsigned Opcode = V.getOpcode();
4575
4576   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4577   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4578     int Elt = SV->getMaskElt(Index);
4579
4580     if (Elt < 0)
4581       return DAG.getUNDEF(VT.getVectorElementType());
4582
4583     unsigned NumElems = VT.getVectorNumElements();
4584     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4585                                          : SV->getOperand(1);
4586     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4587   }
4588
4589   // Recurse into target specific vector shuffles to find scalars.
4590   if (isTargetShuffle(Opcode)) {
4591     MVT ShufVT = V.getValueType().getSimpleVT();
4592     unsigned NumElems = ShufVT.getVectorNumElements();
4593     SmallVector<int, 16> ShuffleMask;
4594     SDValue ImmN;
4595     bool IsUnary;
4596
4597     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4598       return SDValue();
4599
4600     int Elt = ShuffleMask[Index];
4601     if (Elt < 0)
4602       return DAG.getUNDEF(ShufVT.getVectorElementType());
4603
4604     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4605                                          : N->getOperand(1);
4606     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4607                                Depth+1);
4608   }
4609
4610   // Actual nodes that may contain scalar elements
4611   if (Opcode == ISD::BITCAST) {
4612     V = V.getOperand(0);
4613     EVT SrcVT = V.getValueType();
4614     unsigned NumElems = VT.getVectorNumElements();
4615
4616     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4617       return SDValue();
4618   }
4619
4620   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4621     return (Index == 0) ? V.getOperand(0)
4622                         : DAG.getUNDEF(VT.getVectorElementType());
4623
4624   if (V.getOpcode() == ISD::BUILD_VECTOR)
4625     return V.getOperand(Index);
4626
4627   return SDValue();
4628 }
4629
4630 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4631 /// shuffle operation which come from a consecutively from a zero. The
4632 /// search can start in two different directions, from left or right.
4633 static
4634 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4635                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4636   unsigned i;
4637   for (i = 0; i != NumElems; ++i) {
4638     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4639     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4640     if (!(Elt.getNode() &&
4641          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4642       break;
4643   }
4644
4645   return i;
4646 }
4647
4648 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4649 /// correspond consecutively to elements from one of the vector operands,
4650 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4651 static
4652 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4653                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4654                               unsigned NumElems, unsigned &OpNum) {
4655   bool SeenV1 = false;
4656   bool SeenV2 = false;
4657
4658   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4659     int Idx = SVOp->getMaskElt(i);
4660     // Ignore undef indicies
4661     if (Idx < 0)
4662       continue;
4663
4664     if (Idx < (int)NumElems)
4665       SeenV1 = true;
4666     else
4667       SeenV2 = true;
4668
4669     // Only accept consecutive elements from the same vector
4670     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4671       return false;
4672   }
4673
4674   OpNum = SeenV1 ? 0 : 1;
4675   return true;
4676 }
4677
4678 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4679 /// logical left shift of a vector.
4680 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4681                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4682   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4683   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4684               false /* check zeros from right */, DAG);
4685   unsigned OpSrc;
4686
4687   if (!NumZeros)
4688     return false;
4689
4690   // Considering the elements in the mask that are not consecutive zeros,
4691   // check if they consecutively come from only one of the source vectors.
4692   //
4693   //               V1 = {X, A, B, C}     0
4694   //                         \  \  \    /
4695   //   vector_shuffle V1, V2 <1, 2, 3, X>
4696   //
4697   if (!isShuffleMaskConsecutive(SVOp,
4698             0,                   // Mask Start Index
4699             NumElems-NumZeros,   // Mask End Index(exclusive)
4700             NumZeros,            // Where to start looking in the src vector
4701             NumElems,            // Number of elements in vector
4702             OpSrc))              // Which source operand ?
4703     return false;
4704
4705   isLeft = false;
4706   ShAmt = NumZeros;
4707   ShVal = SVOp->getOperand(OpSrc);
4708   return true;
4709 }
4710
4711 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4712 /// logical left shift of a vector.
4713 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4714                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4715   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4716   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4717               true /* check zeros from left */, DAG);
4718   unsigned OpSrc;
4719
4720   if (!NumZeros)
4721     return false;
4722
4723   // Considering the elements in the mask that are not consecutive zeros,
4724   // check if they consecutively come from only one of the source vectors.
4725   //
4726   //                           0    { A, B, X, X } = V2
4727   //                          / \    /  /
4728   //   vector_shuffle V1, V2 <X, X, 4, 5>
4729   //
4730   if (!isShuffleMaskConsecutive(SVOp,
4731             NumZeros,     // Mask Start Index
4732             NumElems,     // Mask End Index(exclusive)
4733             0,            // Where to start looking in the src vector
4734             NumElems,     // Number of elements in vector
4735             OpSrc))       // Which source operand ?
4736     return false;
4737
4738   isLeft = true;
4739   ShAmt = NumZeros;
4740   ShVal = SVOp->getOperand(OpSrc);
4741   return true;
4742 }
4743
4744 /// isVectorShift - Returns true if the shuffle can be implemented as a
4745 /// logical left or right shift of a vector.
4746 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4747                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4748   // Although the logic below support any bitwidth size, there are no
4749   // shift instructions which handle more than 128-bit vectors.
4750   if (SVOp->getValueType(0).getSizeInBits() > 128)
4751     return false;
4752
4753   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4754       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4755     return true;
4756
4757   return false;
4758 }
4759
4760 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4761 ///
4762 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4763                                        unsigned NumNonZero, unsigned NumZero,
4764                                        SelectionDAG &DAG,
4765                                        const X86Subtarget* Subtarget,
4766                                        const TargetLowering &TLI) {
4767   if (NumNonZero > 8)
4768     return SDValue();
4769
4770   DebugLoc dl = Op.getDebugLoc();
4771   SDValue V(0, 0);
4772   bool First = true;
4773   for (unsigned i = 0; i < 16; ++i) {
4774     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4775     if (ThisIsNonZero && First) {
4776       if (NumZero)
4777         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4778       else
4779         V = DAG.getUNDEF(MVT::v8i16);
4780       First = false;
4781     }
4782
4783     if ((i & 1) != 0) {
4784       SDValue ThisElt(0, 0), LastElt(0, 0);
4785       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4786       if (LastIsNonZero) {
4787         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4788                               MVT::i16, Op.getOperand(i-1));
4789       }
4790       if (ThisIsNonZero) {
4791         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4792         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4793                               ThisElt, DAG.getConstant(8, MVT::i8));
4794         if (LastIsNonZero)
4795           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4796       } else
4797         ThisElt = LastElt;
4798
4799       if (ThisElt.getNode())
4800         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4801                         DAG.getIntPtrConstant(i/2));
4802     }
4803   }
4804
4805   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4806 }
4807
4808 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4809 ///
4810 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4811                                      unsigned NumNonZero, unsigned NumZero,
4812                                      SelectionDAG &DAG,
4813                                      const X86Subtarget* Subtarget,
4814                                      const TargetLowering &TLI) {
4815   if (NumNonZero > 4)
4816     return SDValue();
4817
4818   DebugLoc dl = Op.getDebugLoc();
4819   SDValue V(0, 0);
4820   bool First = true;
4821   for (unsigned i = 0; i < 8; ++i) {
4822     bool isNonZero = (NonZeros & (1 << i)) != 0;
4823     if (isNonZero) {
4824       if (First) {
4825         if (NumZero)
4826           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4827         else
4828           V = DAG.getUNDEF(MVT::v8i16);
4829         First = false;
4830       }
4831       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4832                       MVT::v8i16, V, Op.getOperand(i),
4833                       DAG.getIntPtrConstant(i));
4834     }
4835   }
4836
4837   return V;
4838 }
4839
4840 /// getVShift - Return a vector logical shift node.
4841 ///
4842 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4843                          unsigned NumBits, SelectionDAG &DAG,
4844                          const TargetLowering &TLI, DebugLoc dl) {
4845   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4846   EVT ShVT = MVT::v2i64;
4847   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4848   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4849   return DAG.getNode(ISD::BITCAST, dl, VT,
4850                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4851                              DAG.getConstant(NumBits,
4852                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4853 }
4854
4855 SDValue
4856 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4857                                           SelectionDAG &DAG) const {
4858
4859   // Check if the scalar load can be widened into a vector load. And if
4860   // the address is "base + cst" see if the cst can be "absorbed" into
4861   // the shuffle mask.
4862   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4863     SDValue Ptr = LD->getBasePtr();
4864     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4865       return SDValue();
4866     EVT PVT = LD->getValueType(0);
4867     if (PVT != MVT::i32 && PVT != MVT::f32)
4868       return SDValue();
4869
4870     int FI = -1;
4871     int64_t Offset = 0;
4872     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4873       FI = FINode->getIndex();
4874       Offset = 0;
4875     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4876                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4877       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4878       Offset = Ptr.getConstantOperandVal(1);
4879       Ptr = Ptr.getOperand(0);
4880     } else {
4881       return SDValue();
4882     }
4883
4884     // FIXME: 256-bit vector instructions don't require a strict alignment,
4885     // improve this code to support it better.
4886     unsigned RequiredAlign = VT.getSizeInBits()/8;
4887     SDValue Chain = LD->getChain();
4888     // Make sure the stack object alignment is at least 16 or 32.
4889     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4890     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4891       if (MFI->isFixedObjectIndex(FI)) {
4892         // Can't change the alignment. FIXME: It's possible to compute
4893         // the exact stack offset and reference FI + adjust offset instead.
4894         // If someone *really* cares about this. That's the way to implement it.
4895         return SDValue();
4896       } else {
4897         MFI->setObjectAlignment(FI, RequiredAlign);
4898       }
4899     }
4900
4901     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4902     // Ptr + (Offset & ~15).
4903     if (Offset < 0)
4904       return SDValue();
4905     if ((Offset % RequiredAlign) & 3)
4906       return SDValue();
4907     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4908     if (StartOffset)
4909       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4910                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4911
4912     int EltNo = (Offset - StartOffset) >> 2;
4913     unsigned NumElems = VT.getVectorNumElements();
4914
4915     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4916     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4917                              LD->getPointerInfo().getWithOffset(StartOffset),
4918                              false, false, false, 0);
4919
4920     SmallVector<int, 8> Mask;
4921     for (unsigned i = 0; i != NumElems; ++i)
4922       Mask.push_back(EltNo);
4923
4924     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4925   }
4926
4927   return SDValue();
4928 }
4929
4930 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4931 /// vector of type 'VT', see if the elements can be replaced by a single large
4932 /// load which has the same value as a build_vector whose operands are 'elts'.
4933 ///
4934 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4935 ///
4936 /// FIXME: we'd also like to handle the case where the last elements are zero
4937 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4938 /// There's even a handy isZeroNode for that purpose.
4939 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4940                                         DebugLoc &DL, SelectionDAG &DAG) {
4941   EVT EltVT = VT.getVectorElementType();
4942   unsigned NumElems = Elts.size();
4943
4944   LoadSDNode *LDBase = NULL;
4945   unsigned LastLoadedElt = -1U;
4946
4947   // For each element in the initializer, see if we've found a load or an undef.
4948   // If we don't find an initial load element, or later load elements are
4949   // non-consecutive, bail out.
4950   for (unsigned i = 0; i < NumElems; ++i) {
4951     SDValue Elt = Elts[i];
4952
4953     if (!Elt.getNode() ||
4954         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4955       return SDValue();
4956     if (!LDBase) {
4957       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4958         return SDValue();
4959       LDBase = cast<LoadSDNode>(Elt.getNode());
4960       LastLoadedElt = i;
4961       continue;
4962     }
4963     if (Elt.getOpcode() == ISD::UNDEF)
4964       continue;
4965
4966     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4967     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4968       return SDValue();
4969     LastLoadedElt = i;
4970   }
4971
4972   // If we have found an entire vector of loads and undefs, then return a large
4973   // load of the entire vector width starting at the base pointer.  If we found
4974   // consecutive loads for the low half, generate a vzext_load node.
4975   if (LastLoadedElt == NumElems - 1) {
4976     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4977       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4978                          LDBase->getPointerInfo(),
4979                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4980                          LDBase->isInvariant(), 0);
4981     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4982                        LDBase->getPointerInfo(),
4983                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4984                        LDBase->isInvariant(), LDBase->getAlignment());
4985   }
4986   if (NumElems == 4 && LastLoadedElt == 1 &&
4987       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4988     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4989     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4990     SDValue ResNode =
4991         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4992                                 LDBase->getPointerInfo(),
4993                                 LDBase->getAlignment(),
4994                                 false/*isVolatile*/, true/*ReadMem*/,
4995                                 false/*WriteMem*/);
4996     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4997   }
4998   return SDValue();
4999 }
5000
5001 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5002 /// to generate a splat value for the following cases:
5003 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5004 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5005 /// a scalar load, or a constant.
5006 /// The VBROADCAST node is returned when a pattern is found,
5007 /// or SDValue() otherwise.
5008 SDValue
5009 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5010   if (!Subtarget->hasAVX())
5011     return SDValue();
5012
5013   EVT VT = Op.getValueType();
5014   DebugLoc dl = Op.getDebugLoc();
5015
5016   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5017          "Unsupported vector type for broadcast.");
5018
5019   SDValue Ld;
5020   bool ConstSplatVal;
5021
5022   switch (Op.getOpcode()) {
5023     default:
5024       // Unknown pattern found.
5025       return SDValue();
5026
5027     case ISD::BUILD_VECTOR: {
5028       // The BUILD_VECTOR node must be a splat.
5029       if (!isSplatVector(Op.getNode()))
5030         return SDValue();
5031
5032       Ld = Op.getOperand(0);
5033       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5034                      Ld.getOpcode() == ISD::ConstantFP);
5035
5036       // The suspected load node has several users. Make sure that all
5037       // of its users are from the BUILD_VECTOR node.
5038       // Constants may have multiple users.
5039       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5040         return SDValue();
5041       break;
5042     }
5043
5044     case ISD::VECTOR_SHUFFLE: {
5045       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5046
5047       // Shuffles must have a splat mask where the first element is
5048       // broadcasted.
5049       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5050         return SDValue();
5051
5052       SDValue Sc = Op.getOperand(0);
5053       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5054           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5055
5056         if (!Subtarget->hasAVX2())
5057           return SDValue();
5058
5059         // Use the register form of the broadcast instruction available on AVX2.
5060         if (VT.is256BitVector())
5061           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5062         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5063       }
5064
5065       Ld = Sc.getOperand(0);
5066       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5067                        Ld.getOpcode() == ISD::ConstantFP);
5068
5069       // The scalar_to_vector node and the suspected
5070       // load node must have exactly one user.
5071       // Constants may have multiple users.
5072       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5073         return SDValue();
5074       break;
5075     }
5076   }
5077
5078   bool Is256 = VT.getSizeInBits() == 256;
5079
5080   // Handle the broadcasting a single constant scalar from the constant pool
5081   // into a vector. On Sandybridge it is still better to load a constant vector
5082   // from the constant pool and not to broadcast it from a scalar.
5083   if (ConstSplatVal && Subtarget->hasAVX2()) {
5084     EVT CVT = Ld.getValueType();
5085     assert(!CVT.isVector() && "Must not broadcast a vector type");
5086     unsigned ScalarSize = CVT.getSizeInBits();
5087
5088     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5089       const Constant *C = 0;
5090       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5091         C = CI->getConstantIntValue();
5092       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5093         C = CF->getConstantFPValue();
5094
5095       assert(C && "Invalid constant type");
5096
5097       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5098       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5099       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5100                        MachinePointerInfo::getConstantPool(),
5101                        false, false, false, Alignment);
5102
5103       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5104     }
5105   }
5106
5107   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5108   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5109
5110   // Handle AVX2 in-register broadcasts.
5111   if (!IsLoad && Subtarget->hasAVX2() &&
5112       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5113     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5114
5115   // The scalar source must be a normal load.
5116   if (!IsLoad)
5117     return SDValue();
5118
5119   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5120     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5121
5122   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5123   // double since there is no vbroadcastsd xmm
5124   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5125     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5126       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5127   }
5128
5129   // Unsupported broadcast.
5130   return SDValue();
5131 }
5132
5133 SDValue
5134 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5135   DebugLoc dl = Op.getDebugLoc();
5136
5137   EVT VT = Op.getValueType();
5138   EVT ExtVT = VT.getVectorElementType();
5139   unsigned NumElems = Op.getNumOperands();
5140
5141   // Vectors containing all zeros can be matched by pxor and xorps later
5142   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5143     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5144     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5145     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5146       return Op;
5147
5148     return getZeroVector(VT, Subtarget, DAG, dl);
5149   }
5150
5151   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5152   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5153   // vpcmpeqd on 256-bit vectors.
5154   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5155     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5156       return Op;
5157
5158     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5159   }
5160
5161   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5162   if (Broadcast.getNode())
5163     return Broadcast;
5164
5165   unsigned EVTBits = ExtVT.getSizeInBits();
5166
5167   unsigned NumZero  = 0;
5168   unsigned NumNonZero = 0;
5169   unsigned NonZeros = 0;
5170   bool IsAllConstants = true;
5171   SmallSet<SDValue, 8> Values;
5172   for (unsigned i = 0; i < NumElems; ++i) {
5173     SDValue Elt = Op.getOperand(i);
5174     if (Elt.getOpcode() == ISD::UNDEF)
5175       continue;
5176     Values.insert(Elt);
5177     if (Elt.getOpcode() != ISD::Constant &&
5178         Elt.getOpcode() != ISD::ConstantFP)
5179       IsAllConstants = false;
5180     if (X86::isZeroNode(Elt))
5181       NumZero++;
5182     else {
5183       NonZeros |= (1 << i);
5184       NumNonZero++;
5185     }
5186   }
5187
5188   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5189   if (NumNonZero == 0)
5190     return DAG.getUNDEF(VT);
5191
5192   // Special case for single non-zero, non-undef, element.
5193   if (NumNonZero == 1) {
5194     unsigned Idx = CountTrailingZeros_32(NonZeros);
5195     SDValue Item = Op.getOperand(Idx);
5196
5197     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5198     // the value are obviously zero, truncate the value to i32 and do the
5199     // insertion that way.  Only do this if the value is non-constant or if the
5200     // value is a constant being inserted into element 0.  It is cheaper to do
5201     // a constant pool load than it is to do a movd + shuffle.
5202     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5203         (!IsAllConstants || Idx == 0)) {
5204       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5205         // Handle SSE only.
5206         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5207         EVT VecVT = MVT::v4i32;
5208         unsigned VecElts = 4;
5209
5210         // Truncate the value (which may itself be a constant) to i32, and
5211         // convert it to a vector with movd (S2V+shuffle to zero extend).
5212         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5213         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5214         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5215
5216         // Now we have our 32-bit value zero extended in the low element of
5217         // a vector.  If Idx != 0, swizzle it into place.
5218         if (Idx != 0) {
5219           SmallVector<int, 4> Mask;
5220           Mask.push_back(Idx);
5221           for (unsigned i = 1; i != VecElts; ++i)
5222             Mask.push_back(i);
5223           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5224                                       &Mask[0]);
5225         }
5226         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5227       }
5228     }
5229
5230     // If we have a constant or non-constant insertion into the low element of
5231     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5232     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5233     // depending on what the source datatype is.
5234     if (Idx == 0) {
5235       if (NumZero == 0)
5236         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5237
5238       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5239           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5240         if (VT.getSizeInBits() == 256) {
5241           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5242           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5243                              Item, DAG.getIntPtrConstant(0));
5244         }
5245         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5246         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5247         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5248         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5249       }
5250
5251       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5252         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5253         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5254         if (VT.getSizeInBits() == 256) {
5255           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5256           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5257         } else {
5258           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5259           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5260         }
5261         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5262       }
5263     }
5264
5265     // Is it a vector logical left shift?
5266     if (NumElems == 2 && Idx == 1 &&
5267         X86::isZeroNode(Op.getOperand(0)) &&
5268         !X86::isZeroNode(Op.getOperand(1))) {
5269       unsigned NumBits = VT.getSizeInBits();
5270       return getVShift(true, VT,
5271                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5272                                    VT, Op.getOperand(1)),
5273                        NumBits/2, DAG, *this, dl);
5274     }
5275
5276     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5277       return SDValue();
5278
5279     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5280     // is a non-constant being inserted into an element other than the low one,
5281     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5282     // movd/movss) to move this into the low element, then shuffle it into
5283     // place.
5284     if (EVTBits == 32) {
5285       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5286
5287       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5288       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5289       SmallVector<int, 8> MaskVec;
5290       for (unsigned i = 0; i != NumElems; ++i)
5291         MaskVec.push_back(i == Idx ? 0 : 1);
5292       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5293     }
5294   }
5295
5296   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5297   if (Values.size() == 1) {
5298     if (EVTBits == 32) {
5299       // Instead of a shuffle like this:
5300       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5301       // Check if it's possible to issue this instead.
5302       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5303       unsigned Idx = CountTrailingZeros_32(NonZeros);
5304       SDValue Item = Op.getOperand(Idx);
5305       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5306         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5307     }
5308     return SDValue();
5309   }
5310
5311   // A vector full of immediates; various special cases are already
5312   // handled, so this is best done with a single constant-pool load.
5313   if (IsAllConstants)
5314     return SDValue();
5315
5316   // For AVX-length vectors, build the individual 128-bit pieces and use
5317   // shuffles to put them in place.
5318   if (VT.getSizeInBits() == 256) {
5319     SmallVector<SDValue, 32> V;
5320     for (unsigned i = 0; i != NumElems; ++i)
5321       V.push_back(Op.getOperand(i));
5322
5323     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5324
5325     // Build both the lower and upper subvector.
5326     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5327     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5328                                 NumElems/2);
5329
5330     // Recreate the wider vector with the lower and upper part.
5331     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5332   }
5333
5334   // Let legalizer expand 2-wide build_vectors.
5335   if (EVTBits == 64) {
5336     if (NumNonZero == 1) {
5337       // One half is zero or undef.
5338       unsigned Idx = CountTrailingZeros_32(NonZeros);
5339       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5340                                  Op.getOperand(Idx));
5341       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5342     }
5343     return SDValue();
5344   }
5345
5346   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5347   if (EVTBits == 8 && NumElems == 16) {
5348     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5349                                         Subtarget, *this);
5350     if (V.getNode()) return V;
5351   }
5352
5353   if (EVTBits == 16 && NumElems == 8) {
5354     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5355                                       Subtarget, *this);
5356     if (V.getNode()) return V;
5357   }
5358
5359   // If element VT is == 32 bits, turn it into a number of shuffles.
5360   SmallVector<SDValue, 8> V(NumElems);
5361   if (NumElems == 4 && NumZero > 0) {
5362     for (unsigned i = 0; i < 4; ++i) {
5363       bool isZero = !(NonZeros & (1 << i));
5364       if (isZero)
5365         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5366       else
5367         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5368     }
5369
5370     for (unsigned i = 0; i < 2; ++i) {
5371       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5372         default: break;
5373         case 0:
5374           V[i] = V[i*2];  // Must be a zero vector.
5375           break;
5376         case 1:
5377           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5378           break;
5379         case 2:
5380           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5381           break;
5382         case 3:
5383           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5384           break;
5385       }
5386     }
5387
5388     bool Reverse1 = (NonZeros & 0x3) == 2;
5389     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5390     int MaskVec[] = {
5391       Reverse1 ? 1 : 0,
5392       Reverse1 ? 0 : 1,
5393       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5394       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5395     };
5396     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5397   }
5398
5399   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5400     // Check for a build vector of consecutive loads.
5401     for (unsigned i = 0; i < NumElems; ++i)
5402       V[i] = Op.getOperand(i);
5403
5404     // Check for elements which are consecutive loads.
5405     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5406     if (LD.getNode())
5407       return LD;
5408
5409     // For SSE 4.1, use insertps to put the high elements into the low element.
5410     if (getSubtarget()->hasSSE41()) {
5411       SDValue Result;
5412       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5413         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5414       else
5415         Result = DAG.getUNDEF(VT);
5416
5417       for (unsigned i = 1; i < NumElems; ++i) {
5418         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5419         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5420                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5421       }
5422       return Result;
5423     }
5424
5425     // Otherwise, expand into a number of unpckl*, start by extending each of
5426     // our (non-undef) elements to the full vector width with the element in the
5427     // bottom slot of the vector (which generates no code for SSE).
5428     for (unsigned i = 0; i < NumElems; ++i) {
5429       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5430         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5431       else
5432         V[i] = DAG.getUNDEF(VT);
5433     }
5434
5435     // Next, we iteratively mix elements, e.g. for v4f32:
5436     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5437     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5438     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5439     unsigned EltStride = NumElems >> 1;
5440     while (EltStride != 0) {
5441       for (unsigned i = 0; i < EltStride; ++i) {
5442         // If V[i+EltStride] is undef and this is the first round of mixing,
5443         // then it is safe to just drop this shuffle: V[i] is already in the
5444         // right place, the one element (since it's the first round) being
5445         // inserted as undef can be dropped.  This isn't safe for successive
5446         // rounds because they will permute elements within both vectors.
5447         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5448             EltStride == NumElems/2)
5449           continue;
5450
5451         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5452       }
5453       EltStride >>= 1;
5454     }
5455     return V[0];
5456   }
5457   return SDValue();
5458 }
5459
5460 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5461 // them in a MMX register.  This is better than doing a stack convert.
5462 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5463   DebugLoc dl = Op.getDebugLoc();
5464   EVT ResVT = Op.getValueType();
5465
5466   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5467          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5468   int Mask[2];
5469   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5470   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5471   InVec = Op.getOperand(1);
5472   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5473     unsigned NumElts = ResVT.getVectorNumElements();
5474     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5475     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5476                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5477   } else {
5478     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5479     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5480     Mask[0] = 0; Mask[1] = 2;
5481     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5482   }
5483   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5484 }
5485
5486 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5487 // to create 256-bit vectors from two other 128-bit ones.
5488 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5489   DebugLoc dl = Op.getDebugLoc();
5490   EVT ResVT = Op.getValueType();
5491
5492   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5493
5494   SDValue V1 = Op.getOperand(0);
5495   SDValue V2 = Op.getOperand(1);
5496   unsigned NumElems = ResVT.getVectorNumElements();
5497
5498   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5499 }
5500
5501 SDValue
5502 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5503   EVT ResVT = Op.getValueType();
5504
5505   assert(Op.getNumOperands() == 2);
5506   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5507          "Unsupported CONCAT_VECTORS for value type");
5508
5509   // We support concatenate two MMX registers and place them in a MMX register.
5510   // This is better than doing a stack convert.
5511   if (ResVT.is128BitVector())
5512     return LowerMMXCONCAT_VECTORS(Op, DAG);
5513
5514   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5515   // from two other 128-bit ones.
5516   return LowerAVXCONCAT_VECTORS(Op, DAG);
5517 }
5518
5519 // Try to lower a shuffle node into a simple blend instruction.
5520 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5521                                           const X86Subtarget *Subtarget,
5522                                           SelectionDAG &DAG) {
5523   SDValue V1 = SVOp->getOperand(0);
5524   SDValue V2 = SVOp->getOperand(1);
5525   DebugLoc dl = SVOp->getDebugLoc();
5526   MVT VT = SVOp->getValueType(0).getSimpleVT();
5527   unsigned NumElems = VT.getVectorNumElements();
5528
5529   if (!Subtarget->hasSSE41())
5530     return SDValue();
5531
5532   unsigned ISDNo = 0;
5533   MVT OpTy;
5534
5535   switch (VT.SimpleTy) {
5536   default: return SDValue();
5537   case MVT::v8i16:
5538     ISDNo = X86ISD::BLENDPW;
5539     OpTy = MVT::v8i16;
5540     break;
5541   case MVT::v4i32:
5542   case MVT::v4f32:
5543     ISDNo = X86ISD::BLENDPS;
5544     OpTy = MVT::v4f32;
5545     break;
5546   case MVT::v2i64:
5547   case MVT::v2f64:
5548     ISDNo = X86ISD::BLENDPD;
5549     OpTy = MVT::v2f64;
5550     break;
5551   case MVT::v8i32:
5552   case MVT::v8f32:
5553     if (!Subtarget->hasAVX())
5554       return SDValue();
5555     ISDNo = X86ISD::BLENDPS;
5556     OpTy = MVT::v8f32;
5557     break;
5558   case MVT::v4i64:
5559   case MVT::v4f64:
5560     if (!Subtarget->hasAVX())
5561       return SDValue();
5562     ISDNo = X86ISD::BLENDPD;
5563     OpTy = MVT::v4f64;
5564     break;
5565   }
5566   assert(ISDNo && "Invalid Op Number");
5567
5568   unsigned MaskVals = 0;
5569
5570   for (unsigned i = 0; i != NumElems; ++i) {
5571     int EltIdx = SVOp->getMaskElt(i);
5572     if (EltIdx == (int)i || EltIdx < 0)
5573       MaskVals |= (1<<i);
5574     else if (EltIdx == (int)(i + NumElems))
5575       continue; // Bit is set to zero;
5576     else
5577       return SDValue();
5578   }
5579
5580   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5581   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5582   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5583                              DAG.getConstant(MaskVals, MVT::i32));
5584   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5585 }
5586
5587 // v8i16 shuffles - Prefer shuffles in the following order:
5588 // 1. [all]   pshuflw, pshufhw, optional move
5589 // 2. [ssse3] 1 x pshufb
5590 // 3. [ssse3] 2 x pshufb + 1 x por
5591 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5592 SDValue
5593 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5594                                             SelectionDAG &DAG) const {
5595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5596   SDValue V1 = SVOp->getOperand(0);
5597   SDValue V2 = SVOp->getOperand(1);
5598   DebugLoc dl = SVOp->getDebugLoc();
5599   SmallVector<int, 8> MaskVals;
5600
5601   // Determine if more than 1 of the words in each of the low and high quadwords
5602   // of the result come from the same quadword of one of the two inputs.  Undef
5603   // mask values count as coming from any quadword, for better codegen.
5604   unsigned LoQuad[] = { 0, 0, 0, 0 };
5605   unsigned HiQuad[] = { 0, 0, 0, 0 };
5606   std::bitset<4> InputQuads;
5607   for (unsigned i = 0; i < 8; ++i) {
5608     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5609     int EltIdx = SVOp->getMaskElt(i);
5610     MaskVals.push_back(EltIdx);
5611     if (EltIdx < 0) {
5612       ++Quad[0];
5613       ++Quad[1];
5614       ++Quad[2];
5615       ++Quad[3];
5616       continue;
5617     }
5618     ++Quad[EltIdx / 4];
5619     InputQuads.set(EltIdx / 4);
5620   }
5621
5622   int BestLoQuad = -1;
5623   unsigned MaxQuad = 1;
5624   for (unsigned i = 0; i < 4; ++i) {
5625     if (LoQuad[i] > MaxQuad) {
5626       BestLoQuad = i;
5627       MaxQuad = LoQuad[i];
5628     }
5629   }
5630
5631   int BestHiQuad = -1;
5632   MaxQuad = 1;
5633   for (unsigned i = 0; i < 4; ++i) {
5634     if (HiQuad[i] > MaxQuad) {
5635       BestHiQuad = i;
5636       MaxQuad = HiQuad[i];
5637     }
5638   }
5639
5640   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5641   // of the two input vectors, shuffle them into one input vector so only a
5642   // single pshufb instruction is necessary. If There are more than 2 input
5643   // quads, disable the next transformation since it does not help SSSE3.
5644   bool V1Used = InputQuads[0] || InputQuads[1];
5645   bool V2Used = InputQuads[2] || InputQuads[3];
5646   if (Subtarget->hasSSSE3()) {
5647     if (InputQuads.count() == 2 && V1Used && V2Used) {
5648       BestLoQuad = InputQuads[0] ? 0 : 1;
5649       BestHiQuad = InputQuads[2] ? 2 : 3;
5650     }
5651     if (InputQuads.count() > 2) {
5652       BestLoQuad = -1;
5653       BestHiQuad = -1;
5654     }
5655   }
5656
5657   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5658   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5659   // words from all 4 input quadwords.
5660   SDValue NewV;
5661   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5662     int MaskV[] = {
5663       BestLoQuad < 0 ? 0 : BestLoQuad,
5664       BestHiQuad < 0 ? 1 : BestHiQuad
5665     };
5666     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5667                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5668                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5669     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5670
5671     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5672     // source words for the shuffle, to aid later transformations.
5673     bool AllWordsInNewV = true;
5674     bool InOrder[2] = { true, true };
5675     for (unsigned i = 0; i != 8; ++i) {
5676       int idx = MaskVals[i];
5677       if (idx != (int)i)
5678         InOrder[i/4] = false;
5679       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5680         continue;
5681       AllWordsInNewV = false;
5682       break;
5683     }
5684
5685     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5686     if (AllWordsInNewV) {
5687       for (int i = 0; i != 8; ++i) {
5688         int idx = MaskVals[i];
5689         if (idx < 0)
5690           continue;
5691         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5692         if ((idx != i) && idx < 4)
5693           pshufhw = false;
5694         if ((idx != i) && idx > 3)
5695           pshuflw = false;
5696       }
5697       V1 = NewV;
5698       V2Used = false;
5699       BestLoQuad = 0;
5700       BestHiQuad = 1;
5701     }
5702
5703     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5704     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5705     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5706       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5707       unsigned TargetMask = 0;
5708       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5709                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5710       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5711       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5712                              getShufflePSHUFLWImmediate(SVOp);
5713       V1 = NewV.getOperand(0);
5714       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5715     }
5716   }
5717
5718   // If we have SSSE3, and all words of the result are from 1 input vector,
5719   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5720   // is present, fall back to case 4.
5721   if (Subtarget->hasSSSE3()) {
5722     SmallVector<SDValue,16> pshufbMask;
5723
5724     // If we have elements from both input vectors, set the high bit of the
5725     // shuffle mask element to zero out elements that come from V2 in the V1
5726     // mask, and elements that come from V1 in the V2 mask, so that the two
5727     // results can be OR'd together.
5728     bool TwoInputs = V1Used && V2Used;
5729     for (unsigned i = 0; i != 8; ++i) {
5730       int EltIdx = MaskVals[i] * 2;
5731       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5732       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5733       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5734       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5735     }
5736     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5737     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5738                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5739                                  MVT::v16i8, &pshufbMask[0], 16));
5740     if (!TwoInputs)
5741       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5742
5743     // Calculate the shuffle mask for the second input, shuffle it, and
5744     // OR it with the first shuffled input.
5745     pshufbMask.clear();
5746     for (unsigned i = 0; i != 8; ++i) {
5747       int EltIdx = MaskVals[i] * 2;
5748       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5749       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5750       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5751       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5752     }
5753     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5754     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5755                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5756                                  MVT::v16i8, &pshufbMask[0], 16));
5757     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5758     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5759   }
5760
5761   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5762   // and update MaskVals with new element order.
5763   std::bitset<8> InOrder;
5764   if (BestLoQuad >= 0) {
5765     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5766     for (int i = 0; i != 4; ++i) {
5767       int idx = MaskVals[i];
5768       if (idx < 0) {
5769         InOrder.set(i);
5770       } else if ((idx / 4) == BestLoQuad) {
5771         MaskV[i] = idx & 3;
5772         InOrder.set(i);
5773       }
5774     }
5775     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5776                                 &MaskV[0]);
5777
5778     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5779       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5780       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5781                                   NewV.getOperand(0),
5782                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5783     }
5784   }
5785
5786   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5787   // and update MaskVals with the new element order.
5788   if (BestHiQuad >= 0) {
5789     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5790     for (unsigned i = 4; i != 8; ++i) {
5791       int idx = MaskVals[i];
5792       if (idx < 0) {
5793         InOrder.set(i);
5794       } else if ((idx / 4) == BestHiQuad) {
5795         MaskV[i] = (idx & 3) + 4;
5796         InOrder.set(i);
5797       }
5798     }
5799     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5800                                 &MaskV[0]);
5801
5802     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5803       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5804       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5805                                   NewV.getOperand(0),
5806                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5807     }
5808   }
5809
5810   // In case BestHi & BestLo were both -1, which means each quadword has a word
5811   // from each of the four input quadwords, calculate the InOrder bitvector now
5812   // before falling through to the insert/extract cleanup.
5813   if (BestLoQuad == -1 && BestHiQuad == -1) {
5814     NewV = V1;
5815     for (int i = 0; i != 8; ++i)
5816       if (MaskVals[i] < 0 || MaskVals[i] == i)
5817         InOrder.set(i);
5818   }
5819
5820   // The other elements are put in the right place using pextrw and pinsrw.
5821   for (unsigned i = 0; i != 8; ++i) {
5822     if (InOrder[i])
5823       continue;
5824     int EltIdx = MaskVals[i];
5825     if (EltIdx < 0)
5826       continue;
5827     SDValue ExtOp = (EltIdx < 8) ?
5828       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5829                   DAG.getIntPtrConstant(EltIdx)) :
5830       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5831                   DAG.getIntPtrConstant(EltIdx - 8));
5832     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5833                        DAG.getIntPtrConstant(i));
5834   }
5835   return NewV;
5836 }
5837
5838 // v16i8 shuffles - Prefer shuffles in the following order:
5839 // 1. [ssse3] 1 x pshufb
5840 // 2. [ssse3] 2 x pshufb + 1 x por
5841 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5842 static
5843 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5844                                  SelectionDAG &DAG,
5845                                  const X86TargetLowering &TLI) {
5846   SDValue V1 = SVOp->getOperand(0);
5847   SDValue V2 = SVOp->getOperand(1);
5848   DebugLoc dl = SVOp->getDebugLoc();
5849   ArrayRef<int> MaskVals = SVOp->getMask();
5850
5851   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5852
5853   // If we have SSSE3, case 1 is generated when all result bytes come from
5854   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5855   // present, fall back to case 3.
5856
5857   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5858   if (TLI.getSubtarget()->hasSSSE3()) {
5859     SmallVector<SDValue,16> pshufbMask;
5860
5861     // If all result elements are from one input vector, then only translate
5862     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5863     //
5864     // Otherwise, we have elements from both input vectors, and must zero out
5865     // elements that come from V2 in the first mask, and V1 in the second mask
5866     // so that we can OR them together.
5867     for (unsigned i = 0; i != 16; ++i) {
5868       int EltIdx = MaskVals[i];
5869       if (EltIdx < 0 || EltIdx >= 16)
5870         EltIdx = 0x80;
5871       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5872     }
5873     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5874                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5875                                  MVT::v16i8, &pshufbMask[0], 16));
5876     if (V2IsUndef)
5877       return V1;
5878
5879     // Calculate the shuffle mask for the second input, shuffle it, and
5880     // OR it with the first shuffled input.
5881     pshufbMask.clear();
5882     for (unsigned i = 0; i != 16; ++i) {
5883       int EltIdx = MaskVals[i];
5884       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5885       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5886     }
5887     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5888                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5889                                  MVT::v16i8, &pshufbMask[0], 16));
5890     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5891   }
5892
5893   // No SSSE3 - Calculate in place words and then fix all out of place words
5894   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5895   // the 16 different words that comprise the two doublequadword input vectors.
5896   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5897   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5898   SDValue NewV = V1;
5899   for (int i = 0; i != 8; ++i) {
5900     int Elt0 = MaskVals[i*2];
5901     int Elt1 = MaskVals[i*2+1];
5902
5903     // This word of the result is all undef, skip it.
5904     if (Elt0 < 0 && Elt1 < 0)
5905       continue;
5906
5907     // This word of the result is already in the correct place, skip it.
5908     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5909       continue;
5910
5911     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5912     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5913     SDValue InsElt;
5914
5915     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5916     // using a single extract together, load it and store it.
5917     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5918       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5919                            DAG.getIntPtrConstant(Elt1 / 2));
5920       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5921                         DAG.getIntPtrConstant(i));
5922       continue;
5923     }
5924
5925     // If Elt1 is defined, extract it from the appropriate source.  If the
5926     // source byte is not also odd, shift the extracted word left 8 bits
5927     // otherwise clear the bottom 8 bits if we need to do an or.
5928     if (Elt1 >= 0) {
5929       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5930                            DAG.getIntPtrConstant(Elt1 / 2));
5931       if ((Elt1 & 1) == 0)
5932         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5933                              DAG.getConstant(8,
5934                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5935       else if (Elt0 >= 0)
5936         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5937                              DAG.getConstant(0xFF00, MVT::i16));
5938     }
5939     // If Elt0 is defined, extract it from the appropriate source.  If the
5940     // source byte is not also even, shift the extracted word right 8 bits. If
5941     // Elt1 was also defined, OR the extracted values together before
5942     // inserting them in the result.
5943     if (Elt0 >= 0) {
5944       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5945                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5946       if ((Elt0 & 1) != 0)
5947         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5948                               DAG.getConstant(8,
5949                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5950       else if (Elt1 >= 0)
5951         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5952                              DAG.getConstant(0x00FF, MVT::i16));
5953       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5954                          : InsElt0;
5955     }
5956     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5957                        DAG.getIntPtrConstant(i));
5958   }
5959   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5960 }
5961
5962 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5963 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5964 /// done when every pair / quad of shuffle mask elements point to elements in
5965 /// the right sequence. e.g.
5966 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5967 static
5968 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5969                                  SelectionDAG &DAG, DebugLoc dl) {
5970   MVT VT = SVOp->getValueType(0).getSimpleVT();
5971   unsigned NumElems = VT.getVectorNumElements();
5972   MVT NewVT;
5973   unsigned Scale;
5974   switch (VT.SimpleTy) {
5975   default: llvm_unreachable("Unexpected!");
5976   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5977   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5978   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5979   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5980   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5981   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5982   }
5983
5984   SmallVector<int, 8> MaskVec;
5985   for (unsigned i = 0; i != NumElems; i += Scale) {
5986     int StartIdx = -1;
5987     for (unsigned j = 0; j != Scale; ++j) {
5988       int EltIdx = SVOp->getMaskElt(i+j);
5989       if (EltIdx < 0)
5990         continue;
5991       if (StartIdx < 0)
5992         StartIdx = (EltIdx / Scale);
5993       if (EltIdx != (int)(StartIdx*Scale + j))
5994         return SDValue();
5995     }
5996     MaskVec.push_back(StartIdx);
5997   }
5998
5999   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6000   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6001   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6002 }
6003
6004 /// getVZextMovL - Return a zero-extending vector move low node.
6005 ///
6006 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6007                             SDValue SrcOp, SelectionDAG &DAG,
6008                             const X86Subtarget *Subtarget, DebugLoc dl) {
6009   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6010     LoadSDNode *LD = NULL;
6011     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6012       LD = dyn_cast<LoadSDNode>(SrcOp);
6013     if (!LD) {
6014       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6015       // instead.
6016       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6017       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6018           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6019           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6020           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6021         // PR2108
6022         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6023         return DAG.getNode(ISD::BITCAST, dl, VT,
6024                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6025                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6026                                                    OpVT,
6027                                                    SrcOp.getOperand(0)
6028                                                           .getOperand(0))));
6029       }
6030     }
6031   }
6032
6033   return DAG.getNode(ISD::BITCAST, dl, VT,
6034                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6035                                  DAG.getNode(ISD::BITCAST, dl,
6036                                              OpVT, SrcOp)));
6037 }
6038
6039 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6040 /// which could not be matched by any known target speficic shuffle
6041 static SDValue
6042 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6043
6044   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6045   if (NewOp.getNode())
6046     return NewOp;
6047
6048   EVT VT = SVOp->getValueType(0);
6049
6050   unsigned NumElems = VT.getVectorNumElements();
6051   unsigned NumLaneElems = NumElems / 2;
6052
6053   DebugLoc dl = SVOp->getDebugLoc();
6054   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6055   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6056   SDValue Output[2];
6057
6058   SmallVector<int, 16> Mask;
6059   for (unsigned l = 0; l < 2; ++l) {
6060     // Build a shuffle mask for the output, discovering on the fly which
6061     // input vectors to use as shuffle operands (recorded in InputUsed).
6062     // If building a suitable shuffle vector proves too hard, then bail
6063     // out with UseBuildVector set.
6064     bool UseBuildVector = false;
6065     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6066     unsigned LaneStart = l * NumLaneElems;
6067     for (unsigned i = 0; i != NumLaneElems; ++i) {
6068       // The mask element.  This indexes into the input.
6069       int Idx = SVOp->getMaskElt(i+LaneStart);
6070       if (Idx < 0) {
6071         // the mask element does not index into any input vector.
6072         Mask.push_back(-1);
6073         continue;
6074       }
6075
6076       // The input vector this mask element indexes into.
6077       int Input = Idx / NumLaneElems;
6078
6079       // Turn the index into an offset from the start of the input vector.
6080       Idx -= Input * NumLaneElems;
6081
6082       // Find or create a shuffle vector operand to hold this input.
6083       unsigned OpNo;
6084       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6085         if (InputUsed[OpNo] == Input)
6086           // This input vector is already an operand.
6087           break;
6088         if (InputUsed[OpNo] < 0) {
6089           // Create a new operand for this input vector.
6090           InputUsed[OpNo] = Input;
6091           break;
6092         }
6093       }
6094
6095       if (OpNo >= array_lengthof(InputUsed)) {
6096         // More than two input vectors used!  Give up on trying to create a
6097         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6098         UseBuildVector = true;
6099         break;
6100       }
6101
6102       // Add the mask index for the new shuffle vector.
6103       Mask.push_back(Idx + OpNo * NumLaneElems);
6104     }
6105
6106     if (UseBuildVector) {
6107       SmallVector<SDValue, 16> SVOps;
6108       for (unsigned i = 0; i != NumLaneElems; ++i) {
6109         // The mask element.  This indexes into the input.
6110         int Idx = SVOp->getMaskElt(i+LaneStart);
6111         if (Idx < 0) {
6112           SVOps.push_back(DAG.getUNDEF(EltVT));
6113           continue;
6114         }
6115
6116         // The input vector this mask element indexes into.
6117         int Input = Idx / NumElems;
6118
6119         // Turn the index into an offset from the start of the input vector.
6120         Idx -= Input * NumElems;
6121
6122         // Extract the vector element by hand.
6123         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6124                                     SVOp->getOperand(Input),
6125                                     DAG.getIntPtrConstant(Idx)));
6126       }
6127
6128       // Construct the output using a BUILD_VECTOR.
6129       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6130                               SVOps.size());
6131     } else if (InputUsed[0] < 0) {
6132       // No input vectors were used! The result is undefined.
6133       Output[l] = DAG.getUNDEF(NVT);
6134     } else {
6135       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6136                                         (InputUsed[0] % 2) * NumLaneElems,
6137                                         DAG, dl);
6138       // If only one input was used, use an undefined vector for the other.
6139       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6140         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6141                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6142       // At least one input vector was used. Create a new shuffle vector.
6143       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6144     }
6145
6146     Mask.clear();
6147   }
6148
6149   // Concatenate the result back
6150   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6151 }
6152
6153 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6154 /// 4 elements, and match them with several different shuffle types.
6155 static SDValue
6156 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6157   SDValue V1 = SVOp->getOperand(0);
6158   SDValue V2 = SVOp->getOperand(1);
6159   DebugLoc dl = SVOp->getDebugLoc();
6160   EVT VT = SVOp->getValueType(0);
6161
6162   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6163
6164   std::pair<int, int> Locs[4];
6165   int Mask1[] = { -1, -1, -1, -1 };
6166   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6167
6168   unsigned NumHi = 0;
6169   unsigned NumLo = 0;
6170   for (unsigned i = 0; i != 4; ++i) {
6171     int Idx = PermMask[i];
6172     if (Idx < 0) {
6173       Locs[i] = std::make_pair(-1, -1);
6174     } else {
6175       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6176       if (Idx < 4) {
6177         Locs[i] = std::make_pair(0, NumLo);
6178         Mask1[NumLo] = Idx;
6179         NumLo++;
6180       } else {
6181         Locs[i] = std::make_pair(1, NumHi);
6182         if (2+NumHi < 4)
6183           Mask1[2+NumHi] = Idx;
6184         NumHi++;
6185       }
6186     }
6187   }
6188
6189   if (NumLo <= 2 && NumHi <= 2) {
6190     // If no more than two elements come from either vector. This can be
6191     // implemented with two shuffles. First shuffle gather the elements.
6192     // The second shuffle, which takes the first shuffle as both of its
6193     // vector operands, put the elements into the right order.
6194     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6195
6196     int Mask2[] = { -1, -1, -1, -1 };
6197
6198     for (unsigned i = 0; i != 4; ++i)
6199       if (Locs[i].first != -1) {
6200         unsigned Idx = (i < 2) ? 0 : 4;
6201         Idx += Locs[i].first * 2 + Locs[i].second;
6202         Mask2[i] = Idx;
6203       }
6204
6205     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6206   }
6207
6208   if (NumLo == 3 || NumHi == 3) {
6209     // Otherwise, we must have three elements from one vector, call it X, and
6210     // one element from the other, call it Y.  First, use a shufps to build an
6211     // intermediate vector with the one element from Y and the element from X
6212     // that will be in the same half in the final destination (the indexes don't
6213     // matter). Then, use a shufps to build the final vector, taking the half
6214     // containing the element from Y from the intermediate, and the other half
6215     // from X.
6216     if (NumHi == 3) {
6217       // Normalize it so the 3 elements come from V1.
6218       CommuteVectorShuffleMask(PermMask, 4);
6219       std::swap(V1, V2);
6220     }
6221
6222     // Find the element from V2.
6223     unsigned HiIndex;
6224     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6225       int Val = PermMask[HiIndex];
6226       if (Val < 0)
6227         continue;
6228       if (Val >= 4)
6229         break;
6230     }
6231
6232     Mask1[0] = PermMask[HiIndex];
6233     Mask1[1] = -1;
6234     Mask1[2] = PermMask[HiIndex^1];
6235     Mask1[3] = -1;
6236     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6237
6238     if (HiIndex >= 2) {
6239       Mask1[0] = PermMask[0];
6240       Mask1[1] = PermMask[1];
6241       Mask1[2] = HiIndex & 1 ? 6 : 4;
6242       Mask1[3] = HiIndex & 1 ? 4 : 6;
6243       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6244     }
6245
6246     Mask1[0] = HiIndex & 1 ? 2 : 0;
6247     Mask1[1] = HiIndex & 1 ? 0 : 2;
6248     Mask1[2] = PermMask[2];
6249     Mask1[3] = PermMask[3];
6250     if (Mask1[2] >= 0)
6251       Mask1[2] += 4;
6252     if (Mask1[3] >= 0)
6253       Mask1[3] += 4;
6254     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6255   }
6256
6257   // Break it into (shuffle shuffle_hi, shuffle_lo).
6258   int LoMask[] = { -1, -1, -1, -1 };
6259   int HiMask[] = { -1, -1, -1, -1 };
6260
6261   int *MaskPtr = LoMask;
6262   unsigned MaskIdx = 0;
6263   unsigned LoIdx = 0;
6264   unsigned HiIdx = 2;
6265   for (unsigned i = 0; i != 4; ++i) {
6266     if (i == 2) {
6267       MaskPtr = HiMask;
6268       MaskIdx = 1;
6269       LoIdx = 0;
6270       HiIdx = 2;
6271     }
6272     int Idx = PermMask[i];
6273     if (Idx < 0) {
6274       Locs[i] = std::make_pair(-1, -1);
6275     } else if (Idx < 4) {
6276       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6277       MaskPtr[LoIdx] = Idx;
6278       LoIdx++;
6279     } else {
6280       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6281       MaskPtr[HiIdx] = Idx;
6282       HiIdx++;
6283     }
6284   }
6285
6286   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6287   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6288   int MaskOps[] = { -1, -1, -1, -1 };
6289   for (unsigned i = 0; i != 4; ++i)
6290     if (Locs[i].first != -1)
6291       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6292   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6293 }
6294
6295 static bool MayFoldVectorLoad(SDValue V) {
6296   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6297     V = V.getOperand(0);
6298   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6299     V = V.getOperand(0);
6300   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6301       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6302     // BUILD_VECTOR (load), undef
6303     V = V.getOperand(0);
6304   if (MayFoldLoad(V))
6305     return true;
6306   return false;
6307 }
6308
6309 // FIXME: the version above should always be used. Since there's
6310 // a bug where several vector shuffles can't be folded because the
6311 // DAG is not updated during lowering and a node claims to have two
6312 // uses while it only has one, use this version, and let isel match
6313 // another instruction if the load really happens to have more than
6314 // one use. Remove this version after this bug get fixed.
6315 // rdar://8434668, PR8156
6316 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6317   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6318     V = V.getOperand(0);
6319   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6320     V = V.getOperand(0);
6321   if (ISD::isNormalLoad(V.getNode()))
6322     return true;
6323   return false;
6324 }
6325
6326 static
6327 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6328   EVT VT = Op.getValueType();
6329
6330   // Canonizalize to v2f64.
6331   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6332   return DAG.getNode(ISD::BITCAST, dl, VT,
6333                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6334                                           V1, DAG));
6335 }
6336
6337 static
6338 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6339                         bool HasSSE2) {
6340   SDValue V1 = Op.getOperand(0);
6341   SDValue V2 = Op.getOperand(1);
6342   EVT VT = Op.getValueType();
6343
6344   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6345
6346   if (HasSSE2 && VT == MVT::v2f64)
6347     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6348
6349   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6350   return DAG.getNode(ISD::BITCAST, dl, VT,
6351                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6352                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6353                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6354 }
6355
6356 static
6357 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6358   SDValue V1 = Op.getOperand(0);
6359   SDValue V2 = Op.getOperand(1);
6360   EVT VT = Op.getValueType();
6361
6362   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6363          "unsupported shuffle type");
6364
6365   if (V2.getOpcode() == ISD::UNDEF)
6366     V2 = V1;
6367
6368   // v4i32 or v4f32
6369   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6370 }
6371
6372 static
6373 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6374   SDValue V1 = Op.getOperand(0);
6375   SDValue V2 = Op.getOperand(1);
6376   EVT VT = Op.getValueType();
6377   unsigned NumElems = VT.getVectorNumElements();
6378
6379   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6380   // operand of these instructions is only memory, so check if there's a
6381   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6382   // same masks.
6383   bool CanFoldLoad = false;
6384
6385   // Trivial case, when V2 comes from a load.
6386   if (MayFoldVectorLoad(V2))
6387     CanFoldLoad = true;
6388
6389   // When V1 is a load, it can be folded later into a store in isel, example:
6390   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6391   //    turns into:
6392   //  (MOVLPSmr addr:$src1, VR128:$src2)
6393   // So, recognize this potential and also use MOVLPS or MOVLPD
6394   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6395     CanFoldLoad = true;
6396
6397   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6398   if (CanFoldLoad) {
6399     if (HasSSE2 && NumElems == 2)
6400       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6401
6402     if (NumElems == 4)
6403       // If we don't care about the second element, proceed to use movss.
6404       if (SVOp->getMaskElt(1) != -1)
6405         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6406   }
6407
6408   // movl and movlp will both match v2i64, but v2i64 is never matched by
6409   // movl earlier because we make it strict to avoid messing with the movlp load
6410   // folding logic (see the code above getMOVLP call). Match it here then,
6411   // this is horrible, but will stay like this until we move all shuffle
6412   // matching to x86 specific nodes. Note that for the 1st condition all
6413   // types are matched with movsd.
6414   if (HasSSE2) {
6415     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6416     // as to remove this logic from here, as much as possible
6417     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6418       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6419     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6420   }
6421
6422   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6423
6424   // Invert the operand order and use SHUFPS to match it.
6425   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6426                               getShuffleSHUFImmediate(SVOp), DAG);
6427 }
6428
6429 SDValue
6430 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6432   EVT VT = Op.getValueType();
6433   DebugLoc dl = Op.getDebugLoc();
6434   SDValue V1 = Op.getOperand(0);
6435   SDValue V2 = Op.getOperand(1);
6436
6437   if (isZeroShuffle(SVOp))
6438     return getZeroVector(VT, Subtarget, DAG, dl);
6439
6440   // Handle splat operations
6441   if (SVOp->isSplat()) {
6442     unsigned NumElem = VT.getVectorNumElements();
6443     int Size = VT.getSizeInBits();
6444
6445     // Use vbroadcast whenever the splat comes from a foldable load
6446     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6447     if (Broadcast.getNode())
6448       return Broadcast;
6449
6450     // Handle splats by matching through known shuffle masks
6451     if ((Size == 128 && NumElem <= 4) ||
6452         (Size == 256 && NumElem < 8))
6453       return SDValue();
6454
6455     // All remaning splats are promoted to target supported vector shuffles.
6456     return PromoteSplat(SVOp, DAG);
6457   }
6458
6459   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6460   // do it!
6461   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6462       VT == MVT::v16i16 || VT == MVT::v32i8) {
6463     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6464     if (NewOp.getNode())
6465       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6466   } else if ((VT == MVT::v4i32 ||
6467              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6468     // FIXME: Figure out a cleaner way to do this.
6469     // Try to make use of movq to zero out the top part.
6470     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6471       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6472       if (NewOp.getNode()) {
6473         EVT NewVT = NewOp.getValueType();
6474         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6475                                NewVT, true, false))
6476           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6477                               DAG, Subtarget, dl);
6478       }
6479     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6480       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6481       if (NewOp.getNode()) {
6482         EVT NewVT = NewOp.getValueType();
6483         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6484           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6485                               DAG, Subtarget, dl);
6486       }
6487     }
6488   }
6489   return SDValue();
6490 }
6491
6492 SDValue
6493 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6494   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6495   SDValue V1 = Op.getOperand(0);
6496   SDValue V2 = Op.getOperand(1);
6497   EVT VT = Op.getValueType();
6498   DebugLoc dl = Op.getDebugLoc();
6499   unsigned NumElems = VT.getVectorNumElements();
6500   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6501   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6502   bool V1IsSplat = false;
6503   bool V2IsSplat = false;
6504   bool HasSSE2 = Subtarget->hasSSE2();
6505   bool HasAVX    = Subtarget->hasAVX();
6506   bool HasAVX2   = Subtarget->hasAVX2();
6507   MachineFunction &MF = DAG.getMachineFunction();
6508   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6509
6510   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6511
6512   if (V1IsUndef && V2IsUndef)
6513     return DAG.getUNDEF(VT);
6514
6515   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6516
6517   // Vector shuffle lowering takes 3 steps:
6518   //
6519   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6520   //    narrowing and commutation of operands should be handled.
6521   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6522   //    shuffle nodes.
6523   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6524   //    so the shuffle can be broken into other shuffles and the legalizer can
6525   //    try the lowering again.
6526   //
6527   // The general idea is that no vector_shuffle operation should be left to
6528   // be matched during isel, all of them must be converted to a target specific
6529   // node here.
6530
6531   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6532   // narrowing and commutation of operands should be handled. The actual code
6533   // doesn't include all of those, work in progress...
6534   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6535   if (NewOp.getNode())
6536     return NewOp;
6537
6538   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6539
6540   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6541   // unpckh_undef). Only use pshufd if speed is more important than size.
6542   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6543     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6544   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6545     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6546
6547   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6548       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6549     return getMOVDDup(Op, dl, V1, DAG);
6550
6551   if (isMOVHLPS_v_undef_Mask(M, VT))
6552     return getMOVHighToLow(Op, dl, DAG);
6553
6554   // Use to match splats
6555   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6556       (VT == MVT::v2f64 || VT == MVT::v2i64))
6557     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6558
6559   if (isPSHUFDMask(M, VT)) {
6560     // The actual implementation will match the mask in the if above and then
6561     // during isel it can match several different instructions, not only pshufd
6562     // as its name says, sad but true, emulate the behavior for now...
6563     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6564       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6565
6566     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6567
6568     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6569       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6570
6571     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6572       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6573
6574     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6575                                 TargetMask, DAG);
6576   }
6577
6578   // Check if this can be converted into a logical shift.
6579   bool isLeft = false;
6580   unsigned ShAmt = 0;
6581   SDValue ShVal;
6582   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6583   if (isShift && ShVal.hasOneUse()) {
6584     // If the shifted value has multiple uses, it may be cheaper to use
6585     // v_set0 + movlhps or movhlps, etc.
6586     EVT EltVT = VT.getVectorElementType();
6587     ShAmt *= EltVT.getSizeInBits();
6588     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6589   }
6590
6591   if (isMOVLMask(M, VT)) {
6592     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6593       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6594     if (!isMOVLPMask(M, VT)) {
6595       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6596         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6597
6598       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6599         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6600     }
6601   }
6602
6603   // FIXME: fold these into legal mask.
6604   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6605     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6606
6607   if (isMOVHLPSMask(M, VT))
6608     return getMOVHighToLow(Op, dl, DAG);
6609
6610   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6611     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6612
6613   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6614     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6615
6616   if (isMOVLPMask(M, VT))
6617     return getMOVLP(Op, dl, DAG, HasSSE2);
6618
6619   if (ShouldXformToMOVHLPS(M, VT) ||
6620       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6621     return CommuteVectorShuffle(SVOp, DAG);
6622
6623   if (isShift) {
6624     // No better options. Use a vshldq / vsrldq.
6625     EVT EltVT = VT.getVectorElementType();
6626     ShAmt *= EltVT.getSizeInBits();
6627     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6628   }
6629
6630   bool Commuted = false;
6631   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6632   // 1,1,1,1 -> v8i16 though.
6633   V1IsSplat = isSplatVector(V1.getNode());
6634   V2IsSplat = isSplatVector(V2.getNode());
6635
6636   // Canonicalize the splat or undef, if present, to be on the RHS.
6637   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6638     CommuteVectorShuffleMask(M, NumElems);
6639     std::swap(V1, V2);
6640     std::swap(V1IsSplat, V2IsSplat);
6641     Commuted = true;
6642   }
6643
6644   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6645     // Shuffling low element of v1 into undef, just return v1.
6646     if (V2IsUndef)
6647       return V1;
6648     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6649     // the instruction selector will not match, so get a canonical MOVL with
6650     // swapped operands to undo the commute.
6651     return getMOVL(DAG, dl, VT, V2, V1);
6652   }
6653
6654   if (isUNPCKLMask(M, VT, HasAVX2))
6655     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6656
6657   if (isUNPCKHMask(M, VT, HasAVX2))
6658     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6659
6660   if (V2IsSplat) {
6661     // Normalize mask so all entries that point to V2 points to its first
6662     // element then try to match unpck{h|l} again. If match, return a
6663     // new vector_shuffle with the corrected mask.p
6664     SmallVector<int, 8> NewMask(M.begin(), M.end());
6665     NormalizeMask(NewMask, NumElems);
6666     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6667       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6668     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6669       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6670   }
6671
6672   if (Commuted) {
6673     // Commute is back and try unpck* again.
6674     // FIXME: this seems wrong.
6675     CommuteVectorShuffleMask(M, NumElems);
6676     std::swap(V1, V2);
6677     std::swap(V1IsSplat, V2IsSplat);
6678     Commuted = false;
6679
6680     if (isUNPCKLMask(M, VT, HasAVX2))
6681       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6682
6683     if (isUNPCKHMask(M, VT, HasAVX2))
6684       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6685   }
6686
6687   // Normalize the node to match x86 shuffle ops if needed
6688   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6689     return CommuteVectorShuffle(SVOp, DAG);
6690
6691   // The checks below are all present in isShuffleMaskLegal, but they are
6692   // inlined here right now to enable us to directly emit target specific
6693   // nodes, and remove one by one until they don't return Op anymore.
6694
6695   if (isPALIGNRMask(M, VT, Subtarget))
6696     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6697                                 getShufflePALIGNRImmediate(SVOp),
6698                                 DAG);
6699
6700   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6701       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6702     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6703       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6704   }
6705
6706   if (isPSHUFHWMask(M, VT, HasAVX2))
6707     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6708                                 getShufflePSHUFHWImmediate(SVOp),
6709                                 DAG);
6710
6711   if (isPSHUFLWMask(M, VT, HasAVX2))
6712     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6713                                 getShufflePSHUFLWImmediate(SVOp),
6714                                 DAG);
6715
6716   if (isSHUFPMask(M, VT, HasAVX))
6717     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6718                                 getShuffleSHUFImmediate(SVOp), DAG);
6719
6720   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6721     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6722   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6723     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6724
6725   //===--------------------------------------------------------------------===//
6726   // Generate target specific nodes for 128 or 256-bit shuffles only
6727   // supported in the AVX instruction set.
6728   //
6729
6730   // Handle VMOVDDUPY permutations
6731   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6732     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6733
6734   // Handle VPERMILPS/D* permutations
6735   if (isVPERMILPMask(M, VT, HasAVX)) {
6736     if (HasAVX2 && VT == MVT::v8i32)
6737       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6738                                   getShuffleSHUFImmediate(SVOp), DAG);
6739     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6740                                 getShuffleSHUFImmediate(SVOp), DAG);
6741   }
6742
6743   // Handle VPERM2F128/VPERM2I128 permutations
6744   if (isVPERM2X128Mask(M, VT, HasAVX))
6745     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6746                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6747
6748   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6749   if (BlendOp.getNode())
6750     return BlendOp;
6751
6752   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6753     SmallVector<SDValue, 8> permclMask;
6754     for (unsigned i = 0; i != 8; ++i) {
6755       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6756     }
6757     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6758                                &permclMask[0], 8);
6759     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6760     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6761                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6762   }
6763
6764   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6765     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6766                                 getShuffleCLImmediate(SVOp), DAG);
6767
6768
6769   //===--------------------------------------------------------------------===//
6770   // Since no target specific shuffle was selected for this generic one,
6771   // lower it into other known shuffles. FIXME: this isn't true yet, but
6772   // this is the plan.
6773   //
6774
6775   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6776   if (VT == MVT::v8i16) {
6777     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6778     if (NewOp.getNode())
6779       return NewOp;
6780   }
6781
6782   if (VT == MVT::v16i8) {
6783     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6784     if (NewOp.getNode())
6785       return NewOp;
6786   }
6787
6788   // Handle all 128-bit wide vectors with 4 elements, and match them with
6789   // several different shuffle types.
6790   if (NumElems == 4 && VT.getSizeInBits() == 128)
6791     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6792
6793   // Handle general 256-bit shuffles
6794   if (VT.is256BitVector())
6795     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6796
6797   return SDValue();
6798 }
6799
6800 SDValue
6801 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6802                                                 SelectionDAG &DAG) const {
6803   EVT VT = Op.getValueType();
6804   DebugLoc dl = Op.getDebugLoc();
6805
6806   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6807     return SDValue();
6808
6809   if (VT.getSizeInBits() == 8) {
6810     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6811                                     Op.getOperand(0), Op.getOperand(1));
6812     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6813                                     DAG.getValueType(VT));
6814     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6815   }
6816
6817   if (VT.getSizeInBits() == 16) {
6818     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6819     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6820     if (Idx == 0)
6821       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6822                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6823                                      DAG.getNode(ISD::BITCAST, dl,
6824                                                  MVT::v4i32,
6825                                                  Op.getOperand(0)),
6826                                      Op.getOperand(1)));
6827     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6828                                     Op.getOperand(0), Op.getOperand(1));
6829     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6830                                     DAG.getValueType(VT));
6831     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6832   }
6833
6834   if (VT == MVT::f32) {
6835     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6836     // the result back to FR32 register. It's only worth matching if the
6837     // result has a single use which is a store or a bitcast to i32.  And in
6838     // the case of a store, it's not worth it if the index is a constant 0,
6839     // because a MOVSSmr can be used instead, which is smaller and faster.
6840     if (!Op.hasOneUse())
6841       return SDValue();
6842     SDNode *User = *Op.getNode()->use_begin();
6843     if ((User->getOpcode() != ISD::STORE ||
6844          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6845           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6846         (User->getOpcode() != ISD::BITCAST ||
6847          User->getValueType(0) != MVT::i32))
6848       return SDValue();
6849     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6850                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6851                                               Op.getOperand(0)),
6852                                               Op.getOperand(1));
6853     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6854   }
6855
6856   if (VT == MVT::i32 || VT == MVT::i64) {
6857     // ExtractPS/pextrq works with constant index.
6858     if (isa<ConstantSDNode>(Op.getOperand(1)))
6859       return Op;
6860   }
6861   return SDValue();
6862 }
6863
6864
6865 SDValue
6866 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6867                                            SelectionDAG &DAG) const {
6868   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6869     return SDValue();
6870
6871   SDValue Vec = Op.getOperand(0);
6872   EVT VecVT = Vec.getValueType();
6873
6874   // If this is a 256-bit vector result, first extract the 128-bit vector and
6875   // then extract the element from the 128-bit vector.
6876   if (VecVT.getSizeInBits() == 256) {
6877     DebugLoc dl = Op.getNode()->getDebugLoc();
6878     unsigned NumElems = VecVT.getVectorNumElements();
6879     SDValue Idx = Op.getOperand(1);
6880     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6881
6882     // Get the 128-bit vector.
6883     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6884
6885     if (IdxVal >= NumElems/2)
6886       IdxVal -= NumElems/2;
6887     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6888                        DAG.getConstant(IdxVal, MVT::i32));
6889   }
6890
6891   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6892
6893   if (Subtarget->hasSSE41()) {
6894     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6895     if (Res.getNode())
6896       return Res;
6897   }
6898
6899   EVT VT = Op.getValueType();
6900   DebugLoc dl = Op.getDebugLoc();
6901   // TODO: handle v16i8.
6902   if (VT.getSizeInBits() == 16) {
6903     SDValue Vec = Op.getOperand(0);
6904     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6905     if (Idx == 0)
6906       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6907                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6908                                      DAG.getNode(ISD::BITCAST, dl,
6909                                                  MVT::v4i32, Vec),
6910                                      Op.getOperand(1)));
6911     // Transform it so it match pextrw which produces a 32-bit result.
6912     EVT EltVT = MVT::i32;
6913     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6914                                     Op.getOperand(0), Op.getOperand(1));
6915     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6916                                     DAG.getValueType(VT));
6917     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6918   }
6919
6920   if (VT.getSizeInBits() == 32) {
6921     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6922     if (Idx == 0)
6923       return Op;
6924
6925     // SHUFPS the element to the lowest double word, then movss.
6926     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6927     EVT VVT = Op.getOperand(0).getValueType();
6928     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6929                                        DAG.getUNDEF(VVT), Mask);
6930     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6931                        DAG.getIntPtrConstant(0));
6932   }
6933
6934   if (VT.getSizeInBits() == 64) {
6935     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6936     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6937     //        to match extract_elt for f64.
6938     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6939     if (Idx == 0)
6940       return Op;
6941
6942     // UNPCKHPD the element to the lowest double word, then movsd.
6943     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6944     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6945     int Mask[2] = { 1, -1 };
6946     EVT VVT = Op.getOperand(0).getValueType();
6947     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6948                                        DAG.getUNDEF(VVT), Mask);
6949     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6950                        DAG.getIntPtrConstant(0));
6951   }
6952
6953   return SDValue();
6954 }
6955
6956 SDValue
6957 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6958                                                SelectionDAG &DAG) const {
6959   EVT VT = Op.getValueType();
6960   EVT EltVT = VT.getVectorElementType();
6961   DebugLoc dl = Op.getDebugLoc();
6962
6963   SDValue N0 = Op.getOperand(0);
6964   SDValue N1 = Op.getOperand(1);
6965   SDValue N2 = Op.getOperand(2);
6966
6967   if (VT.getSizeInBits() == 256)
6968     return SDValue();
6969
6970   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6971       isa<ConstantSDNode>(N2)) {
6972     unsigned Opc;
6973     if (VT == MVT::v8i16)
6974       Opc = X86ISD::PINSRW;
6975     else if (VT == MVT::v16i8)
6976       Opc = X86ISD::PINSRB;
6977     else
6978       Opc = X86ISD::PINSRB;
6979
6980     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6981     // argument.
6982     if (N1.getValueType() != MVT::i32)
6983       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6984     if (N2.getValueType() != MVT::i32)
6985       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6986     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6987   }
6988
6989   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6990     // Bits [7:6] of the constant are the source select.  This will always be
6991     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6992     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6993     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6994     // Bits [5:4] of the constant are the destination select.  This is the
6995     //  value of the incoming immediate.
6996     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6997     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6998     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6999     // Create this as a scalar to vector..
7000     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7001     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7002   }
7003
7004   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7005     // PINSR* works with constant index.
7006     return Op;
7007   }
7008   return SDValue();
7009 }
7010
7011 SDValue
7012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7013   EVT VT = Op.getValueType();
7014   EVT EltVT = VT.getVectorElementType();
7015
7016   DebugLoc dl = Op.getDebugLoc();
7017   SDValue N0 = Op.getOperand(0);
7018   SDValue N1 = Op.getOperand(1);
7019   SDValue N2 = Op.getOperand(2);
7020
7021   // If this is a 256-bit vector result, first extract the 128-bit vector,
7022   // insert the element into the extracted half and then place it back.
7023   if (VT.getSizeInBits() == 256) {
7024     if (!isa<ConstantSDNode>(N2))
7025       return SDValue();
7026
7027     // Get the desired 128-bit vector half.
7028     unsigned NumElems = VT.getVectorNumElements();
7029     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7030     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7031
7032     // Insert the element into the desired half.
7033     bool Upper = IdxVal >= NumElems/2;
7034     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7035                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7036
7037     // Insert the changed part back to the 256-bit vector
7038     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7039   }
7040
7041   if (Subtarget->hasSSE41())
7042     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7043
7044   if (EltVT == MVT::i8)
7045     return SDValue();
7046
7047   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7048     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7049     // as its second argument.
7050     if (N1.getValueType() != MVT::i32)
7051       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7052     if (N2.getValueType() != MVT::i32)
7053       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7054     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7055   }
7056   return SDValue();
7057 }
7058
7059 SDValue
7060 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7061   LLVMContext *Context = DAG.getContext();
7062   DebugLoc dl = Op.getDebugLoc();
7063   EVT OpVT = Op.getValueType();
7064
7065   // If this is a 256-bit vector result, first insert into a 128-bit
7066   // vector and then insert into the 256-bit vector.
7067   if (OpVT.getSizeInBits() > 128) {
7068     // Insert into a 128-bit vector.
7069     EVT VT128 = EVT::getVectorVT(*Context,
7070                                  OpVT.getVectorElementType(),
7071                                  OpVT.getVectorNumElements() / 2);
7072
7073     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7074
7075     // Insert the 128-bit vector.
7076     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7077   }
7078
7079   if (OpVT == MVT::v1i64 &&
7080       Op.getOperand(0).getValueType() == MVT::i64)
7081     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7082
7083   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7084   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7085   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7086                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7087 }
7088
7089 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7090 // a simple subregister reference or explicit instructions to grab
7091 // upper bits of a vector.
7092 SDValue
7093 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7094   if (Subtarget->hasAVX()) {
7095     DebugLoc dl = Op.getNode()->getDebugLoc();
7096     SDValue Vec = Op.getNode()->getOperand(0);
7097     SDValue Idx = Op.getNode()->getOperand(1);
7098
7099     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7100         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7101         isa<ConstantSDNode>(Idx)) {
7102       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7103       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7104     }
7105   }
7106   return SDValue();
7107 }
7108
7109 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7110 // simple superregister reference or explicit instructions to insert
7111 // the upper bits of a vector.
7112 SDValue
7113 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7114   if (Subtarget->hasAVX()) {
7115     DebugLoc dl = Op.getNode()->getDebugLoc();
7116     SDValue Vec = Op.getNode()->getOperand(0);
7117     SDValue SubVec = Op.getNode()->getOperand(1);
7118     SDValue Idx = Op.getNode()->getOperand(2);
7119
7120     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7121         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7122         isa<ConstantSDNode>(Idx)) {
7123       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7124       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7125     }
7126   }
7127   return SDValue();
7128 }
7129
7130 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7131 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7132 // one of the above mentioned nodes. It has to be wrapped because otherwise
7133 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7134 // be used to form addressing mode. These wrapped nodes will be selected
7135 // into MOV32ri.
7136 SDValue
7137 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7138   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7139
7140   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7141   // global base reg.
7142   unsigned char OpFlag = 0;
7143   unsigned WrapperKind = X86ISD::Wrapper;
7144   CodeModel::Model M = getTargetMachine().getCodeModel();
7145
7146   if (Subtarget->isPICStyleRIPRel() &&
7147       (M == CodeModel::Small || M == CodeModel::Kernel))
7148     WrapperKind = X86ISD::WrapperRIP;
7149   else if (Subtarget->isPICStyleGOT())
7150     OpFlag = X86II::MO_GOTOFF;
7151   else if (Subtarget->isPICStyleStubPIC())
7152     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7153
7154   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7155                                              CP->getAlignment(),
7156                                              CP->getOffset(), OpFlag);
7157   DebugLoc DL = CP->getDebugLoc();
7158   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7159   // With PIC, the address is actually $g + Offset.
7160   if (OpFlag) {
7161     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7162                          DAG.getNode(X86ISD::GlobalBaseReg,
7163                                      DebugLoc(), getPointerTy()),
7164                          Result);
7165   }
7166
7167   return Result;
7168 }
7169
7170 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7171   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7172
7173   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7174   // global base reg.
7175   unsigned char OpFlag = 0;
7176   unsigned WrapperKind = X86ISD::Wrapper;
7177   CodeModel::Model M = getTargetMachine().getCodeModel();
7178
7179   if (Subtarget->isPICStyleRIPRel() &&
7180       (M == CodeModel::Small || M == CodeModel::Kernel))
7181     WrapperKind = X86ISD::WrapperRIP;
7182   else if (Subtarget->isPICStyleGOT())
7183     OpFlag = X86II::MO_GOTOFF;
7184   else if (Subtarget->isPICStyleStubPIC())
7185     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7186
7187   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7188                                           OpFlag);
7189   DebugLoc DL = JT->getDebugLoc();
7190   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7191
7192   // With PIC, the address is actually $g + Offset.
7193   if (OpFlag)
7194     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7195                          DAG.getNode(X86ISD::GlobalBaseReg,
7196                                      DebugLoc(), getPointerTy()),
7197                          Result);
7198
7199   return Result;
7200 }
7201
7202 SDValue
7203 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7204   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7205
7206   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7207   // global base reg.
7208   unsigned char OpFlag = 0;
7209   unsigned WrapperKind = X86ISD::Wrapper;
7210   CodeModel::Model M = getTargetMachine().getCodeModel();
7211
7212   if (Subtarget->isPICStyleRIPRel() &&
7213       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7214     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7215       OpFlag = X86II::MO_GOTPCREL;
7216     WrapperKind = X86ISD::WrapperRIP;
7217   } else if (Subtarget->isPICStyleGOT()) {
7218     OpFlag = X86II::MO_GOT;
7219   } else if (Subtarget->isPICStyleStubPIC()) {
7220     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7221   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7222     OpFlag = X86II::MO_DARWIN_NONLAZY;
7223   }
7224
7225   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7226
7227   DebugLoc DL = Op.getDebugLoc();
7228   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7229
7230
7231   // With PIC, the address is actually $g + Offset.
7232   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7233       !Subtarget->is64Bit()) {
7234     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7235                          DAG.getNode(X86ISD::GlobalBaseReg,
7236                                      DebugLoc(), getPointerTy()),
7237                          Result);
7238   }
7239
7240   // For symbols that require a load from a stub to get the address, emit the
7241   // load.
7242   if (isGlobalStubReference(OpFlag))
7243     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7244                          MachinePointerInfo::getGOT(), false, false, false, 0);
7245
7246   return Result;
7247 }
7248
7249 SDValue
7250 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7251   // Create the TargetBlockAddressAddress node.
7252   unsigned char OpFlags =
7253     Subtarget->ClassifyBlockAddressReference();
7254   CodeModel::Model M = getTargetMachine().getCodeModel();
7255   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7256   DebugLoc dl = Op.getDebugLoc();
7257   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7258                                        /*isTarget=*/true, OpFlags);
7259
7260   if (Subtarget->isPICStyleRIPRel() &&
7261       (M == CodeModel::Small || M == CodeModel::Kernel))
7262     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7263   else
7264     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7265
7266   // With PIC, the address is actually $g + Offset.
7267   if (isGlobalRelativeToPICBase(OpFlags)) {
7268     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7269                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7270                          Result);
7271   }
7272
7273   return Result;
7274 }
7275
7276 SDValue
7277 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7278                                       int64_t Offset,
7279                                       SelectionDAG &DAG) const {
7280   // Create the TargetGlobalAddress node, folding in the constant
7281   // offset if it is legal.
7282   unsigned char OpFlags =
7283     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7284   CodeModel::Model M = getTargetMachine().getCodeModel();
7285   SDValue Result;
7286   if (OpFlags == X86II::MO_NO_FLAG &&
7287       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7288     // A direct static reference to a global.
7289     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7290     Offset = 0;
7291   } else {
7292     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7293   }
7294
7295   if (Subtarget->isPICStyleRIPRel() &&
7296       (M == CodeModel::Small || M == CodeModel::Kernel))
7297     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7298   else
7299     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7300
7301   // With PIC, the address is actually $g + Offset.
7302   if (isGlobalRelativeToPICBase(OpFlags)) {
7303     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7304                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7305                          Result);
7306   }
7307
7308   // For globals that require a load from a stub to get the address, emit the
7309   // load.
7310   if (isGlobalStubReference(OpFlags))
7311     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7312                          MachinePointerInfo::getGOT(), false, false, false, 0);
7313
7314   // If there was a non-zero offset that we didn't fold, create an explicit
7315   // addition for it.
7316   if (Offset != 0)
7317     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7318                          DAG.getConstant(Offset, getPointerTy()));
7319
7320   return Result;
7321 }
7322
7323 SDValue
7324 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7325   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7326   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7327   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7328 }
7329
7330 static SDValue
7331 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7332            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7333            unsigned char OperandFlags, bool LocalDynamic = false) {
7334   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7335   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7336   DebugLoc dl = GA->getDebugLoc();
7337   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7338                                            GA->getValueType(0),
7339                                            GA->getOffset(),
7340                                            OperandFlags);
7341
7342   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7343                                            : X86ISD::TLSADDR;
7344
7345   if (InFlag) {
7346     SDValue Ops[] = { Chain,  TGA, *InFlag };
7347     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7348   } else {
7349     SDValue Ops[]  = { Chain, TGA };
7350     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7351   }
7352
7353   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7354   MFI->setAdjustsStack(true);
7355
7356   SDValue Flag = Chain.getValue(1);
7357   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7358 }
7359
7360 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7361 static SDValue
7362 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7363                                 const EVT PtrVT) {
7364   SDValue InFlag;
7365   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7366   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7367                                      DAG.getNode(X86ISD::GlobalBaseReg,
7368                                                  DebugLoc(), PtrVT), InFlag);
7369   InFlag = Chain.getValue(1);
7370
7371   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7372 }
7373
7374 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7375 static SDValue
7376 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7377                                 const EVT PtrVT) {
7378   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7379                     X86::RAX, X86II::MO_TLSGD);
7380 }
7381
7382 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7383                                            SelectionDAG &DAG,
7384                                            const EVT PtrVT,
7385                                            bool is64Bit) {
7386   DebugLoc dl = GA->getDebugLoc();
7387
7388   // Get the start address of the TLS block for this module.
7389   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7390       .getInfo<X86MachineFunctionInfo>();
7391   MFI->incNumLocalDynamicTLSAccesses();
7392
7393   SDValue Base;
7394   if (is64Bit) {
7395     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7396                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7397   } else {
7398     SDValue InFlag;
7399     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7400         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7401     InFlag = Chain.getValue(1);
7402     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7403                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7404   }
7405
7406   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7407   // of Base.
7408
7409   // Build x@dtpoff.
7410   unsigned char OperandFlags = X86II::MO_DTPOFF;
7411   unsigned WrapperKind = X86ISD::Wrapper;
7412   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7413                                            GA->getValueType(0),
7414                                            GA->getOffset(), OperandFlags);
7415   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7416
7417   // Add x@dtpoff with the base.
7418   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7419 }
7420
7421 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7422 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7423                                    const EVT PtrVT, TLSModel::Model model,
7424                                    bool is64Bit, bool isPIC) {
7425   DebugLoc dl = GA->getDebugLoc();
7426
7427   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7428   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7429                                                          is64Bit ? 257 : 256));
7430
7431   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7432                                       DAG.getIntPtrConstant(0),
7433                                       MachinePointerInfo(Ptr),
7434                                       false, false, false, 0);
7435
7436   unsigned char OperandFlags = 0;
7437   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7438   // initialexec.
7439   unsigned WrapperKind = X86ISD::Wrapper;
7440   if (model == TLSModel::LocalExec) {
7441     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7442   } else if (model == TLSModel::InitialExec) {
7443     if (is64Bit) {
7444       OperandFlags = X86II::MO_GOTTPOFF;
7445       WrapperKind = X86ISD::WrapperRIP;
7446     } else {
7447       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7448     }
7449   } else {
7450     llvm_unreachable("Unexpected model");
7451   }
7452
7453   // emit "addl x@ntpoff,%eax" (local exec)
7454   // or "addl x@indntpoff,%eax" (initial exec)
7455   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7456   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7457                                            GA->getValueType(0),
7458                                            GA->getOffset(), OperandFlags);
7459   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7460
7461   if (model == TLSModel::InitialExec) {
7462     if (isPIC && !is64Bit) {
7463       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7464                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7465                            Offset);
7466     }
7467
7468     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7469                          MachinePointerInfo::getGOT(), false, false, false,
7470                          0);
7471   }
7472
7473   // The address of the thread local variable is the add of the thread
7474   // pointer with the offset of the variable.
7475   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7476 }
7477
7478 SDValue
7479 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7480
7481   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7482   const GlobalValue *GV = GA->getGlobal();
7483
7484   if (Subtarget->isTargetELF()) {
7485     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7486
7487     switch (model) {
7488       case TLSModel::GeneralDynamic:
7489         if (Subtarget->is64Bit())
7490           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7491         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7492       case TLSModel::LocalDynamic:
7493         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7494                                            Subtarget->is64Bit());
7495       case TLSModel::InitialExec:
7496       case TLSModel::LocalExec:
7497         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7498                                    Subtarget->is64Bit(),
7499                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7500     }
7501     llvm_unreachable("Unknown TLS model.");
7502   }
7503
7504   if (Subtarget->isTargetDarwin()) {
7505     // Darwin only has one model of TLS.  Lower to that.
7506     unsigned char OpFlag = 0;
7507     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7508                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7509
7510     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7511     // global base reg.
7512     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7513                   !Subtarget->is64Bit();
7514     if (PIC32)
7515       OpFlag = X86II::MO_TLVP_PIC_BASE;
7516     else
7517       OpFlag = X86II::MO_TLVP;
7518     DebugLoc DL = Op.getDebugLoc();
7519     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7520                                                 GA->getValueType(0),
7521                                                 GA->getOffset(), OpFlag);
7522     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7523
7524     // With PIC32, the address is actually $g + Offset.
7525     if (PIC32)
7526       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7527                            DAG.getNode(X86ISD::GlobalBaseReg,
7528                                        DebugLoc(), getPointerTy()),
7529                            Offset);
7530
7531     // Lowering the machine isd will make sure everything is in the right
7532     // location.
7533     SDValue Chain = DAG.getEntryNode();
7534     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7535     SDValue Args[] = { Chain, Offset };
7536     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7537
7538     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7539     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7540     MFI->setAdjustsStack(true);
7541
7542     // And our return value (tls address) is in the standard call return value
7543     // location.
7544     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7545     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7546                               Chain.getValue(1));
7547   }
7548
7549   if (Subtarget->isTargetWindows()) {
7550     // Just use the implicit TLS architecture
7551     // Need to generate someting similar to:
7552     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7553     //                                  ; from TEB
7554     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7555     //   mov     rcx, qword [rdx+rcx*8]
7556     //   mov     eax, .tls$:tlsvar
7557     //   [rax+rcx] contains the address
7558     // Windows 64bit: gs:0x58
7559     // Windows 32bit: fs:__tls_array
7560
7561     // If GV is an alias then use the aliasee for determining
7562     // thread-localness.
7563     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7564       GV = GA->resolveAliasedGlobal(false);
7565     DebugLoc dl = GA->getDebugLoc();
7566     SDValue Chain = DAG.getEntryNode();
7567
7568     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7569     // %gs:0x58 (64-bit).
7570     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7571                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7572                                                              256)
7573                                         : Type::getInt32PtrTy(*DAG.getContext(),
7574                                                               257));
7575
7576     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7577                                         Subtarget->is64Bit()
7578                                         ? DAG.getIntPtrConstant(0x58)
7579                                         : DAG.getExternalSymbol("_tls_array",
7580                                                                 getPointerTy()),
7581                                         MachinePointerInfo(Ptr),
7582                                         false, false, false, 0);
7583
7584     // Load the _tls_index variable
7585     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7586     if (Subtarget->is64Bit())
7587       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7588                            IDX, MachinePointerInfo(), MVT::i32,
7589                            false, false, 0);
7590     else
7591       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7592                         false, false, false, 0);
7593
7594     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7595                                     getPointerTy());
7596     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7597
7598     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7599     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7600                       false, false, false, 0);
7601
7602     // Get the offset of start of .tls section
7603     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7604                                              GA->getValueType(0),
7605                                              GA->getOffset(), X86II::MO_SECREL);
7606     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7607
7608     // The address of the thread local variable is the add of the thread
7609     // pointer with the offset of the variable.
7610     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7611   }
7612
7613   llvm_unreachable("TLS not implemented for this target.");
7614 }
7615
7616
7617 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7618 /// and take a 2 x i32 value to shift plus a shift amount.
7619 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7620   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7621   EVT VT = Op.getValueType();
7622   unsigned VTBits = VT.getSizeInBits();
7623   DebugLoc dl = Op.getDebugLoc();
7624   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7625   SDValue ShOpLo = Op.getOperand(0);
7626   SDValue ShOpHi = Op.getOperand(1);
7627   SDValue ShAmt  = Op.getOperand(2);
7628   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7629                                      DAG.getConstant(VTBits - 1, MVT::i8))
7630                        : DAG.getConstant(0, VT);
7631
7632   SDValue Tmp2, Tmp3;
7633   if (Op.getOpcode() == ISD::SHL_PARTS) {
7634     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7635     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7636   } else {
7637     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7638     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7639   }
7640
7641   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7642                                 DAG.getConstant(VTBits, MVT::i8));
7643   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7644                              AndNode, DAG.getConstant(0, MVT::i8));
7645
7646   SDValue Hi, Lo;
7647   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7648   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7649   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7650
7651   if (Op.getOpcode() == ISD::SHL_PARTS) {
7652     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7653     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7654   } else {
7655     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7656     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7657   }
7658
7659   SDValue Ops[2] = { Lo, Hi };
7660   return DAG.getMergeValues(Ops, 2, dl);
7661 }
7662
7663 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7664                                            SelectionDAG &DAG) const {
7665   EVT SrcVT = Op.getOperand(0).getValueType();
7666
7667   if (SrcVT.isVector())
7668     return SDValue();
7669
7670   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7671          "Unknown SINT_TO_FP to lower!");
7672
7673   // These are really Legal; return the operand so the caller accepts it as
7674   // Legal.
7675   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7676     return Op;
7677   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7678       Subtarget->is64Bit()) {
7679     return Op;
7680   }
7681
7682   DebugLoc dl = Op.getDebugLoc();
7683   unsigned Size = SrcVT.getSizeInBits()/8;
7684   MachineFunction &MF = DAG.getMachineFunction();
7685   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7686   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7687   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7688                                StackSlot,
7689                                MachinePointerInfo::getFixedStack(SSFI),
7690                                false, false, 0);
7691   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7692 }
7693
7694 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7695                                      SDValue StackSlot,
7696                                      SelectionDAG &DAG) const {
7697   // Build the FILD
7698   DebugLoc DL = Op.getDebugLoc();
7699   SDVTList Tys;
7700   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7701   if (useSSE)
7702     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7703   else
7704     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7705
7706   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7707
7708   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7709   MachineMemOperand *MMO;
7710   if (FI) {
7711     int SSFI = FI->getIndex();
7712     MMO =
7713       DAG.getMachineFunction()
7714       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7715                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7716   } else {
7717     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7718     StackSlot = StackSlot.getOperand(1);
7719   }
7720   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7721   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7722                                            X86ISD::FILD, DL,
7723                                            Tys, Ops, array_lengthof(Ops),
7724                                            SrcVT, MMO);
7725
7726   if (useSSE) {
7727     Chain = Result.getValue(1);
7728     SDValue InFlag = Result.getValue(2);
7729
7730     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7731     // shouldn't be necessary except that RFP cannot be live across
7732     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7733     MachineFunction &MF = DAG.getMachineFunction();
7734     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7735     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7736     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7737     Tys = DAG.getVTList(MVT::Other);
7738     SDValue Ops[] = {
7739       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7740     };
7741     MachineMemOperand *MMO =
7742       DAG.getMachineFunction()
7743       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7744                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7745
7746     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7747                                     Ops, array_lengthof(Ops),
7748                                     Op.getValueType(), MMO);
7749     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7750                          MachinePointerInfo::getFixedStack(SSFI),
7751                          false, false, false, 0);
7752   }
7753
7754   return Result;
7755 }
7756
7757 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7758 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7759                                                SelectionDAG &DAG) const {
7760   // This algorithm is not obvious. Here it is what we're trying to output:
7761   /*
7762      movq       %rax,  %xmm0
7763      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7764      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7765      #ifdef __SSE3__
7766        haddpd   %xmm0, %xmm0
7767      #else
7768        pshufd   $0x4e, %xmm0, %xmm1
7769        addpd    %xmm1, %xmm0
7770      #endif
7771   */
7772
7773   DebugLoc dl = Op.getDebugLoc();
7774   LLVMContext *Context = DAG.getContext();
7775
7776   // Build some magic constants.
7777   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7778   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7779   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7780
7781   SmallVector<Constant*,2> CV1;
7782   CV1.push_back(
7783         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7784   CV1.push_back(
7785         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7786   Constant *C1 = ConstantVector::get(CV1);
7787   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7788
7789   // Load the 64-bit value into an XMM register.
7790   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7791                             Op.getOperand(0));
7792   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7793                               MachinePointerInfo::getConstantPool(),
7794                               false, false, false, 16);
7795   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7796                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7797                               CLod0);
7798
7799   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7800                               MachinePointerInfo::getConstantPool(),
7801                               false, false, false, 16);
7802   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7803   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7804   SDValue Result;
7805
7806   if (Subtarget->hasSSE3()) {
7807     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7808     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7809   } else {
7810     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7811     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7812                                            S2F, 0x4E, DAG);
7813     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7814                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7815                          Sub);
7816   }
7817
7818   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7819                      DAG.getIntPtrConstant(0));
7820 }
7821
7822 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7823 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7824                                                SelectionDAG &DAG) const {
7825   DebugLoc dl = Op.getDebugLoc();
7826   // FP constant to bias correct the final result.
7827   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7828                                    MVT::f64);
7829
7830   // Load the 32-bit value into an XMM register.
7831   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7832                              Op.getOperand(0));
7833
7834   // Zero out the upper parts of the register.
7835   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7836
7837   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7838                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7839                      DAG.getIntPtrConstant(0));
7840
7841   // Or the load with the bias.
7842   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7843                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7844                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7845                                                    MVT::v2f64, Load)),
7846                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7847                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7848                                                    MVT::v2f64, Bias)));
7849   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7850                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7851                    DAG.getIntPtrConstant(0));
7852
7853   // Subtract the bias.
7854   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7855
7856   // Handle final rounding.
7857   EVT DestVT = Op.getValueType();
7858
7859   if (DestVT.bitsLT(MVT::f64))
7860     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7861                        DAG.getIntPtrConstant(0));
7862   if (DestVT.bitsGT(MVT::f64))
7863     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7864
7865   // Handle final rounding.
7866   return Sub;
7867 }
7868
7869 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7870                                            SelectionDAG &DAG) const {
7871   SDValue N0 = Op.getOperand(0);
7872   DebugLoc dl = Op.getDebugLoc();
7873
7874   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7875   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7876   // the optimization here.
7877   if (DAG.SignBitIsZero(N0))
7878     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7879
7880   EVT SrcVT = N0.getValueType();
7881   EVT DstVT = Op.getValueType();
7882   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7883     return LowerUINT_TO_FP_i64(Op, DAG);
7884   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7885     return LowerUINT_TO_FP_i32(Op, DAG);
7886   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7887     return SDValue();
7888
7889   // Make a 64-bit buffer, and use it to build an FILD.
7890   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7891   if (SrcVT == MVT::i32) {
7892     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7893     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7894                                      getPointerTy(), StackSlot, WordOff);
7895     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7896                                   StackSlot, MachinePointerInfo(),
7897                                   false, false, 0);
7898     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7899                                   OffsetSlot, MachinePointerInfo(),
7900                                   false, false, 0);
7901     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7902     return Fild;
7903   }
7904
7905   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7906   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7907                                StackSlot, MachinePointerInfo(),
7908                                false, false, 0);
7909   // For i64 source, we need to add the appropriate power of 2 if the input
7910   // was negative.  This is the same as the optimization in
7911   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7912   // we must be careful to do the computation in x87 extended precision, not
7913   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7914   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7915   MachineMemOperand *MMO =
7916     DAG.getMachineFunction()
7917     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7918                           MachineMemOperand::MOLoad, 8, 8);
7919
7920   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7921   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7922   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7923                                          MVT::i64, MMO);
7924
7925   APInt FF(32, 0x5F800000ULL);
7926
7927   // Check whether the sign bit is set.
7928   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7929                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7930                                  ISD::SETLT);
7931
7932   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7933   SDValue FudgePtr = DAG.getConstantPool(
7934                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7935                                          getPointerTy());
7936
7937   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7938   SDValue Zero = DAG.getIntPtrConstant(0);
7939   SDValue Four = DAG.getIntPtrConstant(4);
7940   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7941                                Zero, Four);
7942   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7943
7944   // Load the value out, extending it from f32 to f80.
7945   // FIXME: Avoid the extend by constructing the right constant pool?
7946   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7947                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7948                                  MVT::f32, false, false, 4);
7949   // Extend everything to 80 bits to force it to be done on x87.
7950   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7951   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7952 }
7953
7954 std::pair<SDValue,SDValue> X86TargetLowering::
7955 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7956   DebugLoc DL = Op.getDebugLoc();
7957
7958   EVT DstTy = Op.getValueType();
7959
7960   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7961     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7962     DstTy = MVT::i64;
7963   }
7964
7965   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7966          DstTy.getSimpleVT() >= MVT::i16 &&
7967          "Unknown FP_TO_INT to lower!");
7968
7969   // These are really Legal.
7970   if (DstTy == MVT::i32 &&
7971       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7972     return std::make_pair(SDValue(), SDValue());
7973   if (Subtarget->is64Bit() &&
7974       DstTy == MVT::i64 &&
7975       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7976     return std::make_pair(SDValue(), SDValue());
7977
7978   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7979   // stack slot, or into the FTOL runtime function.
7980   MachineFunction &MF = DAG.getMachineFunction();
7981   unsigned MemSize = DstTy.getSizeInBits()/8;
7982   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7983   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7984
7985   unsigned Opc;
7986   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7987     Opc = X86ISD::WIN_FTOL;
7988   else
7989     switch (DstTy.getSimpleVT().SimpleTy) {
7990     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7991     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7992     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7993     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7994     }
7995
7996   SDValue Chain = DAG.getEntryNode();
7997   SDValue Value = Op.getOperand(0);
7998   EVT TheVT = Op.getOperand(0).getValueType();
7999   // FIXME This causes a redundant load/store if the SSE-class value is already
8000   // in memory, such as if it is on the callstack.
8001   if (isScalarFPTypeInSSEReg(TheVT)) {
8002     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8003     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8004                          MachinePointerInfo::getFixedStack(SSFI),
8005                          false, false, 0);
8006     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8007     SDValue Ops[] = {
8008       Chain, StackSlot, DAG.getValueType(TheVT)
8009     };
8010
8011     MachineMemOperand *MMO =
8012       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013                               MachineMemOperand::MOLoad, MemSize, MemSize);
8014     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8015                                     DstTy, MMO);
8016     Chain = Value.getValue(1);
8017     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8018     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8019   }
8020
8021   MachineMemOperand *MMO =
8022     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8023                             MachineMemOperand::MOStore, MemSize, MemSize);
8024
8025   if (Opc != X86ISD::WIN_FTOL) {
8026     // Build the FP_TO_INT*_IN_MEM
8027     SDValue Ops[] = { Chain, Value, StackSlot };
8028     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8029                                            Ops, 3, DstTy, MMO);
8030     return std::make_pair(FIST, StackSlot);
8031   } else {
8032     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8033       DAG.getVTList(MVT::Other, MVT::Glue),
8034       Chain, Value);
8035     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8036       MVT::i32, ftol.getValue(1));
8037     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8038       MVT::i32, eax.getValue(2));
8039     SDValue Ops[] = { eax, edx };
8040     SDValue pair = IsReplace
8041       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8042       : DAG.getMergeValues(Ops, 2, DL);
8043     return std::make_pair(pair, SDValue());
8044   }
8045 }
8046
8047 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8048                                            SelectionDAG &DAG) const {
8049   if (Op.getValueType().isVector())
8050     return SDValue();
8051
8052   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8053     /*IsSigned=*/ true, /*IsReplace=*/ false);
8054   SDValue FIST = Vals.first, StackSlot = Vals.second;
8055   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8056   if (FIST.getNode() == 0) return Op;
8057
8058   if (StackSlot.getNode())
8059     // Load the result.
8060     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8061                        FIST, StackSlot, MachinePointerInfo(),
8062                        false, false, false, 0);
8063
8064   // The node is the result.
8065   return FIST;
8066 }
8067
8068 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8069                                            SelectionDAG &DAG) const {
8070   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8071     /*IsSigned=*/ false, /*IsReplace=*/ false);
8072   SDValue FIST = Vals.first, StackSlot = Vals.second;
8073   assert(FIST.getNode() && "Unexpected failure");
8074
8075   if (StackSlot.getNode())
8076     // Load the result.
8077     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8078                        FIST, StackSlot, MachinePointerInfo(),
8079                        false, false, false, 0);
8080
8081   // The node is the result.
8082   return FIST;
8083 }
8084
8085 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8086                                      SelectionDAG &DAG) const {
8087   LLVMContext *Context = DAG.getContext();
8088   DebugLoc dl = Op.getDebugLoc();
8089   EVT VT = Op.getValueType();
8090   EVT EltVT = VT;
8091   if (VT.isVector())
8092     EltVT = VT.getVectorElementType();
8093   Constant *C;
8094   if (EltVT == MVT::f64) {
8095     C = ConstantVector::getSplat(2,
8096                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8097   } else {
8098     C = ConstantVector::getSplat(4,
8099                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8100   }
8101   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8102   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8103                              MachinePointerInfo::getConstantPool(),
8104                              false, false, false, 16);
8105   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8106 }
8107
8108 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8109   LLVMContext *Context = DAG.getContext();
8110   DebugLoc dl = Op.getDebugLoc();
8111   EVT VT = Op.getValueType();
8112   EVT EltVT = VT;
8113   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8114   if (VT.isVector()) {
8115     EltVT = VT.getVectorElementType();
8116     NumElts = VT.getVectorNumElements();
8117   }
8118   Constant *C;
8119   if (EltVT == MVT::f64)
8120     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8121   else
8122     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8123   C = ConstantVector::getSplat(NumElts, C);
8124   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8125   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8126                              MachinePointerInfo::getConstantPool(),
8127                              false, false, false, 16);
8128   if (VT.isVector()) {
8129     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8130     return DAG.getNode(ISD::BITCAST, dl, VT,
8131                        DAG.getNode(ISD::XOR, dl, XORVT,
8132                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8133                                                Op.getOperand(0)),
8134                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8135   }
8136
8137   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8138 }
8139
8140 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8141   LLVMContext *Context = DAG.getContext();
8142   SDValue Op0 = Op.getOperand(0);
8143   SDValue Op1 = Op.getOperand(1);
8144   DebugLoc dl = Op.getDebugLoc();
8145   EVT VT = Op.getValueType();
8146   EVT SrcVT = Op1.getValueType();
8147
8148   // If second operand is smaller, extend it first.
8149   if (SrcVT.bitsLT(VT)) {
8150     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8151     SrcVT = VT;
8152   }
8153   // And if it is bigger, shrink it first.
8154   if (SrcVT.bitsGT(VT)) {
8155     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8156     SrcVT = VT;
8157   }
8158
8159   // At this point the operands and the result should have the same
8160   // type, and that won't be f80 since that is not custom lowered.
8161
8162   // First get the sign bit of second operand.
8163   SmallVector<Constant*,4> CV;
8164   if (SrcVT == MVT::f64) {
8165     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8166     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8167   } else {
8168     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8169     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8170     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8171     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8172   }
8173   Constant *C = ConstantVector::get(CV);
8174   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8175   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8176                               MachinePointerInfo::getConstantPool(),
8177                               false, false, false, 16);
8178   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8179
8180   // Shift sign bit right or left if the two operands have different types.
8181   if (SrcVT.bitsGT(VT)) {
8182     // Op0 is MVT::f32, Op1 is MVT::f64.
8183     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8184     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8185                           DAG.getConstant(32, MVT::i32));
8186     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8187     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8188                           DAG.getIntPtrConstant(0));
8189   }
8190
8191   // Clear first operand sign bit.
8192   CV.clear();
8193   if (VT == MVT::f64) {
8194     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8195     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8196   } else {
8197     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8198     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8199     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8200     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8201   }
8202   C = ConstantVector::get(CV);
8203   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8204   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8205                               MachinePointerInfo::getConstantPool(),
8206                               false, false, false, 16);
8207   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8208
8209   // Or the value with the sign bit.
8210   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8211 }
8212
8213 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8214   SDValue N0 = Op.getOperand(0);
8215   DebugLoc dl = Op.getDebugLoc();
8216   EVT VT = Op.getValueType();
8217
8218   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8219   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8220                                   DAG.getConstant(1, VT));
8221   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8222 }
8223
8224 /// Emit nodes that will be selected as "test Op0,Op0", or something
8225 /// equivalent.
8226 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8227                                     SelectionDAG &DAG) const {
8228   DebugLoc dl = Op.getDebugLoc();
8229
8230   // CF and OF aren't always set the way we want. Determine which
8231   // of these we need.
8232   bool NeedCF = false;
8233   bool NeedOF = false;
8234   switch (X86CC) {
8235   default: break;
8236   case X86::COND_A: case X86::COND_AE:
8237   case X86::COND_B: case X86::COND_BE:
8238     NeedCF = true;
8239     break;
8240   case X86::COND_G: case X86::COND_GE:
8241   case X86::COND_L: case X86::COND_LE:
8242   case X86::COND_O: case X86::COND_NO:
8243     NeedOF = true;
8244     break;
8245   }
8246
8247   // See if we can use the EFLAGS value from the operand instead of
8248   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8249   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8250   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8251     // Emit a CMP with 0, which is the TEST pattern.
8252     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8253                        DAG.getConstant(0, Op.getValueType()));
8254
8255   unsigned Opcode = 0;
8256   unsigned NumOperands = 0;
8257   switch (Op.getNode()->getOpcode()) {
8258   case ISD::ADD:
8259     // Due to an isel shortcoming, be conservative if this add is likely to be
8260     // selected as part of a load-modify-store instruction. When the root node
8261     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8262     // uses of other nodes in the match, such as the ADD in this case. This
8263     // leads to the ADD being left around and reselected, with the result being
8264     // two adds in the output.  Alas, even if none our users are stores, that
8265     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8266     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8267     // climbing the DAG back to the root, and it doesn't seem to be worth the
8268     // effort.
8269     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8270          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8271       if (UI->getOpcode() != ISD::CopyToReg &&
8272           UI->getOpcode() != ISD::SETCC &&
8273           UI->getOpcode() != ISD::STORE)
8274         goto default_case;
8275
8276     if (ConstantSDNode *C =
8277         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8278       // An add of one will be selected as an INC.
8279       if (C->getAPIntValue() == 1) {
8280         Opcode = X86ISD::INC;
8281         NumOperands = 1;
8282         break;
8283       }
8284
8285       // An add of negative one (subtract of one) will be selected as a DEC.
8286       if (C->getAPIntValue().isAllOnesValue()) {
8287         Opcode = X86ISD::DEC;
8288         NumOperands = 1;
8289         break;
8290       }
8291     }
8292
8293     // Otherwise use a regular EFLAGS-setting add.
8294     Opcode = X86ISD::ADD;
8295     NumOperands = 2;
8296     break;
8297   case ISD::AND: {
8298     // If the primary and result isn't used, don't bother using X86ISD::AND,
8299     // because a TEST instruction will be better.
8300     bool NonFlagUse = false;
8301     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8302            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8303       SDNode *User = *UI;
8304       unsigned UOpNo = UI.getOperandNo();
8305       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8306         // Look pass truncate.
8307         UOpNo = User->use_begin().getOperandNo();
8308         User = *User->use_begin();
8309       }
8310
8311       if (User->getOpcode() != ISD::BRCOND &&
8312           User->getOpcode() != ISD::SETCC &&
8313           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8314         NonFlagUse = true;
8315         break;
8316       }
8317     }
8318
8319     if (!NonFlagUse)
8320       break;
8321   }
8322     // FALL THROUGH
8323   case ISD::SUB:
8324   case ISD::OR:
8325   case ISD::XOR:
8326     // Due to the ISEL shortcoming noted above, be conservative if this op is
8327     // likely to be selected as part of a load-modify-store instruction.
8328     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8329            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8330       if (UI->getOpcode() == ISD::STORE)
8331         goto default_case;
8332
8333     // Otherwise use a regular EFLAGS-setting instruction.
8334     switch (Op.getNode()->getOpcode()) {
8335     default: llvm_unreachable("unexpected operator!");
8336     case ISD::SUB:
8337       Opcode = X86ISD::SUB;
8338       break;
8339     case ISD::OR:  Opcode = X86ISD::OR;  break;
8340     case ISD::XOR: Opcode = X86ISD::XOR; break;
8341     case ISD::AND: Opcode = X86ISD::AND; break;
8342     }
8343
8344     NumOperands = 2;
8345     break;
8346   case X86ISD::ADD:
8347   case X86ISD::SUB:
8348   case X86ISD::INC:
8349   case X86ISD::DEC:
8350   case X86ISD::OR:
8351   case X86ISD::XOR:
8352   case X86ISD::AND:
8353     return SDValue(Op.getNode(), 1);
8354   default:
8355   default_case:
8356     break;
8357   }
8358
8359   if (Opcode == 0)
8360     // Emit a CMP with 0, which is the TEST pattern.
8361     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8362                        DAG.getConstant(0, Op.getValueType()));
8363
8364   if (Opcode == X86ISD::CMP) {
8365     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8366                               Op.getOperand(1));
8367     // We can't replace usage of SUB with CMP.
8368     // The SUB node will be removed later because there is no use of it.
8369     return SDValue(New.getNode(), 0);
8370   }
8371
8372   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8373   SmallVector<SDValue, 4> Ops;
8374   for (unsigned i = 0; i != NumOperands; ++i)
8375     Ops.push_back(Op.getOperand(i));
8376
8377   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8378   DAG.ReplaceAllUsesWith(Op, New);
8379   return SDValue(New.getNode(), 1);
8380 }
8381
8382 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8383 /// equivalent.
8384 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8385                                    SelectionDAG &DAG) const {
8386   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8387     if (C->getAPIntValue() == 0)
8388       return EmitTest(Op0, X86CC, DAG);
8389
8390   DebugLoc dl = Op0.getDebugLoc();
8391   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8392        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8393     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8394     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8395     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8396                               Op0, Op1);
8397     return SDValue(Sub.getNode(), 1);
8398   }
8399   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8400 }
8401
8402 /// Convert a comparison if required by the subtarget.
8403 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8404                                                  SelectionDAG &DAG) const {
8405   // If the subtarget does not support the FUCOMI instruction, floating-point
8406   // comparisons have to be converted.
8407   if (Subtarget->hasCMov() ||
8408       Cmp.getOpcode() != X86ISD::CMP ||
8409       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8410       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8411     return Cmp;
8412
8413   // The instruction selector will select an FUCOM instruction instead of
8414   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8415   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8416   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8417   DebugLoc dl = Cmp.getDebugLoc();
8418   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8419   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8420   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8421                             DAG.getConstant(8, MVT::i8));
8422   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8423   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8424 }
8425
8426 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8427 /// if it's possible.
8428 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8429                                      DebugLoc dl, SelectionDAG &DAG) const {
8430   SDValue Op0 = And.getOperand(0);
8431   SDValue Op1 = And.getOperand(1);
8432   if (Op0.getOpcode() == ISD::TRUNCATE)
8433     Op0 = Op0.getOperand(0);
8434   if (Op1.getOpcode() == ISD::TRUNCATE)
8435     Op1 = Op1.getOperand(0);
8436
8437   SDValue LHS, RHS;
8438   if (Op1.getOpcode() == ISD::SHL)
8439     std::swap(Op0, Op1);
8440   if (Op0.getOpcode() == ISD::SHL) {
8441     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8442       if (And00C->getZExtValue() == 1) {
8443         // If we looked past a truncate, check that it's only truncating away
8444         // known zeros.
8445         unsigned BitWidth = Op0.getValueSizeInBits();
8446         unsigned AndBitWidth = And.getValueSizeInBits();
8447         if (BitWidth > AndBitWidth) {
8448           APInt Zeros, Ones;
8449           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8450           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8451             return SDValue();
8452         }
8453         LHS = Op1;
8454         RHS = Op0.getOperand(1);
8455       }
8456   } else if (Op1.getOpcode() == ISD::Constant) {
8457     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8458     uint64_t AndRHSVal = AndRHS->getZExtValue();
8459     SDValue AndLHS = Op0;
8460
8461     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8462       LHS = AndLHS.getOperand(0);
8463       RHS = AndLHS.getOperand(1);
8464     }
8465
8466     // Use BT if the immediate can't be encoded in a TEST instruction.
8467     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8468       LHS = AndLHS;
8469       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8470     }
8471   }
8472
8473   if (LHS.getNode()) {
8474     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8475     // instruction.  Since the shift amount is in-range-or-undefined, we know
8476     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8477     // the encoding for the i16 version is larger than the i32 version.
8478     // Also promote i16 to i32 for performance / code size reason.
8479     if (LHS.getValueType() == MVT::i8 ||
8480         LHS.getValueType() == MVT::i16)
8481       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8482
8483     // If the operand types disagree, extend the shift amount to match.  Since
8484     // BT ignores high bits (like shifts) we can use anyextend.
8485     if (LHS.getValueType() != RHS.getValueType())
8486       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8487
8488     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8489     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8490     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8491                        DAG.getConstant(Cond, MVT::i8), BT);
8492   }
8493
8494   return SDValue();
8495 }
8496
8497 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8498
8499   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8500
8501   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8502   SDValue Op0 = Op.getOperand(0);
8503   SDValue Op1 = Op.getOperand(1);
8504   DebugLoc dl = Op.getDebugLoc();
8505   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8506
8507   // Optimize to BT if possible.
8508   // Lower (X & (1 << N)) == 0 to BT(X, N).
8509   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8510   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8511   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8512       Op1.getOpcode() == ISD::Constant &&
8513       cast<ConstantSDNode>(Op1)->isNullValue() &&
8514       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8515     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8516     if (NewSetCC.getNode())
8517       return NewSetCC;
8518   }
8519
8520   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8521   // these.
8522   if (Op1.getOpcode() == ISD::Constant &&
8523       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8524        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8525       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8526
8527     // If the input is a setcc, then reuse the input setcc or use a new one with
8528     // the inverted condition.
8529     if (Op0.getOpcode() == X86ISD::SETCC) {
8530       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8531       bool Invert = (CC == ISD::SETNE) ^
8532         cast<ConstantSDNode>(Op1)->isNullValue();
8533       if (!Invert) return Op0;
8534
8535       CCode = X86::GetOppositeBranchCondition(CCode);
8536       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8537                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8538     }
8539   }
8540
8541   bool isFP = Op1.getValueType().isFloatingPoint();
8542   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8543   if (X86CC == X86::COND_INVALID)
8544     return SDValue();
8545
8546   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8547   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8548   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8549                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8550 }
8551
8552 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8553 // ones, and then concatenate the result back.
8554 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8555   EVT VT = Op.getValueType();
8556
8557   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8558          "Unsupported value type for operation");
8559
8560   unsigned NumElems = VT.getVectorNumElements();
8561   DebugLoc dl = Op.getDebugLoc();
8562   SDValue CC = Op.getOperand(2);
8563
8564   // Extract the LHS vectors
8565   SDValue LHS = Op.getOperand(0);
8566   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8567   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8568
8569   // Extract the RHS vectors
8570   SDValue RHS = Op.getOperand(1);
8571   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8572   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8573
8574   // Issue the operation on the smaller types and concatenate the result back
8575   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8576   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8577   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8578                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8579                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8580 }
8581
8582
8583 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8584   SDValue Cond;
8585   SDValue Op0 = Op.getOperand(0);
8586   SDValue Op1 = Op.getOperand(1);
8587   SDValue CC = Op.getOperand(2);
8588   EVT VT = Op.getValueType();
8589   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8590   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8591   DebugLoc dl = Op.getDebugLoc();
8592
8593   if (isFP) {
8594     unsigned SSECC = 8;
8595     EVT EltVT = Op0.getValueType().getVectorElementType();
8596     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8597
8598     bool Swap = false;
8599
8600     // SSE Condition code mapping:
8601     //  0 - EQ
8602     //  1 - LT
8603     //  2 - LE
8604     //  3 - UNORD
8605     //  4 - NEQ
8606     //  5 - NLT
8607     //  6 - NLE
8608     //  7 - ORD
8609     switch (SetCCOpcode) {
8610     default: break;
8611     case ISD::SETOEQ:
8612     case ISD::SETEQ:  SSECC = 0; break;
8613     case ISD::SETOGT:
8614     case ISD::SETGT: Swap = true; // Fallthrough
8615     case ISD::SETLT:
8616     case ISD::SETOLT: SSECC = 1; break;
8617     case ISD::SETOGE:
8618     case ISD::SETGE: Swap = true; // Fallthrough
8619     case ISD::SETLE:
8620     case ISD::SETOLE: SSECC = 2; break;
8621     case ISD::SETUO:  SSECC = 3; break;
8622     case ISD::SETUNE:
8623     case ISD::SETNE:  SSECC = 4; break;
8624     case ISD::SETULE: Swap = true;
8625     case ISD::SETUGE: SSECC = 5; break;
8626     case ISD::SETULT: Swap = true;
8627     case ISD::SETUGT: SSECC = 6; break;
8628     case ISD::SETO:   SSECC = 7; break;
8629     }
8630     if (Swap)
8631       std::swap(Op0, Op1);
8632
8633     // In the two special cases we can't handle, emit two comparisons.
8634     if (SSECC == 8) {
8635       if (SetCCOpcode == ISD::SETUEQ) {
8636         SDValue UNORD, EQ;
8637         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8638                             DAG.getConstant(3, MVT::i8));
8639         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8640                          DAG.getConstant(0, MVT::i8));
8641         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8642       }
8643       if (SetCCOpcode == ISD::SETONE) {
8644         SDValue ORD, NEQ;
8645         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8646                           DAG.getConstant(7, MVT::i8));
8647         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8648                           DAG.getConstant(4, MVT::i8));
8649         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8650       }
8651       llvm_unreachable("Illegal FP comparison");
8652     }
8653     // Handle all other FP comparisons here.
8654     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8655                        DAG.getConstant(SSECC, MVT::i8));
8656   }
8657
8658   // Break 256-bit integer vector compare into smaller ones.
8659   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8660     return Lower256IntVSETCC(Op, DAG);
8661
8662   // We are handling one of the integer comparisons here.  Since SSE only has
8663   // GT and EQ comparisons for integer, swapping operands and multiple
8664   // operations may be required for some comparisons.
8665   unsigned Opc = 0;
8666   bool Swap = false, Invert = false, FlipSigns = false;
8667
8668   switch (SetCCOpcode) {
8669   default: break;
8670   case ISD::SETNE:  Invert = true;
8671   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8672   case ISD::SETLT:  Swap = true;
8673   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8674   case ISD::SETGE:  Swap = true;
8675   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8676   case ISD::SETULT: Swap = true;
8677   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8678   case ISD::SETUGE: Swap = true;
8679   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8680   }
8681   if (Swap)
8682     std::swap(Op0, Op1);
8683
8684   // Check that the operation in question is available (most are plain SSE2,
8685   // but PCMPGTQ and PCMPEQQ have different requirements).
8686   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8687     return SDValue();
8688   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8689     return SDValue();
8690
8691   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8692   // bits of the inputs before performing those operations.
8693   if (FlipSigns) {
8694     EVT EltVT = VT.getVectorElementType();
8695     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8696                                       EltVT);
8697     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8698     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8699                                     SignBits.size());
8700     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8701     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8702   }
8703
8704   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8705
8706   // If the logical-not of the result is required, perform that now.
8707   if (Invert)
8708     Result = DAG.getNOT(dl, Result, VT);
8709
8710   return Result;
8711 }
8712
8713 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8714 static bool isX86LogicalCmp(SDValue Op) {
8715   unsigned Opc = Op.getNode()->getOpcode();
8716   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8717       Opc == X86ISD::SAHF)
8718     return true;
8719   if (Op.getResNo() == 1 &&
8720       (Opc == X86ISD::ADD ||
8721        Opc == X86ISD::SUB ||
8722        Opc == X86ISD::ADC ||
8723        Opc == X86ISD::SBB ||
8724        Opc == X86ISD::SMUL ||
8725        Opc == X86ISD::UMUL ||
8726        Opc == X86ISD::INC ||
8727        Opc == X86ISD::DEC ||
8728        Opc == X86ISD::OR ||
8729        Opc == X86ISD::XOR ||
8730        Opc == X86ISD::AND))
8731     return true;
8732
8733   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8734     return true;
8735
8736   return false;
8737 }
8738
8739 static bool isZero(SDValue V) {
8740   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8741   return C && C->isNullValue();
8742 }
8743
8744 static bool isAllOnes(SDValue V) {
8745   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8746   return C && C->isAllOnesValue();
8747 }
8748
8749 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8750   if (V.getOpcode() != ISD::TRUNCATE)
8751     return false;
8752
8753   SDValue VOp0 = V.getOperand(0);
8754   unsigned InBits = VOp0.getValueSizeInBits();
8755   unsigned Bits = V.getValueSizeInBits();
8756   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8757 }
8758
8759 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8760   bool addTest = true;
8761   SDValue Cond  = Op.getOperand(0);
8762   SDValue Op1 = Op.getOperand(1);
8763   SDValue Op2 = Op.getOperand(2);
8764   DebugLoc DL = Op.getDebugLoc();
8765   SDValue CC;
8766
8767   if (Cond.getOpcode() == ISD::SETCC) {
8768     SDValue NewCond = LowerSETCC(Cond, DAG);
8769     if (NewCond.getNode())
8770       Cond = NewCond;
8771   }
8772
8773   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8774   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8775   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8776   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8777   if (Cond.getOpcode() == X86ISD::SETCC &&
8778       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8779       isZero(Cond.getOperand(1).getOperand(1))) {
8780     SDValue Cmp = Cond.getOperand(1);
8781
8782     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8783
8784     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8785         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8786       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8787
8788       SDValue CmpOp0 = Cmp.getOperand(0);
8789       // Apply further optimizations for special cases
8790       // (select (x != 0), -1, 0) -> neg & sbb
8791       // (select (x == 0), 0, -1) -> neg & sbb
8792       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8793         if (YC->isNullValue() &&
8794             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8795           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8796           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8797                                     DAG.getConstant(0, CmpOp0.getValueType()),
8798                                     CmpOp0);
8799           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8800                                     DAG.getConstant(X86::COND_B, MVT::i8),
8801                                     SDValue(Neg.getNode(), 1));
8802           return Res;
8803         }
8804
8805       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8806                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8807       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8808
8809       SDValue Res =   // Res = 0 or -1.
8810         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8811                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8812
8813       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8814         Res = DAG.getNOT(DL, Res, Res.getValueType());
8815
8816       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8817       if (N2C == 0 || !N2C->isNullValue())
8818         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8819       return Res;
8820     }
8821   }
8822
8823   // Look past (and (setcc_carry (cmp ...)), 1).
8824   if (Cond.getOpcode() == ISD::AND &&
8825       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8826     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8827     if (C && C->getAPIntValue() == 1)
8828       Cond = Cond.getOperand(0);
8829   }
8830
8831   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8832   // setting operand in place of the X86ISD::SETCC.
8833   unsigned CondOpcode = Cond.getOpcode();
8834   if (CondOpcode == X86ISD::SETCC ||
8835       CondOpcode == X86ISD::SETCC_CARRY) {
8836     CC = Cond.getOperand(0);
8837
8838     SDValue Cmp = Cond.getOperand(1);
8839     unsigned Opc = Cmp.getOpcode();
8840     EVT VT = Op.getValueType();
8841
8842     bool IllegalFPCMov = false;
8843     if (VT.isFloatingPoint() && !VT.isVector() &&
8844         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8845       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8846
8847     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8848         Opc == X86ISD::BT) { // FIXME
8849       Cond = Cmp;
8850       addTest = false;
8851     }
8852   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8853              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8854              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8855               Cond.getOperand(0).getValueType() != MVT::i8)) {
8856     SDValue LHS = Cond.getOperand(0);
8857     SDValue RHS = Cond.getOperand(1);
8858     unsigned X86Opcode;
8859     unsigned X86Cond;
8860     SDVTList VTs;
8861     switch (CondOpcode) {
8862     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8863     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8864     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8865     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8866     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8867     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8868     default: llvm_unreachable("unexpected overflowing operator");
8869     }
8870     if (CondOpcode == ISD::UMULO)
8871       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8872                           MVT::i32);
8873     else
8874       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8875
8876     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8877
8878     if (CondOpcode == ISD::UMULO)
8879       Cond = X86Op.getValue(2);
8880     else
8881       Cond = X86Op.getValue(1);
8882
8883     CC = DAG.getConstant(X86Cond, MVT::i8);
8884     addTest = false;
8885   }
8886
8887   if (addTest) {
8888     // Look pass the truncate if the high bits are known zero.
8889     if (isTruncWithZeroHighBitsInput(Cond, DAG))
8890         Cond = Cond.getOperand(0);
8891
8892     // We know the result of AND is compared against zero. Try to match
8893     // it to BT.
8894     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8895       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8896       if (NewSetCC.getNode()) {
8897         CC = NewSetCC.getOperand(0);
8898         Cond = NewSetCC.getOperand(1);
8899         addTest = false;
8900       }
8901     }
8902   }
8903
8904   if (addTest) {
8905     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8906     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8907   }
8908
8909   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8910   // a <  b ?  0 : -1 -> RES = setcc_carry
8911   // a >= b ? -1 :  0 -> RES = setcc_carry
8912   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8913   if (Cond.getOpcode() == X86ISD::SUB) {
8914     Cond = ConvertCmpIfNecessary(Cond, DAG);
8915     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8916
8917     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8918         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8919       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8920                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8921       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8922         return DAG.getNOT(DL, Res, Res.getValueType());
8923       return Res;
8924     }
8925   }
8926
8927   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8928   // condition is true.
8929   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8930   SDValue Ops[] = { Op2, Op1, CC, Cond };
8931   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8932 }
8933
8934 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8935 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8936 // from the AND / OR.
8937 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8938   Opc = Op.getOpcode();
8939   if (Opc != ISD::OR && Opc != ISD::AND)
8940     return false;
8941   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8942           Op.getOperand(0).hasOneUse() &&
8943           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8944           Op.getOperand(1).hasOneUse());
8945 }
8946
8947 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8948 // 1 and that the SETCC node has a single use.
8949 static bool isXor1OfSetCC(SDValue Op) {
8950   if (Op.getOpcode() != ISD::XOR)
8951     return false;
8952   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8953   if (N1C && N1C->getAPIntValue() == 1) {
8954     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8955       Op.getOperand(0).hasOneUse();
8956   }
8957   return false;
8958 }
8959
8960 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8961   bool addTest = true;
8962   SDValue Chain = Op.getOperand(0);
8963   SDValue Cond  = Op.getOperand(1);
8964   SDValue Dest  = Op.getOperand(2);
8965   DebugLoc dl = Op.getDebugLoc();
8966   SDValue CC;
8967   bool Inverted = false;
8968
8969   if (Cond.getOpcode() == ISD::SETCC) {
8970     // Check for setcc([su]{add,sub,mul}o == 0).
8971     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8972         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8973         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8974         Cond.getOperand(0).getResNo() == 1 &&
8975         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8976          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8977          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8978          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8979          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8980          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8981       Inverted = true;
8982       Cond = Cond.getOperand(0);
8983     } else {
8984       SDValue NewCond = LowerSETCC(Cond, DAG);
8985       if (NewCond.getNode())
8986         Cond = NewCond;
8987     }
8988   }
8989 #if 0
8990   // FIXME: LowerXALUO doesn't handle these!!
8991   else if (Cond.getOpcode() == X86ISD::ADD  ||
8992            Cond.getOpcode() == X86ISD::SUB  ||
8993            Cond.getOpcode() == X86ISD::SMUL ||
8994            Cond.getOpcode() == X86ISD::UMUL)
8995     Cond = LowerXALUO(Cond, DAG);
8996 #endif
8997
8998   // Look pass (and (setcc_carry (cmp ...)), 1).
8999   if (Cond.getOpcode() == ISD::AND &&
9000       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9001     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9002     if (C && C->getAPIntValue() == 1)
9003       Cond = Cond.getOperand(0);
9004   }
9005
9006   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9007   // setting operand in place of the X86ISD::SETCC.
9008   unsigned CondOpcode = Cond.getOpcode();
9009   if (CondOpcode == X86ISD::SETCC ||
9010       CondOpcode == X86ISD::SETCC_CARRY) {
9011     CC = Cond.getOperand(0);
9012
9013     SDValue Cmp = Cond.getOperand(1);
9014     unsigned Opc = Cmp.getOpcode();
9015     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9016     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9017       Cond = Cmp;
9018       addTest = false;
9019     } else {
9020       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9021       default: break;
9022       case X86::COND_O:
9023       case X86::COND_B:
9024         // These can only come from an arithmetic instruction with overflow,
9025         // e.g. SADDO, UADDO.
9026         Cond = Cond.getNode()->getOperand(1);
9027         addTest = false;
9028         break;
9029       }
9030     }
9031   }
9032   CondOpcode = Cond.getOpcode();
9033   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9034       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9035       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9036        Cond.getOperand(0).getValueType() != MVT::i8)) {
9037     SDValue LHS = Cond.getOperand(0);
9038     SDValue RHS = Cond.getOperand(1);
9039     unsigned X86Opcode;
9040     unsigned X86Cond;
9041     SDVTList VTs;
9042     switch (CondOpcode) {
9043     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9044     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9045     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9046     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9047     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9048     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9049     default: llvm_unreachable("unexpected overflowing operator");
9050     }
9051     if (Inverted)
9052       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9053     if (CondOpcode == ISD::UMULO)
9054       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9055                           MVT::i32);
9056     else
9057       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9058
9059     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9060
9061     if (CondOpcode == ISD::UMULO)
9062       Cond = X86Op.getValue(2);
9063     else
9064       Cond = X86Op.getValue(1);
9065
9066     CC = DAG.getConstant(X86Cond, MVT::i8);
9067     addTest = false;
9068   } else {
9069     unsigned CondOpc;
9070     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9071       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9072       if (CondOpc == ISD::OR) {
9073         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9074         // two branches instead of an explicit OR instruction with a
9075         // separate test.
9076         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9077             isX86LogicalCmp(Cmp)) {
9078           CC = Cond.getOperand(0).getOperand(0);
9079           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9080                               Chain, Dest, CC, Cmp);
9081           CC = Cond.getOperand(1).getOperand(0);
9082           Cond = Cmp;
9083           addTest = false;
9084         }
9085       } else { // ISD::AND
9086         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9087         // two branches instead of an explicit AND instruction with a
9088         // separate test. However, we only do this if this block doesn't
9089         // have a fall-through edge, because this requires an explicit
9090         // jmp when the condition is false.
9091         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9092             isX86LogicalCmp(Cmp) &&
9093             Op.getNode()->hasOneUse()) {
9094           X86::CondCode CCode =
9095             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9096           CCode = X86::GetOppositeBranchCondition(CCode);
9097           CC = DAG.getConstant(CCode, MVT::i8);
9098           SDNode *User = *Op.getNode()->use_begin();
9099           // Look for an unconditional branch following this conditional branch.
9100           // We need this because we need to reverse the successors in order
9101           // to implement FCMP_OEQ.
9102           if (User->getOpcode() == ISD::BR) {
9103             SDValue FalseBB = User->getOperand(1);
9104             SDNode *NewBR =
9105               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9106             assert(NewBR == User);
9107             (void)NewBR;
9108             Dest = FalseBB;
9109
9110             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9111                                 Chain, Dest, CC, Cmp);
9112             X86::CondCode CCode =
9113               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9114             CCode = X86::GetOppositeBranchCondition(CCode);
9115             CC = DAG.getConstant(CCode, MVT::i8);
9116             Cond = Cmp;
9117             addTest = false;
9118           }
9119         }
9120       }
9121     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9122       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9123       // It should be transformed during dag combiner except when the condition
9124       // is set by a arithmetics with overflow node.
9125       X86::CondCode CCode =
9126         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9127       CCode = X86::GetOppositeBranchCondition(CCode);
9128       CC = DAG.getConstant(CCode, MVT::i8);
9129       Cond = Cond.getOperand(0).getOperand(1);
9130       addTest = false;
9131     } else if (Cond.getOpcode() == ISD::SETCC &&
9132                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9133       // For FCMP_OEQ, we can emit
9134       // two branches instead of an explicit AND instruction with a
9135       // separate test. However, we only do this if this block doesn't
9136       // have a fall-through edge, because this requires an explicit
9137       // jmp when the condition is false.
9138       if (Op.getNode()->hasOneUse()) {
9139         SDNode *User = *Op.getNode()->use_begin();
9140         // Look for an unconditional branch following this conditional branch.
9141         // We need this because we need to reverse the successors in order
9142         // to implement FCMP_OEQ.
9143         if (User->getOpcode() == ISD::BR) {
9144           SDValue FalseBB = User->getOperand(1);
9145           SDNode *NewBR =
9146             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9147           assert(NewBR == User);
9148           (void)NewBR;
9149           Dest = FalseBB;
9150
9151           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9152                                     Cond.getOperand(0), Cond.getOperand(1));
9153           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9154           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9155           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9156                               Chain, Dest, CC, Cmp);
9157           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9158           Cond = Cmp;
9159           addTest = false;
9160         }
9161       }
9162     } else if (Cond.getOpcode() == ISD::SETCC &&
9163                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9164       // For FCMP_UNE, we can emit
9165       // two branches instead of an explicit AND instruction with a
9166       // separate test. However, we only do this if this block doesn't
9167       // have a fall-through edge, because this requires an explicit
9168       // jmp when the condition is false.
9169       if (Op.getNode()->hasOneUse()) {
9170         SDNode *User = *Op.getNode()->use_begin();
9171         // Look for an unconditional branch following this conditional branch.
9172         // We need this because we need to reverse the successors in order
9173         // to implement FCMP_UNE.
9174         if (User->getOpcode() == ISD::BR) {
9175           SDValue FalseBB = User->getOperand(1);
9176           SDNode *NewBR =
9177             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9178           assert(NewBR == User);
9179           (void)NewBR;
9180
9181           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9182                                     Cond.getOperand(0), Cond.getOperand(1));
9183           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9184           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9185           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9186                               Chain, Dest, CC, Cmp);
9187           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9188           Cond = Cmp;
9189           addTest = false;
9190           Dest = FalseBB;
9191         }
9192       }
9193     }
9194   }
9195
9196   if (addTest) {
9197     // Look pass the truncate if the high bits are known zero.
9198     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9199         Cond = Cond.getOperand(0);
9200
9201     // We know the result of AND is compared against zero. Try to match
9202     // it to BT.
9203     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9204       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9205       if (NewSetCC.getNode()) {
9206         CC = NewSetCC.getOperand(0);
9207         Cond = NewSetCC.getOperand(1);
9208         addTest = false;
9209       }
9210     }
9211   }
9212
9213   if (addTest) {
9214     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9215     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9216   }
9217   Cond = ConvertCmpIfNecessary(Cond, DAG);
9218   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9219                      Chain, Dest, CC, Cond);
9220 }
9221
9222
9223 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9224 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9225 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9226 // that the guard pages used by the OS virtual memory manager are allocated in
9227 // correct sequence.
9228 SDValue
9229 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9230                                            SelectionDAG &DAG) const {
9231   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9232           getTargetMachine().Options.EnableSegmentedStacks) &&
9233          "This should be used only on Windows targets or when segmented stacks "
9234          "are being used");
9235   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9236   DebugLoc dl = Op.getDebugLoc();
9237
9238   // Get the inputs.
9239   SDValue Chain = Op.getOperand(0);
9240   SDValue Size  = Op.getOperand(1);
9241   // FIXME: Ensure alignment here
9242
9243   bool Is64Bit = Subtarget->is64Bit();
9244   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9245
9246   if (getTargetMachine().Options.EnableSegmentedStacks) {
9247     MachineFunction &MF = DAG.getMachineFunction();
9248     MachineRegisterInfo &MRI = MF.getRegInfo();
9249
9250     if (Is64Bit) {
9251       // The 64 bit implementation of segmented stacks needs to clobber both r10
9252       // r11. This makes it impossible to use it along with nested parameters.
9253       const Function *F = MF.getFunction();
9254
9255       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9256            I != E; ++I)
9257         if (I->hasNestAttr())
9258           report_fatal_error("Cannot use segmented stacks with functions that "
9259                              "have nested arguments.");
9260     }
9261
9262     const TargetRegisterClass *AddrRegClass =
9263       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9264     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9265     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9266     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9267                                 DAG.getRegister(Vreg, SPTy));
9268     SDValue Ops1[2] = { Value, Chain };
9269     return DAG.getMergeValues(Ops1, 2, dl);
9270   } else {
9271     SDValue Flag;
9272     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9273
9274     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9275     Flag = Chain.getValue(1);
9276     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9277
9278     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9279     Flag = Chain.getValue(1);
9280
9281     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9282
9283     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9284     return DAG.getMergeValues(Ops1, 2, dl);
9285   }
9286 }
9287
9288 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9289   MachineFunction &MF = DAG.getMachineFunction();
9290   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9291
9292   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9293   DebugLoc DL = Op.getDebugLoc();
9294
9295   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9296     // vastart just stores the address of the VarArgsFrameIndex slot into the
9297     // memory location argument.
9298     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9299                                    getPointerTy());
9300     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9301                         MachinePointerInfo(SV), false, false, 0);
9302   }
9303
9304   // __va_list_tag:
9305   //   gp_offset         (0 - 6 * 8)
9306   //   fp_offset         (48 - 48 + 8 * 16)
9307   //   overflow_arg_area (point to parameters coming in memory).
9308   //   reg_save_area
9309   SmallVector<SDValue, 8> MemOps;
9310   SDValue FIN = Op.getOperand(1);
9311   // Store gp_offset
9312   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9313                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9314                                                MVT::i32),
9315                                FIN, MachinePointerInfo(SV), false, false, 0);
9316   MemOps.push_back(Store);
9317
9318   // Store fp_offset
9319   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9320                     FIN, DAG.getIntPtrConstant(4));
9321   Store = DAG.getStore(Op.getOperand(0), DL,
9322                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9323                                        MVT::i32),
9324                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9325   MemOps.push_back(Store);
9326
9327   // Store ptr to overflow_arg_area
9328   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9329                     FIN, DAG.getIntPtrConstant(4));
9330   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9331                                     getPointerTy());
9332   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9333                        MachinePointerInfo(SV, 8),
9334                        false, false, 0);
9335   MemOps.push_back(Store);
9336
9337   // Store ptr to reg_save_area.
9338   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9339                     FIN, DAG.getIntPtrConstant(8));
9340   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9341                                     getPointerTy());
9342   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9343                        MachinePointerInfo(SV, 16), false, false, 0);
9344   MemOps.push_back(Store);
9345   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9346                      &MemOps[0], MemOps.size());
9347 }
9348
9349 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9350   assert(Subtarget->is64Bit() &&
9351          "LowerVAARG only handles 64-bit va_arg!");
9352   assert((Subtarget->isTargetLinux() ||
9353           Subtarget->isTargetDarwin()) &&
9354           "Unhandled target in LowerVAARG");
9355   assert(Op.getNode()->getNumOperands() == 4);
9356   SDValue Chain = Op.getOperand(0);
9357   SDValue SrcPtr = Op.getOperand(1);
9358   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9359   unsigned Align = Op.getConstantOperandVal(3);
9360   DebugLoc dl = Op.getDebugLoc();
9361
9362   EVT ArgVT = Op.getNode()->getValueType(0);
9363   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9364   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9365   uint8_t ArgMode;
9366
9367   // Decide which area this value should be read from.
9368   // TODO: Implement the AMD64 ABI in its entirety. This simple
9369   // selection mechanism works only for the basic types.
9370   if (ArgVT == MVT::f80) {
9371     llvm_unreachable("va_arg for f80 not yet implemented");
9372   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9373     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9374   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9375     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9376   } else {
9377     llvm_unreachable("Unhandled argument type in LowerVAARG");
9378   }
9379
9380   if (ArgMode == 2) {
9381     // Sanity Check: Make sure using fp_offset makes sense.
9382     assert(!getTargetMachine().Options.UseSoftFloat &&
9383            !(DAG.getMachineFunction()
9384                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9385            Subtarget->hasSSE1());
9386   }
9387
9388   // Insert VAARG_64 node into the DAG
9389   // VAARG_64 returns two values: Variable Argument Address, Chain
9390   SmallVector<SDValue, 11> InstOps;
9391   InstOps.push_back(Chain);
9392   InstOps.push_back(SrcPtr);
9393   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9394   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9395   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9396   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9397   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9398                                           VTs, &InstOps[0], InstOps.size(),
9399                                           MVT::i64,
9400                                           MachinePointerInfo(SV),
9401                                           /*Align=*/0,
9402                                           /*Volatile=*/false,
9403                                           /*ReadMem=*/true,
9404                                           /*WriteMem=*/true);
9405   Chain = VAARG.getValue(1);
9406
9407   // Load the next argument and return it
9408   return DAG.getLoad(ArgVT, dl,
9409                      Chain,
9410                      VAARG,
9411                      MachinePointerInfo(),
9412                      false, false, false, 0);
9413 }
9414
9415 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9416   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9417   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9418   SDValue Chain = Op.getOperand(0);
9419   SDValue DstPtr = Op.getOperand(1);
9420   SDValue SrcPtr = Op.getOperand(2);
9421   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9422   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9423   DebugLoc DL = Op.getDebugLoc();
9424
9425   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9426                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9427                        false,
9428                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9429 }
9430
9431 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9432 // may or may not be a constant. Takes immediate version of shift as input.
9433 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9434                                    SDValue SrcOp, SDValue ShAmt,
9435                                    SelectionDAG &DAG) {
9436   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9437
9438   if (isa<ConstantSDNode>(ShAmt)) {
9439     // Constant may be a TargetConstant. Use a regular constant.
9440     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9441     switch (Opc) {
9442       default: llvm_unreachable("Unknown target vector shift node");
9443       case X86ISD::VSHLI:
9444       case X86ISD::VSRLI:
9445       case X86ISD::VSRAI:
9446         return DAG.getNode(Opc, dl, VT, SrcOp,
9447                            DAG.getConstant(ShiftAmt, MVT::i32));
9448     }
9449   }
9450
9451   // Change opcode to non-immediate version
9452   switch (Opc) {
9453     default: llvm_unreachable("Unknown target vector shift node");
9454     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9455     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9456     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9457   }
9458
9459   // Need to build a vector containing shift amount
9460   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9461   SDValue ShOps[4];
9462   ShOps[0] = ShAmt;
9463   ShOps[1] = DAG.getConstant(0, MVT::i32);
9464   ShOps[2] = DAG.getUNDEF(MVT::i32);
9465   ShOps[3] = DAG.getUNDEF(MVT::i32);
9466   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9467
9468   // The return type has to be a 128-bit type with the same element
9469   // type as the input type.
9470   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9471   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9472
9473   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9474   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9475 }
9476
9477 SDValue
9478 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9479   DebugLoc dl = Op.getDebugLoc();
9480   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9481   switch (IntNo) {
9482   default: return SDValue();    // Don't custom lower most intrinsics.
9483   // Comparison intrinsics.
9484   case Intrinsic::x86_sse_comieq_ss:
9485   case Intrinsic::x86_sse_comilt_ss:
9486   case Intrinsic::x86_sse_comile_ss:
9487   case Intrinsic::x86_sse_comigt_ss:
9488   case Intrinsic::x86_sse_comige_ss:
9489   case Intrinsic::x86_sse_comineq_ss:
9490   case Intrinsic::x86_sse_ucomieq_ss:
9491   case Intrinsic::x86_sse_ucomilt_ss:
9492   case Intrinsic::x86_sse_ucomile_ss:
9493   case Intrinsic::x86_sse_ucomigt_ss:
9494   case Intrinsic::x86_sse_ucomige_ss:
9495   case Intrinsic::x86_sse_ucomineq_ss:
9496   case Intrinsic::x86_sse2_comieq_sd:
9497   case Intrinsic::x86_sse2_comilt_sd:
9498   case Intrinsic::x86_sse2_comile_sd:
9499   case Intrinsic::x86_sse2_comigt_sd:
9500   case Intrinsic::x86_sse2_comige_sd:
9501   case Intrinsic::x86_sse2_comineq_sd:
9502   case Intrinsic::x86_sse2_ucomieq_sd:
9503   case Intrinsic::x86_sse2_ucomilt_sd:
9504   case Intrinsic::x86_sse2_ucomile_sd:
9505   case Intrinsic::x86_sse2_ucomigt_sd:
9506   case Intrinsic::x86_sse2_ucomige_sd:
9507   case Intrinsic::x86_sse2_ucomineq_sd: {
9508     unsigned Opc = 0;
9509     ISD::CondCode CC = ISD::SETCC_INVALID;
9510     switch (IntNo) {
9511     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9512     case Intrinsic::x86_sse_comieq_ss:
9513     case Intrinsic::x86_sse2_comieq_sd:
9514       Opc = X86ISD::COMI;
9515       CC = ISD::SETEQ;
9516       break;
9517     case Intrinsic::x86_sse_comilt_ss:
9518     case Intrinsic::x86_sse2_comilt_sd:
9519       Opc = X86ISD::COMI;
9520       CC = ISD::SETLT;
9521       break;
9522     case Intrinsic::x86_sse_comile_ss:
9523     case Intrinsic::x86_sse2_comile_sd:
9524       Opc = X86ISD::COMI;
9525       CC = ISD::SETLE;
9526       break;
9527     case Intrinsic::x86_sse_comigt_ss:
9528     case Intrinsic::x86_sse2_comigt_sd:
9529       Opc = X86ISD::COMI;
9530       CC = ISD::SETGT;
9531       break;
9532     case Intrinsic::x86_sse_comige_ss:
9533     case Intrinsic::x86_sse2_comige_sd:
9534       Opc = X86ISD::COMI;
9535       CC = ISD::SETGE;
9536       break;
9537     case Intrinsic::x86_sse_comineq_ss:
9538     case Intrinsic::x86_sse2_comineq_sd:
9539       Opc = X86ISD::COMI;
9540       CC = ISD::SETNE;
9541       break;
9542     case Intrinsic::x86_sse_ucomieq_ss:
9543     case Intrinsic::x86_sse2_ucomieq_sd:
9544       Opc = X86ISD::UCOMI;
9545       CC = ISD::SETEQ;
9546       break;
9547     case Intrinsic::x86_sse_ucomilt_ss:
9548     case Intrinsic::x86_sse2_ucomilt_sd:
9549       Opc = X86ISD::UCOMI;
9550       CC = ISD::SETLT;
9551       break;
9552     case Intrinsic::x86_sse_ucomile_ss:
9553     case Intrinsic::x86_sse2_ucomile_sd:
9554       Opc = X86ISD::UCOMI;
9555       CC = ISD::SETLE;
9556       break;
9557     case Intrinsic::x86_sse_ucomigt_ss:
9558     case Intrinsic::x86_sse2_ucomigt_sd:
9559       Opc = X86ISD::UCOMI;
9560       CC = ISD::SETGT;
9561       break;
9562     case Intrinsic::x86_sse_ucomige_ss:
9563     case Intrinsic::x86_sse2_ucomige_sd:
9564       Opc = X86ISD::UCOMI;
9565       CC = ISD::SETGE;
9566       break;
9567     case Intrinsic::x86_sse_ucomineq_ss:
9568     case Intrinsic::x86_sse2_ucomineq_sd:
9569       Opc = X86ISD::UCOMI;
9570       CC = ISD::SETNE;
9571       break;
9572     }
9573
9574     SDValue LHS = Op.getOperand(1);
9575     SDValue RHS = Op.getOperand(2);
9576     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9577     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9578     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9579     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9580                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9581     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9582   }
9583   // Arithmetic intrinsics.
9584   case Intrinsic::x86_sse2_pmulu_dq:
9585   case Intrinsic::x86_avx2_pmulu_dq:
9586     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9587                        Op.getOperand(1), Op.getOperand(2));
9588   case Intrinsic::x86_sse3_hadd_ps:
9589   case Intrinsic::x86_sse3_hadd_pd:
9590   case Intrinsic::x86_avx_hadd_ps_256:
9591   case Intrinsic::x86_avx_hadd_pd_256:
9592     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9593                        Op.getOperand(1), Op.getOperand(2));
9594   case Intrinsic::x86_sse3_hsub_ps:
9595   case Intrinsic::x86_sse3_hsub_pd:
9596   case Intrinsic::x86_avx_hsub_ps_256:
9597   case Intrinsic::x86_avx_hsub_pd_256:
9598     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9599                        Op.getOperand(1), Op.getOperand(2));
9600   case Intrinsic::x86_ssse3_phadd_w_128:
9601   case Intrinsic::x86_ssse3_phadd_d_128:
9602   case Intrinsic::x86_avx2_phadd_w:
9603   case Intrinsic::x86_avx2_phadd_d:
9604     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9605                        Op.getOperand(1), Op.getOperand(2));
9606   case Intrinsic::x86_ssse3_phsub_w_128:
9607   case Intrinsic::x86_ssse3_phsub_d_128:
9608   case Intrinsic::x86_avx2_phsub_w:
9609   case Intrinsic::x86_avx2_phsub_d:
9610     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9611                        Op.getOperand(1), Op.getOperand(2));
9612   case Intrinsic::x86_avx2_psllv_d:
9613   case Intrinsic::x86_avx2_psllv_q:
9614   case Intrinsic::x86_avx2_psllv_d_256:
9615   case Intrinsic::x86_avx2_psllv_q_256:
9616     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9617                       Op.getOperand(1), Op.getOperand(2));
9618   case Intrinsic::x86_avx2_psrlv_d:
9619   case Intrinsic::x86_avx2_psrlv_q:
9620   case Intrinsic::x86_avx2_psrlv_d_256:
9621   case Intrinsic::x86_avx2_psrlv_q_256:
9622     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9623                       Op.getOperand(1), Op.getOperand(2));
9624   case Intrinsic::x86_avx2_psrav_d:
9625   case Intrinsic::x86_avx2_psrav_d_256:
9626     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9627                       Op.getOperand(1), Op.getOperand(2));
9628   case Intrinsic::x86_ssse3_pshuf_b_128:
9629   case Intrinsic::x86_avx2_pshuf_b:
9630     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9631                        Op.getOperand(1), Op.getOperand(2));
9632   case Intrinsic::x86_ssse3_psign_b_128:
9633   case Intrinsic::x86_ssse3_psign_w_128:
9634   case Intrinsic::x86_ssse3_psign_d_128:
9635   case Intrinsic::x86_avx2_psign_b:
9636   case Intrinsic::x86_avx2_psign_w:
9637   case Intrinsic::x86_avx2_psign_d:
9638     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9639                        Op.getOperand(1), Op.getOperand(2));
9640   case Intrinsic::x86_sse41_insertps:
9641     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9642                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9643   case Intrinsic::x86_avx_vperm2f128_ps_256:
9644   case Intrinsic::x86_avx_vperm2f128_pd_256:
9645   case Intrinsic::x86_avx_vperm2f128_si_256:
9646   case Intrinsic::x86_avx2_vperm2i128:
9647     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9648                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9649   case Intrinsic::x86_avx2_permd:
9650   case Intrinsic::x86_avx2_permps:
9651     // Operands intentionally swapped. Mask is last operand to intrinsic,
9652     // but second operand for node/intruction.
9653     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9654                        Op.getOperand(2), Op.getOperand(1));
9655
9656   // ptest and testp intrinsics. The intrinsic these come from are designed to
9657   // return an integer value, not just an instruction so lower it to the ptest
9658   // or testp pattern and a setcc for the result.
9659   case Intrinsic::x86_sse41_ptestz:
9660   case Intrinsic::x86_sse41_ptestc:
9661   case Intrinsic::x86_sse41_ptestnzc:
9662   case Intrinsic::x86_avx_ptestz_256:
9663   case Intrinsic::x86_avx_ptestc_256:
9664   case Intrinsic::x86_avx_ptestnzc_256:
9665   case Intrinsic::x86_avx_vtestz_ps:
9666   case Intrinsic::x86_avx_vtestc_ps:
9667   case Intrinsic::x86_avx_vtestnzc_ps:
9668   case Intrinsic::x86_avx_vtestz_pd:
9669   case Intrinsic::x86_avx_vtestc_pd:
9670   case Intrinsic::x86_avx_vtestnzc_pd:
9671   case Intrinsic::x86_avx_vtestz_ps_256:
9672   case Intrinsic::x86_avx_vtestc_ps_256:
9673   case Intrinsic::x86_avx_vtestnzc_ps_256:
9674   case Intrinsic::x86_avx_vtestz_pd_256:
9675   case Intrinsic::x86_avx_vtestc_pd_256:
9676   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9677     bool IsTestPacked = false;
9678     unsigned X86CC = 0;
9679     switch (IntNo) {
9680     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9681     case Intrinsic::x86_avx_vtestz_ps:
9682     case Intrinsic::x86_avx_vtestz_pd:
9683     case Intrinsic::x86_avx_vtestz_ps_256:
9684     case Intrinsic::x86_avx_vtestz_pd_256:
9685       IsTestPacked = true; // Fallthrough
9686     case Intrinsic::x86_sse41_ptestz:
9687     case Intrinsic::x86_avx_ptestz_256:
9688       // ZF = 1
9689       X86CC = X86::COND_E;
9690       break;
9691     case Intrinsic::x86_avx_vtestc_ps:
9692     case Intrinsic::x86_avx_vtestc_pd:
9693     case Intrinsic::x86_avx_vtestc_ps_256:
9694     case Intrinsic::x86_avx_vtestc_pd_256:
9695       IsTestPacked = true; // Fallthrough
9696     case Intrinsic::x86_sse41_ptestc:
9697     case Intrinsic::x86_avx_ptestc_256:
9698       // CF = 1
9699       X86CC = X86::COND_B;
9700       break;
9701     case Intrinsic::x86_avx_vtestnzc_ps:
9702     case Intrinsic::x86_avx_vtestnzc_pd:
9703     case Intrinsic::x86_avx_vtestnzc_ps_256:
9704     case Intrinsic::x86_avx_vtestnzc_pd_256:
9705       IsTestPacked = true; // Fallthrough
9706     case Intrinsic::x86_sse41_ptestnzc:
9707     case Intrinsic::x86_avx_ptestnzc_256:
9708       // ZF and CF = 0
9709       X86CC = X86::COND_A;
9710       break;
9711     }
9712
9713     SDValue LHS = Op.getOperand(1);
9714     SDValue RHS = Op.getOperand(2);
9715     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9716     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9717     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9718     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9719     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9720   }
9721
9722   // SSE/AVX shift intrinsics
9723   case Intrinsic::x86_sse2_psll_w:
9724   case Intrinsic::x86_sse2_psll_d:
9725   case Intrinsic::x86_sse2_psll_q:
9726   case Intrinsic::x86_avx2_psll_w:
9727   case Intrinsic::x86_avx2_psll_d:
9728   case Intrinsic::x86_avx2_psll_q:
9729     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9730                        Op.getOperand(1), Op.getOperand(2));
9731   case Intrinsic::x86_sse2_psrl_w:
9732   case Intrinsic::x86_sse2_psrl_d:
9733   case Intrinsic::x86_sse2_psrl_q:
9734   case Intrinsic::x86_avx2_psrl_w:
9735   case Intrinsic::x86_avx2_psrl_d:
9736   case Intrinsic::x86_avx2_psrl_q:
9737     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9738                        Op.getOperand(1), Op.getOperand(2));
9739   case Intrinsic::x86_sse2_psra_w:
9740   case Intrinsic::x86_sse2_psra_d:
9741   case Intrinsic::x86_avx2_psra_w:
9742   case Intrinsic::x86_avx2_psra_d:
9743     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9744                        Op.getOperand(1), Op.getOperand(2));
9745   case Intrinsic::x86_sse2_pslli_w:
9746   case Intrinsic::x86_sse2_pslli_d:
9747   case Intrinsic::x86_sse2_pslli_q:
9748   case Intrinsic::x86_avx2_pslli_w:
9749   case Intrinsic::x86_avx2_pslli_d:
9750   case Intrinsic::x86_avx2_pslli_q:
9751     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9752                                Op.getOperand(1), Op.getOperand(2), DAG);
9753   case Intrinsic::x86_sse2_psrli_w:
9754   case Intrinsic::x86_sse2_psrli_d:
9755   case Intrinsic::x86_sse2_psrli_q:
9756   case Intrinsic::x86_avx2_psrli_w:
9757   case Intrinsic::x86_avx2_psrli_d:
9758   case Intrinsic::x86_avx2_psrli_q:
9759     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9760                                Op.getOperand(1), Op.getOperand(2), DAG);
9761   case Intrinsic::x86_sse2_psrai_w:
9762   case Intrinsic::x86_sse2_psrai_d:
9763   case Intrinsic::x86_avx2_psrai_w:
9764   case Intrinsic::x86_avx2_psrai_d:
9765     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9766                                Op.getOperand(1), Op.getOperand(2), DAG);
9767   // Fix vector shift instructions where the last operand is a non-immediate
9768   // i32 value.
9769   case Intrinsic::x86_mmx_pslli_w:
9770   case Intrinsic::x86_mmx_pslli_d:
9771   case Intrinsic::x86_mmx_pslli_q:
9772   case Intrinsic::x86_mmx_psrli_w:
9773   case Intrinsic::x86_mmx_psrli_d:
9774   case Intrinsic::x86_mmx_psrli_q:
9775   case Intrinsic::x86_mmx_psrai_w:
9776   case Intrinsic::x86_mmx_psrai_d: {
9777     SDValue ShAmt = Op.getOperand(2);
9778     if (isa<ConstantSDNode>(ShAmt))
9779       return SDValue();
9780
9781     unsigned NewIntNo = 0;
9782     switch (IntNo) {
9783     case Intrinsic::x86_mmx_pslli_w:
9784       NewIntNo = Intrinsic::x86_mmx_psll_w;
9785       break;
9786     case Intrinsic::x86_mmx_pslli_d:
9787       NewIntNo = Intrinsic::x86_mmx_psll_d;
9788       break;
9789     case Intrinsic::x86_mmx_pslli_q:
9790       NewIntNo = Intrinsic::x86_mmx_psll_q;
9791       break;
9792     case Intrinsic::x86_mmx_psrli_w:
9793       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9794       break;
9795     case Intrinsic::x86_mmx_psrli_d:
9796       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9797       break;
9798     case Intrinsic::x86_mmx_psrli_q:
9799       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9800       break;
9801     case Intrinsic::x86_mmx_psrai_w:
9802       NewIntNo = Intrinsic::x86_mmx_psra_w;
9803       break;
9804     case Intrinsic::x86_mmx_psrai_d:
9805       NewIntNo = Intrinsic::x86_mmx_psra_d;
9806       break;
9807     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9808     }
9809
9810     // The vector shift intrinsics with scalars uses 32b shift amounts but
9811     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9812     // to be zero.
9813     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9814                          DAG.getConstant(0, MVT::i32));
9815 // FIXME this must be lowered to get rid of the invalid type.
9816
9817     EVT VT = Op.getValueType();
9818     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9819     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9820                        DAG.getConstant(NewIntNo, MVT::i32),
9821                        Op.getOperand(1), ShAmt);
9822   }
9823   case Intrinsic::x86_sse42_pcmpistria128:
9824   case Intrinsic::x86_sse42_pcmpestria128:
9825   case Intrinsic::x86_sse42_pcmpistric128:
9826   case Intrinsic::x86_sse42_pcmpestric128:
9827   case Intrinsic::x86_sse42_pcmpistrio128:
9828   case Intrinsic::x86_sse42_pcmpestrio128:
9829   case Intrinsic::x86_sse42_pcmpistris128:
9830   case Intrinsic::x86_sse42_pcmpestris128:
9831   case Intrinsic::x86_sse42_pcmpistriz128:
9832   case Intrinsic::x86_sse42_pcmpestriz128: {
9833     unsigned Opcode;
9834     unsigned X86CC;
9835     switch (IntNo) {
9836     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9837     case Intrinsic::x86_sse42_pcmpistria128:
9838       Opcode = X86ISD::PCMPISTRI;
9839       X86CC = X86::COND_A;
9840       break;
9841     case Intrinsic::x86_sse42_pcmpestria128:
9842       Opcode = X86ISD::PCMPESTRI;
9843       X86CC = X86::COND_A;
9844       break;
9845     case Intrinsic::x86_sse42_pcmpistric128:
9846       Opcode = X86ISD::PCMPISTRI;
9847       X86CC = X86::COND_B;
9848       break;
9849     case Intrinsic::x86_sse42_pcmpestric128:
9850       Opcode = X86ISD::PCMPESTRI;
9851       X86CC = X86::COND_B;
9852       break;
9853     case Intrinsic::x86_sse42_pcmpistrio128:
9854       Opcode = X86ISD::PCMPISTRI;
9855       X86CC = X86::COND_O;
9856       break;
9857     case Intrinsic::x86_sse42_pcmpestrio128:
9858       Opcode = X86ISD::PCMPESTRI;
9859       X86CC = X86::COND_O;
9860       break;
9861     case Intrinsic::x86_sse42_pcmpistris128:
9862       Opcode = X86ISD::PCMPISTRI;
9863       X86CC = X86::COND_S;
9864       break;
9865     case Intrinsic::x86_sse42_pcmpestris128:
9866       Opcode = X86ISD::PCMPESTRI;
9867       X86CC = X86::COND_S;
9868       break;
9869     case Intrinsic::x86_sse42_pcmpistriz128:
9870       Opcode = X86ISD::PCMPISTRI;
9871       X86CC = X86::COND_E;
9872       break;
9873     case Intrinsic::x86_sse42_pcmpestriz128:
9874       Opcode = X86ISD::PCMPESTRI;
9875       X86CC = X86::COND_E;
9876       break;
9877     }
9878     SmallVector<SDValue, 5> NewOps;
9879     NewOps.append(Op->op_begin()+1, Op->op_end());
9880     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9881     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9882     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9883                                 DAG.getConstant(X86CC, MVT::i8),
9884                                 SDValue(PCMP.getNode(), 1));
9885     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9886   }
9887   case Intrinsic::x86_sse42_pcmpistri128:
9888   case Intrinsic::x86_sse42_pcmpestri128: {
9889     unsigned Opcode;
9890     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
9891       Opcode = X86ISD::PCMPISTRI;
9892     else
9893       Opcode = X86ISD::PCMPESTRI;
9894
9895     SmallVector<SDValue, 5> NewOps;
9896     NewOps.append(Op->op_begin()+1, Op->op_end());
9897     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9898     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9899   }
9900   }
9901 }
9902
9903 SDValue
9904 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9905   DebugLoc dl = Op.getDebugLoc();
9906   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9907   switch (IntNo) {
9908   default: return SDValue();    // Don't custom lower most intrinsics.
9909
9910   // RDRAND intrinsics.
9911   case Intrinsic::x86_rdrand_16:
9912   case Intrinsic::x86_rdrand_32:
9913   case Intrinsic::x86_rdrand_64: {
9914     // Emit the node with the right value type.
9915     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9916     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9917
9918     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9919     // return the value from Rand, which is always 0, casted to i32.
9920     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9921                       DAG.getConstant(1, Op->getValueType(1)),
9922                       DAG.getConstant(X86::COND_B, MVT::i32),
9923                       SDValue(Result.getNode(), 1) };
9924     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9925                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
9926                                   Ops, 4);
9927
9928     // Return { result, isValid, chain }.
9929     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9930                        SDValue(Result.getNode(), 2));
9931   }
9932   }
9933 }
9934
9935 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9936                                            SelectionDAG &DAG) const {
9937   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9938   MFI->setReturnAddressIsTaken(true);
9939
9940   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9941   DebugLoc dl = Op.getDebugLoc();
9942
9943   if (Depth > 0) {
9944     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9945     SDValue Offset =
9946       DAG.getConstant(TD->getPointerSize(),
9947                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9948     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9949                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9950                                    FrameAddr, Offset),
9951                        MachinePointerInfo(), false, false, false, 0);
9952   }
9953
9954   // Just load the return address.
9955   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9956   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9957                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9958 }
9959
9960 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9961   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9962   MFI->setFrameAddressIsTaken(true);
9963
9964   EVT VT = Op.getValueType();
9965   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9966   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9967   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9968   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9969   while (Depth--)
9970     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9971                             MachinePointerInfo(),
9972                             false, false, false, 0);
9973   return FrameAddr;
9974 }
9975
9976 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9977                                                      SelectionDAG &DAG) const {
9978   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9979 }
9980
9981 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9982   SDValue Chain     = Op.getOperand(0);
9983   SDValue Offset    = Op.getOperand(1);
9984   SDValue Handler   = Op.getOperand(2);
9985   DebugLoc dl       = Op.getDebugLoc();
9986
9987   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9988                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9989                                      getPointerTy());
9990   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9991
9992   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9993                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9994   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9995   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9996                        false, false, 0);
9997   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9998
9999   return DAG.getNode(X86ISD::EH_RETURN, dl,
10000                      MVT::Other,
10001                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10002 }
10003
10004 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10005                                                   SelectionDAG &DAG) const {
10006   return Op.getOperand(0);
10007 }
10008
10009 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10010                                                 SelectionDAG &DAG) const {
10011   SDValue Root = Op.getOperand(0);
10012   SDValue Trmp = Op.getOperand(1); // trampoline
10013   SDValue FPtr = Op.getOperand(2); // nested function
10014   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10015   DebugLoc dl  = Op.getDebugLoc();
10016
10017   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10018
10019   if (Subtarget->is64Bit()) {
10020     SDValue OutChains[6];
10021
10022     // Large code-model.
10023     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10024     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10025
10026     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10027     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10028
10029     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10030
10031     // Load the pointer to the nested function into R11.
10032     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10033     SDValue Addr = Trmp;
10034     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10035                                 Addr, MachinePointerInfo(TrmpAddr),
10036                                 false, false, 0);
10037
10038     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10039                        DAG.getConstant(2, MVT::i64));
10040     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10041                                 MachinePointerInfo(TrmpAddr, 2),
10042                                 false, false, 2);
10043
10044     // Load the 'nest' parameter value into R10.
10045     // R10 is specified in X86CallingConv.td
10046     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10047     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10048                        DAG.getConstant(10, MVT::i64));
10049     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10050                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10051                                 false, false, 0);
10052
10053     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10054                        DAG.getConstant(12, MVT::i64));
10055     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10056                                 MachinePointerInfo(TrmpAddr, 12),
10057                                 false, false, 2);
10058
10059     // Jump to the nested function.
10060     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10061     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10062                        DAG.getConstant(20, MVT::i64));
10063     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10064                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10065                                 false, false, 0);
10066
10067     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10068     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10069                        DAG.getConstant(22, MVT::i64));
10070     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10071                                 MachinePointerInfo(TrmpAddr, 22),
10072                                 false, false, 0);
10073
10074     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10075   } else {
10076     const Function *Func =
10077       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10078     CallingConv::ID CC = Func->getCallingConv();
10079     unsigned NestReg;
10080
10081     switch (CC) {
10082     default:
10083       llvm_unreachable("Unsupported calling convention");
10084     case CallingConv::C:
10085     case CallingConv::X86_StdCall: {
10086       // Pass 'nest' parameter in ECX.
10087       // Must be kept in sync with X86CallingConv.td
10088       NestReg = X86::ECX;
10089
10090       // Check that ECX wasn't needed by an 'inreg' parameter.
10091       FunctionType *FTy = Func->getFunctionType();
10092       const AttrListPtr &Attrs = Func->getAttributes();
10093
10094       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10095         unsigned InRegCount = 0;
10096         unsigned Idx = 1;
10097
10098         for (FunctionType::param_iterator I = FTy->param_begin(),
10099              E = FTy->param_end(); I != E; ++I, ++Idx)
10100           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10101             // FIXME: should only count parameters that are lowered to integers.
10102             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10103
10104         if (InRegCount > 2) {
10105           report_fatal_error("Nest register in use - reduce number of inreg"
10106                              " parameters!");
10107         }
10108       }
10109       break;
10110     }
10111     case CallingConv::X86_FastCall:
10112     case CallingConv::X86_ThisCall:
10113     case CallingConv::Fast:
10114       // Pass 'nest' parameter in EAX.
10115       // Must be kept in sync with X86CallingConv.td
10116       NestReg = X86::EAX;
10117       break;
10118     }
10119
10120     SDValue OutChains[4];
10121     SDValue Addr, Disp;
10122
10123     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10124                        DAG.getConstant(10, MVT::i32));
10125     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10126
10127     // This is storing the opcode for MOV32ri.
10128     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10129     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10130     OutChains[0] = DAG.getStore(Root, dl,
10131                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10132                                 Trmp, MachinePointerInfo(TrmpAddr),
10133                                 false, false, 0);
10134
10135     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10136                        DAG.getConstant(1, MVT::i32));
10137     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10138                                 MachinePointerInfo(TrmpAddr, 1),
10139                                 false, false, 1);
10140
10141     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10142     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10143                        DAG.getConstant(5, MVT::i32));
10144     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10145                                 MachinePointerInfo(TrmpAddr, 5),
10146                                 false, false, 1);
10147
10148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10149                        DAG.getConstant(6, MVT::i32));
10150     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10151                                 MachinePointerInfo(TrmpAddr, 6),
10152                                 false, false, 1);
10153
10154     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10155   }
10156 }
10157
10158 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10159                                             SelectionDAG &DAG) const {
10160   /*
10161    The rounding mode is in bits 11:10 of FPSR, and has the following
10162    settings:
10163      00 Round to nearest
10164      01 Round to -inf
10165      10 Round to +inf
10166      11 Round to 0
10167
10168   FLT_ROUNDS, on the other hand, expects the following:
10169     -1 Undefined
10170      0 Round to 0
10171      1 Round to nearest
10172      2 Round to +inf
10173      3 Round to -inf
10174
10175   To perform the conversion, we do:
10176     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10177   */
10178
10179   MachineFunction &MF = DAG.getMachineFunction();
10180   const TargetMachine &TM = MF.getTarget();
10181   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10182   unsigned StackAlignment = TFI.getStackAlignment();
10183   EVT VT = Op.getValueType();
10184   DebugLoc DL = Op.getDebugLoc();
10185
10186   // Save FP Control Word to stack slot
10187   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10188   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10189
10190
10191   MachineMemOperand *MMO =
10192    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10193                            MachineMemOperand::MOStore, 2, 2);
10194
10195   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10196   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10197                                           DAG.getVTList(MVT::Other),
10198                                           Ops, 2, MVT::i16, MMO);
10199
10200   // Load FP Control Word from stack slot
10201   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10202                             MachinePointerInfo(), false, false, false, 0);
10203
10204   // Transform as necessary
10205   SDValue CWD1 =
10206     DAG.getNode(ISD::SRL, DL, MVT::i16,
10207                 DAG.getNode(ISD::AND, DL, MVT::i16,
10208                             CWD, DAG.getConstant(0x800, MVT::i16)),
10209                 DAG.getConstant(11, MVT::i8));
10210   SDValue CWD2 =
10211     DAG.getNode(ISD::SRL, DL, MVT::i16,
10212                 DAG.getNode(ISD::AND, DL, MVT::i16,
10213                             CWD, DAG.getConstant(0x400, MVT::i16)),
10214                 DAG.getConstant(9, MVT::i8));
10215
10216   SDValue RetVal =
10217     DAG.getNode(ISD::AND, DL, MVT::i16,
10218                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10219                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10220                             DAG.getConstant(1, MVT::i16)),
10221                 DAG.getConstant(3, MVT::i16));
10222
10223
10224   return DAG.getNode((VT.getSizeInBits() < 16 ?
10225                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10226 }
10227
10228 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10229   EVT VT = Op.getValueType();
10230   EVT OpVT = VT;
10231   unsigned NumBits = VT.getSizeInBits();
10232   DebugLoc dl = Op.getDebugLoc();
10233
10234   Op = Op.getOperand(0);
10235   if (VT == MVT::i8) {
10236     // Zero extend to i32 since there is not an i8 bsr.
10237     OpVT = MVT::i32;
10238     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10239   }
10240
10241   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10242   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10243   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10244
10245   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10246   SDValue Ops[] = {
10247     Op,
10248     DAG.getConstant(NumBits+NumBits-1, OpVT),
10249     DAG.getConstant(X86::COND_E, MVT::i8),
10250     Op.getValue(1)
10251   };
10252   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10253
10254   // Finally xor with NumBits-1.
10255   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10256
10257   if (VT == MVT::i8)
10258     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10259   return Op;
10260 }
10261
10262 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10263                                                 SelectionDAG &DAG) const {
10264   EVT VT = Op.getValueType();
10265   EVT OpVT = VT;
10266   unsigned NumBits = VT.getSizeInBits();
10267   DebugLoc dl = Op.getDebugLoc();
10268
10269   Op = Op.getOperand(0);
10270   if (VT == MVT::i8) {
10271     // Zero extend to i32 since there is not an i8 bsr.
10272     OpVT = MVT::i32;
10273     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10274   }
10275
10276   // Issue a bsr (scan bits in reverse).
10277   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10278   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10279
10280   // And xor with NumBits-1.
10281   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10282
10283   if (VT == MVT::i8)
10284     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10285   return Op;
10286 }
10287
10288 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10289   EVT VT = Op.getValueType();
10290   unsigned NumBits = VT.getSizeInBits();
10291   DebugLoc dl = Op.getDebugLoc();
10292   Op = Op.getOperand(0);
10293
10294   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10295   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10296   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10297
10298   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10299   SDValue Ops[] = {
10300     Op,
10301     DAG.getConstant(NumBits, VT),
10302     DAG.getConstant(X86::COND_E, MVT::i8),
10303     Op.getValue(1)
10304   };
10305   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10306 }
10307
10308 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10309 // ones, and then concatenate the result back.
10310 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10311   EVT VT = Op.getValueType();
10312
10313   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10314          "Unsupported value type for operation");
10315
10316   unsigned NumElems = VT.getVectorNumElements();
10317   DebugLoc dl = Op.getDebugLoc();
10318
10319   // Extract the LHS vectors
10320   SDValue LHS = Op.getOperand(0);
10321   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10322   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10323
10324   // Extract the RHS vectors
10325   SDValue RHS = Op.getOperand(1);
10326   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10327   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10328
10329   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10330   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10331
10332   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10333                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10334                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10335 }
10336
10337 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10338   assert(Op.getValueType().getSizeInBits() == 256 &&
10339          Op.getValueType().isInteger() &&
10340          "Only handle AVX 256-bit vector integer operation");
10341   return Lower256IntArith(Op, DAG);
10342 }
10343
10344 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10345   assert(Op.getValueType().getSizeInBits() == 256 &&
10346          Op.getValueType().isInteger() &&
10347          "Only handle AVX 256-bit vector integer operation");
10348   return Lower256IntArith(Op, DAG);
10349 }
10350
10351 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10352   EVT VT = Op.getValueType();
10353
10354   // Decompose 256-bit ops into smaller 128-bit ops.
10355   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10356     return Lower256IntArith(Op, DAG);
10357
10358   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10359          "Only know how to lower V2I64/V4I64 multiply");
10360
10361   DebugLoc dl = Op.getDebugLoc();
10362
10363   //  Ahi = psrlqi(a, 32);
10364   //  Bhi = psrlqi(b, 32);
10365   //
10366   //  AloBlo = pmuludq(a, b);
10367   //  AloBhi = pmuludq(a, Bhi);
10368   //  AhiBlo = pmuludq(Ahi, b);
10369
10370   //  AloBhi = psllqi(AloBhi, 32);
10371   //  AhiBlo = psllqi(AhiBlo, 32);
10372   //  return AloBlo + AloBhi + AhiBlo;
10373
10374   SDValue A = Op.getOperand(0);
10375   SDValue B = Op.getOperand(1);
10376
10377   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10378
10379   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10380   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10381
10382   // Bit cast to 32-bit vectors for MULUDQ
10383   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10384   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10385   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10386   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10387   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10388
10389   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10390   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10391   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10392
10393   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10394   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10395
10396   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10397   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10398 }
10399
10400 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10401
10402   EVT VT = Op.getValueType();
10403   DebugLoc dl = Op.getDebugLoc();
10404   SDValue R = Op.getOperand(0);
10405   SDValue Amt = Op.getOperand(1);
10406   LLVMContext *Context = DAG.getContext();
10407
10408   if (!Subtarget->hasSSE2())
10409     return SDValue();
10410
10411   // Optimize shl/srl/sra with constant shift amount.
10412   if (isSplatVector(Amt.getNode())) {
10413     SDValue SclrAmt = Amt->getOperand(0);
10414     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10415       uint64_t ShiftAmt = C->getZExtValue();
10416
10417       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10418           (Subtarget->hasAVX2() &&
10419            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10420         if (Op.getOpcode() == ISD::SHL)
10421           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10422                              DAG.getConstant(ShiftAmt, MVT::i32));
10423         if (Op.getOpcode() == ISD::SRL)
10424           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10425                              DAG.getConstant(ShiftAmt, MVT::i32));
10426         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10427           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10428                              DAG.getConstant(ShiftAmt, MVT::i32));
10429       }
10430
10431       if (VT == MVT::v16i8) {
10432         if (Op.getOpcode() == ISD::SHL) {
10433           // Make a large shift.
10434           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10435                                     DAG.getConstant(ShiftAmt, MVT::i32));
10436           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10437           // Zero out the rightmost bits.
10438           SmallVector<SDValue, 16> V(16,
10439                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10440                                                      MVT::i8));
10441           return DAG.getNode(ISD::AND, dl, VT, SHL,
10442                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10443         }
10444         if (Op.getOpcode() == ISD::SRL) {
10445           // Make a large shift.
10446           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10447                                     DAG.getConstant(ShiftAmt, MVT::i32));
10448           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10449           // Zero out the leftmost bits.
10450           SmallVector<SDValue, 16> V(16,
10451                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10452                                                      MVT::i8));
10453           return DAG.getNode(ISD::AND, dl, VT, SRL,
10454                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10455         }
10456         if (Op.getOpcode() == ISD::SRA) {
10457           if (ShiftAmt == 7) {
10458             // R s>> 7  ===  R s< 0
10459             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10460             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10461           }
10462
10463           // R s>> a === ((R u>> a) ^ m) - m
10464           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10465           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10466                                                          MVT::i8));
10467           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10468           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10469           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10470           return Res;
10471         }
10472         llvm_unreachable("Unknown shift opcode.");
10473       }
10474
10475       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10476         if (Op.getOpcode() == ISD::SHL) {
10477           // Make a large shift.
10478           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10479                                     DAG.getConstant(ShiftAmt, MVT::i32));
10480           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10481           // Zero out the rightmost bits.
10482           SmallVector<SDValue, 32> V(32,
10483                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10484                                                      MVT::i8));
10485           return DAG.getNode(ISD::AND, dl, VT, SHL,
10486                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10487         }
10488         if (Op.getOpcode() == ISD::SRL) {
10489           // Make a large shift.
10490           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10491                                     DAG.getConstant(ShiftAmt, MVT::i32));
10492           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10493           // Zero out the leftmost bits.
10494           SmallVector<SDValue, 32> V(32,
10495                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10496                                                      MVT::i8));
10497           return DAG.getNode(ISD::AND, dl, VT, SRL,
10498                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10499         }
10500         if (Op.getOpcode() == ISD::SRA) {
10501           if (ShiftAmt == 7) {
10502             // R s>> 7  ===  R s< 0
10503             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10504             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10505           }
10506
10507           // R s>> a === ((R u>> a) ^ m) - m
10508           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10509           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10510                                                          MVT::i8));
10511           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10512           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10513           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10514           return Res;
10515         }
10516         llvm_unreachable("Unknown shift opcode.");
10517       }
10518     }
10519   }
10520
10521   // Lower SHL with variable shift amount.
10522   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10523     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10524                      DAG.getConstant(23, MVT::i32));
10525
10526     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10527     Constant *C = ConstantDataVector::get(*Context, CV);
10528     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10529     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10530                                  MachinePointerInfo::getConstantPool(),
10531                                  false, false, false, 16);
10532
10533     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10534     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10535     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10536     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10537   }
10538   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10539     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10540
10541     // a = a << 5;
10542     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10543                      DAG.getConstant(5, MVT::i32));
10544     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10545
10546     // Turn 'a' into a mask suitable for VSELECT
10547     SDValue VSelM = DAG.getConstant(0x80, VT);
10548     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10549     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10550
10551     SDValue CM1 = DAG.getConstant(0x0f, VT);
10552     SDValue CM2 = DAG.getConstant(0x3f, VT);
10553
10554     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10555     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10556     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10557                             DAG.getConstant(4, MVT::i32), DAG);
10558     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10559     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10560
10561     // a += a
10562     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10563     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10564     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10565
10566     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10567     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10568     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10569                             DAG.getConstant(2, MVT::i32), DAG);
10570     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10571     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10572
10573     // a += a
10574     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10575     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10576     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10577
10578     // return VSELECT(r, r+r, a);
10579     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10580                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10581     return R;
10582   }
10583
10584   // Decompose 256-bit shifts into smaller 128-bit shifts.
10585   if (VT.getSizeInBits() == 256) {
10586     unsigned NumElems = VT.getVectorNumElements();
10587     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10588     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10589
10590     // Extract the two vectors
10591     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10592     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10593
10594     // Recreate the shift amount vectors
10595     SDValue Amt1, Amt2;
10596     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10597       // Constant shift amount
10598       SmallVector<SDValue, 4> Amt1Csts;
10599       SmallVector<SDValue, 4> Amt2Csts;
10600       for (unsigned i = 0; i != NumElems/2; ++i)
10601         Amt1Csts.push_back(Amt->getOperand(i));
10602       for (unsigned i = NumElems/2; i != NumElems; ++i)
10603         Amt2Csts.push_back(Amt->getOperand(i));
10604
10605       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10606                                  &Amt1Csts[0], NumElems/2);
10607       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10608                                  &Amt2Csts[0], NumElems/2);
10609     } else {
10610       // Variable shift amount
10611       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10612       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10613     }
10614
10615     // Issue new vector shifts for the smaller types
10616     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10617     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10618
10619     // Concatenate the result back
10620     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10621   }
10622
10623   return SDValue();
10624 }
10625
10626 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10627   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10628   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10629   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10630   // has only one use.
10631   SDNode *N = Op.getNode();
10632   SDValue LHS = N->getOperand(0);
10633   SDValue RHS = N->getOperand(1);
10634   unsigned BaseOp = 0;
10635   unsigned Cond = 0;
10636   DebugLoc DL = Op.getDebugLoc();
10637   switch (Op.getOpcode()) {
10638   default: llvm_unreachable("Unknown ovf instruction!");
10639   case ISD::SADDO:
10640     // A subtract of one will be selected as a INC. Note that INC doesn't
10641     // set CF, so we can't do this for UADDO.
10642     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10643       if (C->isOne()) {
10644         BaseOp = X86ISD::INC;
10645         Cond = X86::COND_O;
10646         break;
10647       }
10648     BaseOp = X86ISD::ADD;
10649     Cond = X86::COND_O;
10650     break;
10651   case ISD::UADDO:
10652     BaseOp = X86ISD::ADD;
10653     Cond = X86::COND_B;
10654     break;
10655   case ISD::SSUBO:
10656     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10657     // set CF, so we can't do this for USUBO.
10658     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10659       if (C->isOne()) {
10660         BaseOp = X86ISD::DEC;
10661         Cond = X86::COND_O;
10662         break;
10663       }
10664     BaseOp = X86ISD::SUB;
10665     Cond = X86::COND_O;
10666     break;
10667   case ISD::USUBO:
10668     BaseOp = X86ISD::SUB;
10669     Cond = X86::COND_B;
10670     break;
10671   case ISD::SMULO:
10672     BaseOp = X86ISD::SMUL;
10673     Cond = X86::COND_O;
10674     break;
10675   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10676     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10677                                  MVT::i32);
10678     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10679
10680     SDValue SetCC =
10681       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10682                   DAG.getConstant(X86::COND_O, MVT::i32),
10683                   SDValue(Sum.getNode(), 2));
10684
10685     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10686   }
10687   }
10688
10689   // Also sets EFLAGS.
10690   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10691   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10692
10693   SDValue SetCC =
10694     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10695                 DAG.getConstant(Cond, MVT::i32),
10696                 SDValue(Sum.getNode(), 1));
10697
10698   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10699 }
10700
10701 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10702                                                   SelectionDAG &DAG) const {
10703   DebugLoc dl = Op.getDebugLoc();
10704   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10705   EVT VT = Op.getValueType();
10706
10707   if (!Subtarget->hasSSE2() || !VT.isVector())
10708     return SDValue();
10709
10710   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10711                       ExtraVT.getScalarType().getSizeInBits();
10712   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10713
10714   switch (VT.getSimpleVT().SimpleTy) {
10715     default: return SDValue();
10716     case MVT::v8i32:
10717     case MVT::v16i16:
10718       if (!Subtarget->hasAVX())
10719         return SDValue();
10720       if (!Subtarget->hasAVX2()) {
10721         // needs to be split
10722         unsigned NumElems = VT.getVectorNumElements();
10723
10724         // Extract the LHS vectors
10725         SDValue LHS = Op.getOperand(0);
10726         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10727         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10728
10729         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10730         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10731
10732         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10733         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10734         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10735                                    ExtraNumElems/2);
10736         SDValue Extra = DAG.getValueType(ExtraVT);
10737
10738         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10739         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10740
10741         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10742       }
10743       // fall through
10744     case MVT::v4i32:
10745     case MVT::v8i16: {
10746       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10747                                          Op.getOperand(0), ShAmt, DAG);
10748       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10749     }
10750   }
10751 }
10752
10753
10754 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10755   DebugLoc dl = Op.getDebugLoc();
10756
10757   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10758   // There isn't any reason to disable it if the target processor supports it.
10759   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10760     SDValue Chain = Op.getOperand(0);
10761     SDValue Zero = DAG.getConstant(0, MVT::i32);
10762     SDValue Ops[] = {
10763       DAG.getRegister(X86::ESP, MVT::i32), // Base
10764       DAG.getTargetConstant(1, MVT::i8),   // Scale
10765       DAG.getRegister(0, MVT::i32),        // Index
10766       DAG.getTargetConstant(0, MVT::i32),  // Disp
10767       DAG.getRegister(0, MVT::i32),        // Segment.
10768       Zero,
10769       Chain
10770     };
10771     SDNode *Res =
10772       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10773                           array_lengthof(Ops));
10774     return SDValue(Res, 0);
10775   }
10776
10777   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10778   if (!isDev)
10779     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10780
10781   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10782   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10783   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10784   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10785
10786   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10787   if (!Op1 && !Op2 && !Op3 && Op4)
10788     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10789
10790   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10791   if (Op1 && !Op2 && !Op3 && !Op4)
10792     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10793
10794   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10795   //           (MFENCE)>;
10796   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10797 }
10798
10799 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10800                                              SelectionDAG &DAG) const {
10801   DebugLoc dl = Op.getDebugLoc();
10802   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10803     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10804   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10805     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10806
10807   // The only fence that needs an instruction is a sequentially-consistent
10808   // cross-thread fence.
10809   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10810     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10811     // no-sse2). There isn't any reason to disable it if the target processor
10812     // supports it.
10813     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10814       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10815
10816     SDValue Chain = Op.getOperand(0);
10817     SDValue Zero = DAG.getConstant(0, MVT::i32);
10818     SDValue Ops[] = {
10819       DAG.getRegister(X86::ESP, MVT::i32), // Base
10820       DAG.getTargetConstant(1, MVT::i8),   // Scale
10821       DAG.getRegister(0, MVT::i32),        // Index
10822       DAG.getTargetConstant(0, MVT::i32),  // Disp
10823       DAG.getRegister(0, MVT::i32),        // Segment.
10824       Zero,
10825       Chain
10826     };
10827     SDNode *Res =
10828       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10829                          array_lengthof(Ops));
10830     return SDValue(Res, 0);
10831   }
10832
10833   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10834   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10835 }
10836
10837
10838 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10839   EVT T = Op.getValueType();
10840   DebugLoc DL = Op.getDebugLoc();
10841   unsigned Reg = 0;
10842   unsigned size = 0;
10843   switch(T.getSimpleVT().SimpleTy) {
10844   default: llvm_unreachable("Invalid value type!");
10845   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10846   case MVT::i16: Reg = X86::AX;  size = 2; break;
10847   case MVT::i32: Reg = X86::EAX; size = 4; break;
10848   case MVT::i64:
10849     assert(Subtarget->is64Bit() && "Node not type legal!");
10850     Reg = X86::RAX; size = 8;
10851     break;
10852   }
10853   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10854                                     Op.getOperand(2), SDValue());
10855   SDValue Ops[] = { cpIn.getValue(0),
10856                     Op.getOperand(1),
10857                     Op.getOperand(3),
10858                     DAG.getTargetConstant(size, MVT::i8),
10859                     cpIn.getValue(1) };
10860   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10861   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10862   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10863                                            Ops, 5, T, MMO);
10864   SDValue cpOut =
10865     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10866   return cpOut;
10867 }
10868
10869 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10870                                                  SelectionDAG &DAG) const {
10871   assert(Subtarget->is64Bit() && "Result not type legalized?");
10872   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10873   SDValue TheChain = Op.getOperand(0);
10874   DebugLoc dl = Op.getDebugLoc();
10875   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10876   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10877   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10878                                    rax.getValue(2));
10879   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10880                             DAG.getConstant(32, MVT::i8));
10881   SDValue Ops[] = {
10882     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10883     rdx.getValue(1)
10884   };
10885   return DAG.getMergeValues(Ops, 2, dl);
10886 }
10887
10888 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10889                                             SelectionDAG &DAG) const {
10890   EVT SrcVT = Op.getOperand(0).getValueType();
10891   EVT DstVT = Op.getValueType();
10892   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10893          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10894   assert((DstVT == MVT::i64 ||
10895           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10896          "Unexpected custom BITCAST");
10897   // i64 <=> MMX conversions are Legal.
10898   if (SrcVT==MVT::i64 && DstVT.isVector())
10899     return Op;
10900   if (DstVT==MVT::i64 && SrcVT.isVector())
10901     return Op;
10902   // MMX <=> MMX conversions are Legal.
10903   if (SrcVT.isVector() && DstVT.isVector())
10904     return Op;
10905   // All other conversions need to be expanded.
10906   return SDValue();
10907 }
10908
10909 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10910   SDNode *Node = Op.getNode();
10911   DebugLoc dl = Node->getDebugLoc();
10912   EVT T = Node->getValueType(0);
10913   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10914                               DAG.getConstant(0, T), Node->getOperand(2));
10915   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10916                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10917                        Node->getOperand(0),
10918                        Node->getOperand(1), negOp,
10919                        cast<AtomicSDNode>(Node)->getSrcValue(),
10920                        cast<AtomicSDNode>(Node)->getAlignment(),
10921                        cast<AtomicSDNode>(Node)->getOrdering(),
10922                        cast<AtomicSDNode>(Node)->getSynchScope());
10923 }
10924
10925 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10926   SDNode *Node = Op.getNode();
10927   DebugLoc dl = Node->getDebugLoc();
10928   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10929
10930   // Convert seq_cst store -> xchg
10931   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10932   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10933   //        (The only way to get a 16-byte store is cmpxchg16b)
10934   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10935   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10936       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10937     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10938                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10939                                  Node->getOperand(0),
10940                                  Node->getOperand(1), Node->getOperand(2),
10941                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10942                                  cast<AtomicSDNode>(Node)->getOrdering(),
10943                                  cast<AtomicSDNode>(Node)->getSynchScope());
10944     return Swap.getValue(1);
10945   }
10946   // Other atomic stores have a simple pattern.
10947   return Op;
10948 }
10949
10950 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10951   EVT VT = Op.getNode()->getValueType(0);
10952
10953   // Let legalize expand this if it isn't a legal type yet.
10954   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10955     return SDValue();
10956
10957   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10958
10959   unsigned Opc;
10960   bool ExtraOp = false;
10961   switch (Op.getOpcode()) {
10962   default: llvm_unreachable("Invalid code");
10963   case ISD::ADDC: Opc = X86ISD::ADD; break;
10964   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10965   case ISD::SUBC: Opc = X86ISD::SUB; break;
10966   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10967   }
10968
10969   if (!ExtraOp)
10970     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10971                        Op.getOperand(1));
10972   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10973                      Op.getOperand(1), Op.getOperand(2));
10974 }
10975
10976 /// LowerOperation - Provide custom lowering hooks for some operations.
10977 ///
10978 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10979   switch (Op.getOpcode()) {
10980   default: llvm_unreachable("Should not custom lower this!");
10981   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10982   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10983   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10984   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10985   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10986   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10987   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10988   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10989   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10990   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10991   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10992   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10993   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10994   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10995   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10996   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10997   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10998   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10999   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11000   case ISD::SHL_PARTS:
11001   case ISD::SRA_PARTS:
11002   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11003   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11004   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11005   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11006   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11007   case ISD::FABS:               return LowerFABS(Op, DAG);
11008   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11009   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11010   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11011   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11012   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11013   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11014   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11015   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11016   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11017   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11018   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11019   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11020   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11021   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11022   case ISD::FRAME_TO_ARGS_OFFSET:
11023                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11024   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11025   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11026   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11027   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11028   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11029   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11030   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11031   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11032   case ISD::MUL:                return LowerMUL(Op, DAG);
11033   case ISD::SRA:
11034   case ISD::SRL:
11035   case ISD::SHL:                return LowerShift(Op, DAG);
11036   case ISD::SADDO:
11037   case ISD::UADDO:
11038   case ISD::SSUBO:
11039   case ISD::USUBO:
11040   case ISD::SMULO:
11041   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11042   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11043   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11044   case ISD::ADDC:
11045   case ISD::ADDE:
11046   case ISD::SUBC:
11047   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11048   case ISD::ADD:                return LowerADD(Op, DAG);
11049   case ISD::SUB:                return LowerSUB(Op, DAG);
11050   }
11051 }
11052
11053 static void ReplaceATOMIC_LOAD(SDNode *Node,
11054                                   SmallVectorImpl<SDValue> &Results,
11055                                   SelectionDAG &DAG) {
11056   DebugLoc dl = Node->getDebugLoc();
11057   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11058
11059   // Convert wide load -> cmpxchg8b/cmpxchg16b
11060   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11061   //        (The only way to get a 16-byte load is cmpxchg16b)
11062   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11063   SDValue Zero = DAG.getConstant(0, VT);
11064   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11065                                Node->getOperand(0),
11066                                Node->getOperand(1), Zero, Zero,
11067                                cast<AtomicSDNode>(Node)->getMemOperand(),
11068                                cast<AtomicSDNode>(Node)->getOrdering(),
11069                                cast<AtomicSDNode>(Node)->getSynchScope());
11070   Results.push_back(Swap.getValue(0));
11071   Results.push_back(Swap.getValue(1));
11072 }
11073
11074 void X86TargetLowering::
11075 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11076                         SelectionDAG &DAG, unsigned NewOp) const {
11077   DebugLoc dl = Node->getDebugLoc();
11078   assert (Node->getValueType(0) == MVT::i64 &&
11079           "Only know how to expand i64 atomics");
11080
11081   SDValue Chain = Node->getOperand(0);
11082   SDValue In1 = Node->getOperand(1);
11083   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11084                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11085   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11086                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11087   SDValue Ops[] = { Chain, In1, In2L, In2H };
11088   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11089   SDValue Result =
11090     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11091                             cast<MemSDNode>(Node)->getMemOperand());
11092   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11093   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11094   Results.push_back(Result.getValue(2));
11095 }
11096
11097 /// ReplaceNodeResults - Replace a node with an illegal result type
11098 /// with a new node built out of custom code.
11099 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11100                                            SmallVectorImpl<SDValue>&Results,
11101                                            SelectionDAG &DAG) const {
11102   DebugLoc dl = N->getDebugLoc();
11103   switch (N->getOpcode()) {
11104   default:
11105     llvm_unreachable("Do not know how to custom type legalize this operation!");
11106   case ISD::SIGN_EXTEND_INREG:
11107   case ISD::ADDC:
11108   case ISD::ADDE:
11109   case ISD::SUBC:
11110   case ISD::SUBE:
11111     // We don't want to expand or promote these.
11112     return;
11113   case ISD::FP_TO_SINT:
11114   case ISD::FP_TO_UINT: {
11115     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11116
11117     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11118       return;
11119
11120     std::pair<SDValue,SDValue> Vals =
11121         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11122     SDValue FIST = Vals.first, StackSlot = Vals.second;
11123     if (FIST.getNode() != 0) {
11124       EVT VT = N->getValueType(0);
11125       // Return a load from the stack slot.
11126       if (StackSlot.getNode() != 0)
11127         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11128                                       MachinePointerInfo(),
11129                                       false, false, false, 0));
11130       else
11131         Results.push_back(FIST);
11132     }
11133     return;
11134   }
11135   case ISD::READCYCLECOUNTER: {
11136     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11137     SDValue TheChain = N->getOperand(0);
11138     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11139     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11140                                      rd.getValue(1));
11141     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11142                                      eax.getValue(2));
11143     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11144     SDValue Ops[] = { eax, edx };
11145     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11146     Results.push_back(edx.getValue(1));
11147     return;
11148   }
11149   case ISD::ATOMIC_CMP_SWAP: {
11150     EVT T = N->getValueType(0);
11151     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11152     bool Regs64bit = T == MVT::i128;
11153     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11154     SDValue cpInL, cpInH;
11155     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11156                         DAG.getConstant(0, HalfT));
11157     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11158                         DAG.getConstant(1, HalfT));
11159     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11160                              Regs64bit ? X86::RAX : X86::EAX,
11161                              cpInL, SDValue());
11162     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11163                              Regs64bit ? X86::RDX : X86::EDX,
11164                              cpInH, cpInL.getValue(1));
11165     SDValue swapInL, swapInH;
11166     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11167                           DAG.getConstant(0, HalfT));
11168     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11169                           DAG.getConstant(1, HalfT));
11170     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11171                                Regs64bit ? X86::RBX : X86::EBX,
11172                                swapInL, cpInH.getValue(1));
11173     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11174                                Regs64bit ? X86::RCX : X86::ECX,
11175                                swapInH, swapInL.getValue(1));
11176     SDValue Ops[] = { swapInH.getValue(0),
11177                       N->getOperand(1),
11178                       swapInH.getValue(1) };
11179     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11180     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11181     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11182                                   X86ISD::LCMPXCHG8_DAG;
11183     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11184                                              Ops, 3, T, MMO);
11185     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11186                                         Regs64bit ? X86::RAX : X86::EAX,
11187                                         HalfT, Result.getValue(1));
11188     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11189                                         Regs64bit ? X86::RDX : X86::EDX,
11190                                         HalfT, cpOutL.getValue(2));
11191     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11192     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11193     Results.push_back(cpOutH.getValue(1));
11194     return;
11195   }
11196   case ISD::ATOMIC_LOAD_ADD:
11197     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11198     return;
11199   case ISD::ATOMIC_LOAD_AND:
11200     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11201     return;
11202   case ISD::ATOMIC_LOAD_NAND:
11203     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11204     return;
11205   case ISD::ATOMIC_LOAD_OR:
11206     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11207     return;
11208   case ISD::ATOMIC_LOAD_SUB:
11209     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11210     return;
11211   case ISD::ATOMIC_LOAD_XOR:
11212     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11213     return;
11214   case ISD::ATOMIC_SWAP:
11215     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11216     return;
11217   case ISD::ATOMIC_LOAD:
11218     ReplaceATOMIC_LOAD(N, Results, DAG);
11219   }
11220 }
11221
11222 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11223   switch (Opcode) {
11224   default: return NULL;
11225   case X86ISD::BSF:                return "X86ISD::BSF";
11226   case X86ISD::BSR:                return "X86ISD::BSR";
11227   case X86ISD::SHLD:               return "X86ISD::SHLD";
11228   case X86ISD::SHRD:               return "X86ISD::SHRD";
11229   case X86ISD::FAND:               return "X86ISD::FAND";
11230   case X86ISD::FOR:                return "X86ISD::FOR";
11231   case X86ISD::FXOR:               return "X86ISD::FXOR";
11232   case X86ISD::FSRL:               return "X86ISD::FSRL";
11233   case X86ISD::FILD:               return "X86ISD::FILD";
11234   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11235   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11236   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11237   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11238   case X86ISD::FLD:                return "X86ISD::FLD";
11239   case X86ISD::FST:                return "X86ISD::FST";
11240   case X86ISD::CALL:               return "X86ISD::CALL";
11241   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11242   case X86ISD::BT:                 return "X86ISD::BT";
11243   case X86ISD::CMP:                return "X86ISD::CMP";
11244   case X86ISD::COMI:               return "X86ISD::COMI";
11245   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11246   case X86ISD::SETCC:              return "X86ISD::SETCC";
11247   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11248   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11249   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11250   case X86ISD::CMOV:               return "X86ISD::CMOV";
11251   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11252   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11253   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11254   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11255   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11256   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11257   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11258   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11259   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11260   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11261   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11262   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11263   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11264   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11265   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11266   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11267   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11268   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11269   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11270   case X86ISD::HADD:               return "X86ISD::HADD";
11271   case X86ISD::HSUB:               return "X86ISD::HSUB";
11272   case X86ISD::FHADD:              return "X86ISD::FHADD";
11273   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11274   case X86ISD::FMAX:               return "X86ISD::FMAX";
11275   case X86ISD::FMIN:               return "X86ISD::FMIN";
11276   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11277   case X86ISD::FRCP:               return "X86ISD::FRCP";
11278   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11279   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11280   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11281   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11282   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11283   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11284   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11285   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11286   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11287   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11288   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11289   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11290   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11291   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11292   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11293   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11294   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11295   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11296   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11297   case X86ISD::VSHL:               return "X86ISD::VSHL";
11298   case X86ISD::VSRL:               return "X86ISD::VSRL";
11299   case X86ISD::VSRA:               return "X86ISD::VSRA";
11300   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11301   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11302   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11303   case X86ISD::CMPP:               return "X86ISD::CMPP";
11304   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11305   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11306   case X86ISD::ADD:                return "X86ISD::ADD";
11307   case X86ISD::SUB:                return "X86ISD::SUB";
11308   case X86ISD::ADC:                return "X86ISD::ADC";
11309   case X86ISD::SBB:                return "X86ISD::SBB";
11310   case X86ISD::SMUL:               return "X86ISD::SMUL";
11311   case X86ISD::UMUL:               return "X86ISD::UMUL";
11312   case X86ISD::INC:                return "X86ISD::INC";
11313   case X86ISD::DEC:                return "X86ISD::DEC";
11314   case X86ISD::OR:                 return "X86ISD::OR";
11315   case X86ISD::XOR:                return "X86ISD::XOR";
11316   case X86ISD::AND:                return "X86ISD::AND";
11317   case X86ISD::ANDN:               return "X86ISD::ANDN";
11318   case X86ISD::BLSI:               return "X86ISD::BLSI";
11319   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11320   case X86ISD::BLSR:               return "X86ISD::BLSR";
11321   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11322   case X86ISD::PTEST:              return "X86ISD::PTEST";
11323   case X86ISD::TESTP:              return "X86ISD::TESTP";
11324   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11325   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11326   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11327   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11328   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11329   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11330   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11331   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11332   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11333   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11334   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11335   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11336   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11337   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11338   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11339   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11340   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11341   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11342   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11343   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11344   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11345   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11346   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11347   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11348   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11349   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11350   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11351   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11352   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11353   case X86ISD::SAHF:               return "X86ISD::SAHF";
11354   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11355   case X86ISD::FMADD:              return "X86ISD::FMADD";
11356   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11357   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11358   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11359   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11360   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11361   }
11362 }
11363
11364 // isLegalAddressingMode - Return true if the addressing mode represented
11365 // by AM is legal for this target, for a load/store of the specified type.
11366 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11367                                               Type *Ty) const {
11368   // X86 supports extremely general addressing modes.
11369   CodeModel::Model M = getTargetMachine().getCodeModel();
11370   Reloc::Model R = getTargetMachine().getRelocationModel();
11371
11372   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11373   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11374     return false;
11375
11376   if (AM.BaseGV) {
11377     unsigned GVFlags =
11378       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11379
11380     // If a reference to this global requires an extra load, we can't fold it.
11381     if (isGlobalStubReference(GVFlags))
11382       return false;
11383
11384     // If BaseGV requires a register for the PIC base, we cannot also have a
11385     // BaseReg specified.
11386     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11387       return false;
11388
11389     // If lower 4G is not available, then we must use rip-relative addressing.
11390     if ((M != CodeModel::Small || R != Reloc::Static) &&
11391         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11392       return false;
11393   }
11394
11395   switch (AM.Scale) {
11396   case 0:
11397   case 1:
11398   case 2:
11399   case 4:
11400   case 8:
11401     // These scales always work.
11402     break;
11403   case 3:
11404   case 5:
11405   case 9:
11406     // These scales are formed with basereg+scalereg.  Only accept if there is
11407     // no basereg yet.
11408     if (AM.HasBaseReg)
11409       return false;
11410     break;
11411   default:  // Other stuff never works.
11412     return false;
11413   }
11414
11415   return true;
11416 }
11417
11418
11419 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11420   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11421     return false;
11422   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11423   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11424   if (NumBits1 <= NumBits2)
11425     return false;
11426   return true;
11427 }
11428
11429 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11430   return Imm == (int32_t)Imm;
11431 }
11432
11433 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11434   // Can also use sub to handle negated immediates.
11435   return Imm == (int32_t)Imm;
11436 }
11437
11438 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11439   if (!VT1.isInteger() || !VT2.isInteger())
11440     return false;
11441   unsigned NumBits1 = VT1.getSizeInBits();
11442   unsigned NumBits2 = VT2.getSizeInBits();
11443   if (NumBits1 <= NumBits2)
11444     return false;
11445   return true;
11446 }
11447
11448 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11449   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11450   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11451 }
11452
11453 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11454   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11455   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11456 }
11457
11458 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11459   // i16 instructions are longer (0x66 prefix) and potentially slower.
11460   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11461 }
11462
11463 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11464 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11465 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11466 /// are assumed to be legal.
11467 bool
11468 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11469                                       EVT VT) const {
11470   // Very little shuffling can be done for 64-bit vectors right now.
11471   if (VT.getSizeInBits() == 64)
11472     return false;
11473
11474   // FIXME: pshufb, blends, shifts.
11475   return (VT.getVectorNumElements() == 2 ||
11476           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11477           isMOVLMask(M, VT) ||
11478           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11479           isPSHUFDMask(M, VT) ||
11480           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11481           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11482           isPALIGNRMask(M, VT, Subtarget) ||
11483           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11484           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11485           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11486           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11487 }
11488
11489 bool
11490 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11491                                           EVT VT) const {
11492   unsigned NumElts = VT.getVectorNumElements();
11493   // FIXME: This collection of masks seems suspect.
11494   if (NumElts == 2)
11495     return true;
11496   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11497     return (isMOVLMask(Mask, VT)  ||
11498             isCommutedMOVLMask(Mask, VT, true) ||
11499             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11500             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11501   }
11502   return false;
11503 }
11504
11505 //===----------------------------------------------------------------------===//
11506 //                           X86 Scheduler Hooks
11507 //===----------------------------------------------------------------------===//
11508
11509 // private utility function
11510 MachineBasicBlock *
11511 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11512                                                        MachineBasicBlock *MBB,
11513                                                        unsigned regOpc,
11514                                                        unsigned immOpc,
11515                                                        unsigned LoadOpc,
11516                                                        unsigned CXchgOpc,
11517                                                        unsigned notOpc,
11518                                                        unsigned EAXreg,
11519                                                  const TargetRegisterClass *RC,
11520                                                        bool Invert) const {
11521   // For the atomic bitwise operator, we generate
11522   //   thisMBB:
11523   //   newMBB:
11524   //     ld  t1 = [bitinstr.addr]
11525   //     op  t2 = t1, [bitinstr.val]
11526   //     not t3 = t2  (if Invert)
11527   //     mov EAX = t1
11528   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11529   //     bz  newMBB
11530   //     fallthrough -->nextMBB
11531   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11532   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11533   MachineFunction::iterator MBBIter = MBB;
11534   ++MBBIter;
11535
11536   /// First build the CFG
11537   MachineFunction *F = MBB->getParent();
11538   MachineBasicBlock *thisMBB = MBB;
11539   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11540   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11541   F->insert(MBBIter, newMBB);
11542   F->insert(MBBIter, nextMBB);
11543
11544   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11545   nextMBB->splice(nextMBB->begin(), thisMBB,
11546                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11547                   thisMBB->end());
11548   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11549
11550   // Update thisMBB to fall through to newMBB
11551   thisMBB->addSuccessor(newMBB);
11552
11553   // newMBB jumps to itself and fall through to nextMBB
11554   newMBB->addSuccessor(nextMBB);
11555   newMBB->addSuccessor(newMBB);
11556
11557   // Insert instructions into newMBB based on incoming instruction
11558   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11559          "unexpected number of operands");
11560   DebugLoc dl = bInstr->getDebugLoc();
11561   MachineOperand& destOper = bInstr->getOperand(0);
11562   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11563   int numArgs = bInstr->getNumOperands() - 1;
11564   for (int i=0; i < numArgs; ++i)
11565     argOpers[i] = &bInstr->getOperand(i+1);
11566
11567   // x86 address has 4 operands: base, index, scale, and displacement
11568   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11569   int valArgIndx = lastAddrIndx + 1;
11570
11571   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11572   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11573   for (int i=0; i <= lastAddrIndx; ++i)
11574     (*MIB).addOperand(*argOpers[i]);
11575
11576   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11577   assert((argOpers[valArgIndx]->isReg() ||
11578           argOpers[valArgIndx]->isImm()) &&
11579          "invalid operand");
11580   if (argOpers[valArgIndx]->isReg())
11581     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11582   else
11583     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11584   MIB.addReg(t1);
11585   (*MIB).addOperand(*argOpers[valArgIndx]);
11586
11587   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11588   if (Invert) {
11589     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11590   }
11591   else
11592     t3 = t2;
11593
11594   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11595   MIB.addReg(t1);
11596
11597   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11598   for (int i=0; i <= lastAddrIndx; ++i)
11599     (*MIB).addOperand(*argOpers[i]);
11600   MIB.addReg(t3);
11601   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11602   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11603                     bInstr->memoperands_end());
11604
11605   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11606   MIB.addReg(EAXreg);
11607
11608   // insert branch
11609   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11610
11611   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11612   return nextMBB;
11613 }
11614
11615 // private utility function:  64 bit atomics on 32 bit host.
11616 MachineBasicBlock *
11617 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11618                                                        MachineBasicBlock *MBB,
11619                                                        unsigned regOpcL,
11620                                                        unsigned regOpcH,
11621                                                        unsigned immOpcL,
11622                                                        unsigned immOpcH,
11623                                                        bool Invert) const {
11624   // For the atomic bitwise operator, we generate
11625   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11626   //     ld t1,t2 = [bitinstr.addr]
11627   //   newMBB:
11628   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11629   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11630   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11631   //     neg t7, t8 < t5, t6  (if Invert)
11632   //     mov ECX, EBX <- t5, t6
11633   //     mov EAX, EDX <- t1, t2
11634   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11635   //     mov t3, t4 <- EAX, EDX
11636   //     bz  newMBB
11637   //     result in out1, out2
11638   //     fallthrough -->nextMBB
11639
11640   const TargetRegisterClass *RC = &X86::GR32RegClass;
11641   const unsigned LoadOpc = X86::MOV32rm;
11642   const unsigned NotOpc = X86::NOT32r;
11643   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11644   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11645   MachineFunction::iterator MBBIter = MBB;
11646   ++MBBIter;
11647
11648   /// First build the CFG
11649   MachineFunction *F = MBB->getParent();
11650   MachineBasicBlock *thisMBB = MBB;
11651   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11652   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11653   F->insert(MBBIter, newMBB);
11654   F->insert(MBBIter, nextMBB);
11655
11656   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11657   nextMBB->splice(nextMBB->begin(), thisMBB,
11658                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11659                   thisMBB->end());
11660   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11661
11662   // Update thisMBB to fall through to newMBB
11663   thisMBB->addSuccessor(newMBB);
11664
11665   // newMBB jumps to itself and fall through to nextMBB
11666   newMBB->addSuccessor(nextMBB);
11667   newMBB->addSuccessor(newMBB);
11668
11669   DebugLoc dl = bInstr->getDebugLoc();
11670   // Insert instructions into newMBB based on incoming instruction
11671   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11672   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11673          "unexpected number of operands");
11674   MachineOperand& dest1Oper = bInstr->getOperand(0);
11675   MachineOperand& dest2Oper = bInstr->getOperand(1);
11676   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11677   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11678     argOpers[i] = &bInstr->getOperand(i+2);
11679
11680     // We use some of the operands multiple times, so conservatively just
11681     // clear any kill flags that might be present.
11682     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11683       argOpers[i]->setIsKill(false);
11684   }
11685
11686   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11687   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11688
11689   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11690   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11691   for (int i=0; i <= lastAddrIndx; ++i)
11692     (*MIB).addOperand(*argOpers[i]);
11693   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11694   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11695   // add 4 to displacement.
11696   for (int i=0; i <= lastAddrIndx-2; ++i)
11697     (*MIB).addOperand(*argOpers[i]);
11698   MachineOperand newOp3 = *(argOpers[3]);
11699   if (newOp3.isImm())
11700     newOp3.setImm(newOp3.getImm()+4);
11701   else
11702     newOp3.setOffset(newOp3.getOffset()+4);
11703   (*MIB).addOperand(newOp3);
11704   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11705
11706   // t3/4 are defined later, at the bottom of the loop
11707   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11708   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11709   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11710     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11711   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11712     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11713
11714   // The subsequent operations should be using the destination registers of
11715   // the PHI instructions.
11716   t1 = dest1Oper.getReg();
11717   t2 = dest2Oper.getReg();
11718
11719   int valArgIndx = lastAddrIndx + 1;
11720   assert((argOpers[valArgIndx]->isReg() ||
11721           argOpers[valArgIndx]->isImm()) &&
11722          "invalid operand");
11723   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11724   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11725   if (argOpers[valArgIndx]->isReg())
11726     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11727   else
11728     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11729   if (regOpcL != X86::MOV32rr)
11730     MIB.addReg(t1);
11731   (*MIB).addOperand(*argOpers[valArgIndx]);
11732   assert(argOpers[valArgIndx + 1]->isReg() ==
11733          argOpers[valArgIndx]->isReg());
11734   assert(argOpers[valArgIndx + 1]->isImm() ==
11735          argOpers[valArgIndx]->isImm());
11736   if (argOpers[valArgIndx + 1]->isReg())
11737     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11738   else
11739     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11740   if (regOpcH != X86::MOV32rr)
11741     MIB.addReg(t2);
11742   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11743
11744   unsigned t7, t8;
11745   if (Invert) {
11746     t7 = F->getRegInfo().createVirtualRegister(RC);
11747     t8 = F->getRegInfo().createVirtualRegister(RC);
11748     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11749     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11750   } else {
11751     t7 = t5;
11752     t8 = t6;
11753   }
11754
11755   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11756   MIB.addReg(t1);
11757   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11758   MIB.addReg(t2);
11759
11760   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11761   MIB.addReg(t7);
11762   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11763   MIB.addReg(t8);
11764
11765   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11766   for (int i=0; i <= lastAddrIndx; ++i)
11767     (*MIB).addOperand(*argOpers[i]);
11768
11769   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11770   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11771                     bInstr->memoperands_end());
11772
11773   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11774   MIB.addReg(X86::EAX);
11775   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11776   MIB.addReg(X86::EDX);
11777
11778   // insert branch
11779   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11780
11781   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11782   return nextMBB;
11783 }
11784
11785 // private utility function
11786 MachineBasicBlock *
11787 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11788                                                       MachineBasicBlock *MBB,
11789                                                       unsigned cmovOpc) const {
11790   // For the atomic min/max operator, we generate
11791   //   thisMBB:
11792   //   newMBB:
11793   //     ld t1 = [min/max.addr]
11794   //     mov t2 = [min/max.val]
11795   //     cmp  t1, t2
11796   //     cmov[cond] t2 = t1
11797   //     mov EAX = t1
11798   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11799   //     bz   newMBB
11800   //     fallthrough -->nextMBB
11801   //
11802   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11803   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11804   MachineFunction::iterator MBBIter = MBB;
11805   ++MBBIter;
11806
11807   /// First build the CFG
11808   MachineFunction *F = MBB->getParent();
11809   MachineBasicBlock *thisMBB = MBB;
11810   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11811   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11812   F->insert(MBBIter, newMBB);
11813   F->insert(MBBIter, nextMBB);
11814
11815   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11816   nextMBB->splice(nextMBB->begin(), thisMBB,
11817                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11818                   thisMBB->end());
11819   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11820
11821   // Update thisMBB to fall through to newMBB
11822   thisMBB->addSuccessor(newMBB);
11823
11824   // newMBB jumps to newMBB and fall through to nextMBB
11825   newMBB->addSuccessor(nextMBB);
11826   newMBB->addSuccessor(newMBB);
11827
11828   DebugLoc dl = mInstr->getDebugLoc();
11829   // Insert instructions into newMBB based on incoming instruction
11830   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11831          "unexpected number of operands");
11832   MachineOperand& destOper = mInstr->getOperand(0);
11833   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11834   int numArgs = mInstr->getNumOperands() - 1;
11835   for (int i=0; i < numArgs; ++i)
11836     argOpers[i] = &mInstr->getOperand(i+1);
11837
11838   // x86 address has 4 operands: base, index, scale, and displacement
11839   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11840   int valArgIndx = lastAddrIndx + 1;
11841
11842   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11843   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11844   for (int i=0; i <= lastAddrIndx; ++i)
11845     (*MIB).addOperand(*argOpers[i]);
11846
11847   // We only support register and immediate values
11848   assert((argOpers[valArgIndx]->isReg() ||
11849           argOpers[valArgIndx]->isImm()) &&
11850          "invalid operand");
11851
11852   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11853   if (argOpers[valArgIndx]->isReg())
11854     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11855   else
11856     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11857   (*MIB).addOperand(*argOpers[valArgIndx]);
11858
11859   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11860   MIB.addReg(t1);
11861
11862   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11863   MIB.addReg(t1);
11864   MIB.addReg(t2);
11865
11866   // Generate movc
11867   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11868   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11869   MIB.addReg(t2);
11870   MIB.addReg(t1);
11871
11872   // Cmp and exchange if none has modified the memory location
11873   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11874   for (int i=0; i <= lastAddrIndx; ++i)
11875     (*MIB).addOperand(*argOpers[i]);
11876   MIB.addReg(t3);
11877   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11878   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11879                     mInstr->memoperands_end());
11880
11881   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11882   MIB.addReg(X86::EAX);
11883
11884   // insert branch
11885   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11886
11887   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11888   return nextMBB;
11889 }
11890
11891 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11892 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11893 // in the .td file.
11894 MachineBasicBlock *
11895 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11896                             unsigned numArgs, bool memArg) const {
11897   assert(Subtarget->hasSSE42() &&
11898          "Target must have SSE4.2 or AVX features enabled");
11899
11900   DebugLoc dl = MI->getDebugLoc();
11901   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11902   unsigned Opc;
11903   if (!Subtarget->hasAVX()) {
11904     if (memArg)
11905       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11906     else
11907       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11908   } else {
11909     if (memArg)
11910       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11911     else
11912       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11913   }
11914
11915   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11916   for (unsigned i = 0; i < numArgs; ++i) {
11917     MachineOperand &Op = MI->getOperand(i+1);
11918     if (!(Op.isReg() && Op.isImplicit()))
11919       MIB.addOperand(Op);
11920   }
11921   BuildMI(*BB, MI, dl,
11922     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
11923     .addReg(X86::XMM0);
11924
11925   MI->eraseFromParent();
11926   return BB;
11927 }
11928
11929 MachineBasicBlock *
11930 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11931   DebugLoc dl = MI->getDebugLoc();
11932   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11933
11934   // Address into RAX/EAX, other two args into ECX, EDX.
11935   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11936   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11937   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11938   for (int i = 0; i < X86::AddrNumOperands; ++i)
11939     MIB.addOperand(MI->getOperand(i));
11940
11941   unsigned ValOps = X86::AddrNumOperands;
11942   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11943     .addReg(MI->getOperand(ValOps).getReg());
11944   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11945     .addReg(MI->getOperand(ValOps+1).getReg());
11946
11947   // The instruction doesn't actually take any operands though.
11948   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11949
11950   MI->eraseFromParent(); // The pseudo is gone now.
11951   return BB;
11952 }
11953
11954 MachineBasicBlock *
11955 X86TargetLowering::EmitVAARG64WithCustomInserter(
11956                    MachineInstr *MI,
11957                    MachineBasicBlock *MBB) const {
11958   // Emit va_arg instruction on X86-64.
11959
11960   // Operands to this pseudo-instruction:
11961   // 0  ) Output        : destination address (reg)
11962   // 1-5) Input         : va_list address (addr, i64mem)
11963   // 6  ) ArgSize       : Size (in bytes) of vararg type
11964   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11965   // 8  ) Align         : Alignment of type
11966   // 9  ) EFLAGS (implicit-def)
11967
11968   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11969   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11970
11971   unsigned DestReg = MI->getOperand(0).getReg();
11972   MachineOperand &Base = MI->getOperand(1);
11973   MachineOperand &Scale = MI->getOperand(2);
11974   MachineOperand &Index = MI->getOperand(3);
11975   MachineOperand &Disp = MI->getOperand(4);
11976   MachineOperand &Segment = MI->getOperand(5);
11977   unsigned ArgSize = MI->getOperand(6).getImm();
11978   unsigned ArgMode = MI->getOperand(7).getImm();
11979   unsigned Align = MI->getOperand(8).getImm();
11980
11981   // Memory Reference
11982   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11983   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11984   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11985
11986   // Machine Information
11987   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11988   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11989   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11990   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11991   DebugLoc DL = MI->getDebugLoc();
11992
11993   // struct va_list {
11994   //   i32   gp_offset
11995   //   i32   fp_offset
11996   //   i64   overflow_area (address)
11997   //   i64   reg_save_area (address)
11998   // }
11999   // sizeof(va_list) = 24
12000   // alignment(va_list) = 8
12001
12002   unsigned TotalNumIntRegs = 6;
12003   unsigned TotalNumXMMRegs = 8;
12004   bool UseGPOffset = (ArgMode == 1);
12005   bool UseFPOffset = (ArgMode == 2);
12006   unsigned MaxOffset = TotalNumIntRegs * 8 +
12007                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12008
12009   /* Align ArgSize to a multiple of 8 */
12010   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12011   bool NeedsAlign = (Align > 8);
12012
12013   MachineBasicBlock *thisMBB = MBB;
12014   MachineBasicBlock *overflowMBB;
12015   MachineBasicBlock *offsetMBB;
12016   MachineBasicBlock *endMBB;
12017
12018   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12019   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12020   unsigned OffsetReg = 0;
12021
12022   if (!UseGPOffset && !UseFPOffset) {
12023     // If we only pull from the overflow region, we don't create a branch.
12024     // We don't need to alter control flow.
12025     OffsetDestReg = 0; // unused
12026     OverflowDestReg = DestReg;
12027
12028     offsetMBB = NULL;
12029     overflowMBB = thisMBB;
12030     endMBB = thisMBB;
12031   } else {
12032     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12033     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12034     // If not, pull from overflow_area. (branch to overflowMBB)
12035     //
12036     //       thisMBB
12037     //         |     .
12038     //         |        .
12039     //     offsetMBB   overflowMBB
12040     //         |        .
12041     //         |     .
12042     //        endMBB
12043
12044     // Registers for the PHI in endMBB
12045     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12046     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12047
12048     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12049     MachineFunction *MF = MBB->getParent();
12050     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12051     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12052     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12053
12054     MachineFunction::iterator MBBIter = MBB;
12055     ++MBBIter;
12056
12057     // Insert the new basic blocks
12058     MF->insert(MBBIter, offsetMBB);
12059     MF->insert(MBBIter, overflowMBB);
12060     MF->insert(MBBIter, endMBB);
12061
12062     // Transfer the remainder of MBB and its successor edges to endMBB.
12063     endMBB->splice(endMBB->begin(), thisMBB,
12064                     llvm::next(MachineBasicBlock::iterator(MI)),
12065                     thisMBB->end());
12066     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12067
12068     // Make offsetMBB and overflowMBB successors of thisMBB
12069     thisMBB->addSuccessor(offsetMBB);
12070     thisMBB->addSuccessor(overflowMBB);
12071
12072     // endMBB is a successor of both offsetMBB and overflowMBB
12073     offsetMBB->addSuccessor(endMBB);
12074     overflowMBB->addSuccessor(endMBB);
12075
12076     // Load the offset value into a register
12077     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12078     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12079       .addOperand(Base)
12080       .addOperand(Scale)
12081       .addOperand(Index)
12082       .addDisp(Disp, UseFPOffset ? 4 : 0)
12083       .addOperand(Segment)
12084       .setMemRefs(MMOBegin, MMOEnd);
12085
12086     // Check if there is enough room left to pull this argument.
12087     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12088       .addReg(OffsetReg)
12089       .addImm(MaxOffset + 8 - ArgSizeA8);
12090
12091     // Branch to "overflowMBB" if offset >= max
12092     // Fall through to "offsetMBB" otherwise
12093     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12094       .addMBB(overflowMBB);
12095   }
12096
12097   // In offsetMBB, emit code to use the reg_save_area.
12098   if (offsetMBB) {
12099     assert(OffsetReg != 0);
12100
12101     // Read the reg_save_area address.
12102     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12103     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12104       .addOperand(Base)
12105       .addOperand(Scale)
12106       .addOperand(Index)
12107       .addDisp(Disp, 16)
12108       .addOperand(Segment)
12109       .setMemRefs(MMOBegin, MMOEnd);
12110
12111     // Zero-extend the offset
12112     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12113       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12114         .addImm(0)
12115         .addReg(OffsetReg)
12116         .addImm(X86::sub_32bit);
12117
12118     // Add the offset to the reg_save_area to get the final address.
12119     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12120       .addReg(OffsetReg64)
12121       .addReg(RegSaveReg);
12122
12123     // Compute the offset for the next argument
12124     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12125     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12126       .addReg(OffsetReg)
12127       .addImm(UseFPOffset ? 16 : 8);
12128
12129     // Store it back into the va_list.
12130     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12131       .addOperand(Base)
12132       .addOperand(Scale)
12133       .addOperand(Index)
12134       .addDisp(Disp, UseFPOffset ? 4 : 0)
12135       .addOperand(Segment)
12136       .addReg(NextOffsetReg)
12137       .setMemRefs(MMOBegin, MMOEnd);
12138
12139     // Jump to endMBB
12140     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12141       .addMBB(endMBB);
12142   }
12143
12144   //
12145   // Emit code to use overflow area
12146   //
12147
12148   // Load the overflow_area address into a register.
12149   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12150   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12151     .addOperand(Base)
12152     .addOperand(Scale)
12153     .addOperand(Index)
12154     .addDisp(Disp, 8)
12155     .addOperand(Segment)
12156     .setMemRefs(MMOBegin, MMOEnd);
12157
12158   // If we need to align it, do so. Otherwise, just copy the address
12159   // to OverflowDestReg.
12160   if (NeedsAlign) {
12161     // Align the overflow address
12162     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12163     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12164
12165     // aligned_addr = (addr + (align-1)) & ~(align-1)
12166     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12167       .addReg(OverflowAddrReg)
12168       .addImm(Align-1);
12169
12170     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12171       .addReg(TmpReg)
12172       .addImm(~(uint64_t)(Align-1));
12173   } else {
12174     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12175       .addReg(OverflowAddrReg);
12176   }
12177
12178   // Compute the next overflow address after this argument.
12179   // (the overflow address should be kept 8-byte aligned)
12180   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12181   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12182     .addReg(OverflowDestReg)
12183     .addImm(ArgSizeA8);
12184
12185   // Store the new overflow address.
12186   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12187     .addOperand(Base)
12188     .addOperand(Scale)
12189     .addOperand(Index)
12190     .addDisp(Disp, 8)
12191     .addOperand(Segment)
12192     .addReg(NextAddrReg)
12193     .setMemRefs(MMOBegin, MMOEnd);
12194
12195   // If we branched, emit the PHI to the front of endMBB.
12196   if (offsetMBB) {
12197     BuildMI(*endMBB, endMBB->begin(), DL,
12198             TII->get(X86::PHI), DestReg)
12199       .addReg(OffsetDestReg).addMBB(offsetMBB)
12200       .addReg(OverflowDestReg).addMBB(overflowMBB);
12201   }
12202
12203   // Erase the pseudo instruction
12204   MI->eraseFromParent();
12205
12206   return endMBB;
12207 }
12208
12209 MachineBasicBlock *
12210 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12211                                                  MachineInstr *MI,
12212                                                  MachineBasicBlock *MBB) const {
12213   // Emit code to save XMM registers to the stack. The ABI says that the
12214   // number of registers to save is given in %al, so it's theoretically
12215   // possible to do an indirect jump trick to avoid saving all of them,
12216   // however this code takes a simpler approach and just executes all
12217   // of the stores if %al is non-zero. It's less code, and it's probably
12218   // easier on the hardware branch predictor, and stores aren't all that
12219   // expensive anyway.
12220
12221   // Create the new basic blocks. One block contains all the XMM stores,
12222   // and one block is the final destination regardless of whether any
12223   // stores were performed.
12224   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12225   MachineFunction *F = MBB->getParent();
12226   MachineFunction::iterator MBBIter = MBB;
12227   ++MBBIter;
12228   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12229   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12230   F->insert(MBBIter, XMMSaveMBB);
12231   F->insert(MBBIter, EndMBB);
12232
12233   // Transfer the remainder of MBB and its successor edges to EndMBB.
12234   EndMBB->splice(EndMBB->begin(), MBB,
12235                  llvm::next(MachineBasicBlock::iterator(MI)),
12236                  MBB->end());
12237   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12238
12239   // The original block will now fall through to the XMM save block.
12240   MBB->addSuccessor(XMMSaveMBB);
12241   // The XMMSaveMBB will fall through to the end block.
12242   XMMSaveMBB->addSuccessor(EndMBB);
12243
12244   // Now add the instructions.
12245   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12246   DebugLoc DL = MI->getDebugLoc();
12247
12248   unsigned CountReg = MI->getOperand(0).getReg();
12249   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12250   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12251
12252   if (!Subtarget->isTargetWin64()) {
12253     // If %al is 0, branch around the XMM save block.
12254     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12255     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12256     MBB->addSuccessor(EndMBB);
12257   }
12258
12259   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12260   // In the XMM save block, save all the XMM argument registers.
12261   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12262     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12263     MachineMemOperand *MMO =
12264       F->getMachineMemOperand(
12265           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12266         MachineMemOperand::MOStore,
12267         /*Size=*/16, /*Align=*/16);
12268     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12269       .addFrameIndex(RegSaveFrameIndex)
12270       .addImm(/*Scale=*/1)
12271       .addReg(/*IndexReg=*/0)
12272       .addImm(/*Disp=*/Offset)
12273       .addReg(/*Segment=*/0)
12274       .addReg(MI->getOperand(i).getReg())
12275       .addMemOperand(MMO);
12276   }
12277
12278   MI->eraseFromParent();   // The pseudo instruction is gone now.
12279
12280   return EndMBB;
12281 }
12282
12283 // The EFLAGS operand of SelectItr might be missing a kill marker
12284 // because there were multiple uses of EFLAGS, and ISel didn't know
12285 // which to mark. Figure out whether SelectItr should have had a
12286 // kill marker, and set it if it should. Returns the correct kill
12287 // marker value.
12288 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12289                                      MachineBasicBlock* BB,
12290                                      const TargetRegisterInfo* TRI) {
12291   // Scan forward through BB for a use/def of EFLAGS.
12292   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12293   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12294     const MachineInstr& mi = *miI;
12295     if (mi.readsRegister(X86::EFLAGS))
12296       return false;
12297     if (mi.definesRegister(X86::EFLAGS))
12298       break; // Should have kill-flag - update below.
12299   }
12300
12301   // If we hit the end of the block, check whether EFLAGS is live into a
12302   // successor.
12303   if (miI == BB->end()) {
12304     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12305                                           sEnd = BB->succ_end();
12306          sItr != sEnd; ++sItr) {
12307       MachineBasicBlock* succ = *sItr;
12308       if (succ->isLiveIn(X86::EFLAGS))
12309         return false;
12310     }
12311   }
12312
12313   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12314   // out. SelectMI should have a kill flag on EFLAGS.
12315   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12316   return true;
12317 }
12318
12319 MachineBasicBlock *
12320 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12321                                      MachineBasicBlock *BB) const {
12322   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12323   DebugLoc DL = MI->getDebugLoc();
12324
12325   // To "insert" a SELECT_CC instruction, we actually have to insert the
12326   // diamond control-flow pattern.  The incoming instruction knows the
12327   // destination vreg to set, the condition code register to branch on, the
12328   // true/false values to select between, and a branch opcode to use.
12329   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12330   MachineFunction::iterator It = BB;
12331   ++It;
12332
12333   //  thisMBB:
12334   //  ...
12335   //   TrueVal = ...
12336   //   cmpTY ccX, r1, r2
12337   //   bCC copy1MBB
12338   //   fallthrough --> copy0MBB
12339   MachineBasicBlock *thisMBB = BB;
12340   MachineFunction *F = BB->getParent();
12341   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12342   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12343   F->insert(It, copy0MBB);
12344   F->insert(It, sinkMBB);
12345
12346   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12347   // live into the sink and copy blocks.
12348   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12349   if (!MI->killsRegister(X86::EFLAGS) &&
12350       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12351     copy0MBB->addLiveIn(X86::EFLAGS);
12352     sinkMBB->addLiveIn(X86::EFLAGS);
12353   }
12354
12355   // Transfer the remainder of BB and its successor edges to sinkMBB.
12356   sinkMBB->splice(sinkMBB->begin(), BB,
12357                   llvm::next(MachineBasicBlock::iterator(MI)),
12358                   BB->end());
12359   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12360
12361   // Add the true and fallthrough blocks as its successors.
12362   BB->addSuccessor(copy0MBB);
12363   BB->addSuccessor(sinkMBB);
12364
12365   // Create the conditional branch instruction.
12366   unsigned Opc =
12367     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12368   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12369
12370   //  copy0MBB:
12371   //   %FalseValue = ...
12372   //   # fallthrough to sinkMBB
12373   copy0MBB->addSuccessor(sinkMBB);
12374
12375   //  sinkMBB:
12376   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12377   //  ...
12378   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12379           TII->get(X86::PHI), MI->getOperand(0).getReg())
12380     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12381     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12382
12383   MI->eraseFromParent();   // The pseudo instruction is gone now.
12384   return sinkMBB;
12385 }
12386
12387 MachineBasicBlock *
12388 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12389                                         bool Is64Bit) const {
12390   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12391   DebugLoc DL = MI->getDebugLoc();
12392   MachineFunction *MF = BB->getParent();
12393   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12394
12395   assert(getTargetMachine().Options.EnableSegmentedStacks);
12396
12397   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12398   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12399
12400   // BB:
12401   //  ... [Till the alloca]
12402   // If stacklet is not large enough, jump to mallocMBB
12403   //
12404   // bumpMBB:
12405   //  Allocate by subtracting from RSP
12406   //  Jump to continueMBB
12407   //
12408   // mallocMBB:
12409   //  Allocate by call to runtime
12410   //
12411   // continueMBB:
12412   //  ...
12413   //  [rest of original BB]
12414   //
12415
12416   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12417   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12418   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12419
12420   MachineRegisterInfo &MRI = MF->getRegInfo();
12421   const TargetRegisterClass *AddrRegClass =
12422     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12423
12424   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12425     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12426     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12427     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12428     sizeVReg = MI->getOperand(1).getReg(),
12429     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12430
12431   MachineFunction::iterator MBBIter = BB;
12432   ++MBBIter;
12433
12434   MF->insert(MBBIter, bumpMBB);
12435   MF->insert(MBBIter, mallocMBB);
12436   MF->insert(MBBIter, continueMBB);
12437
12438   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12439                       (MachineBasicBlock::iterator(MI)), BB->end());
12440   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12441
12442   // Add code to the main basic block to check if the stack limit has been hit,
12443   // and if so, jump to mallocMBB otherwise to bumpMBB.
12444   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12445   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12446     .addReg(tmpSPVReg).addReg(sizeVReg);
12447   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12448     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12449     .addReg(SPLimitVReg);
12450   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12451
12452   // bumpMBB simply decreases the stack pointer, since we know the current
12453   // stacklet has enough space.
12454   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12455     .addReg(SPLimitVReg);
12456   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12457     .addReg(SPLimitVReg);
12458   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12459
12460   // Calls into a routine in libgcc to allocate more space from the heap.
12461   const uint32_t *RegMask =
12462     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12463   if (Is64Bit) {
12464     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12465       .addReg(sizeVReg);
12466     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12467       .addExternalSymbol("__morestack_allocate_stack_space")
12468       .addRegMask(RegMask)
12469       .addReg(X86::RDI, RegState::Implicit)
12470       .addReg(X86::RAX, RegState::ImplicitDefine);
12471   } else {
12472     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12473       .addImm(12);
12474     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12475     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12476       .addExternalSymbol("__morestack_allocate_stack_space")
12477       .addRegMask(RegMask)
12478       .addReg(X86::EAX, RegState::ImplicitDefine);
12479   }
12480
12481   if (!Is64Bit)
12482     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12483       .addImm(16);
12484
12485   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12486     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12487   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12488
12489   // Set up the CFG correctly.
12490   BB->addSuccessor(bumpMBB);
12491   BB->addSuccessor(mallocMBB);
12492   mallocMBB->addSuccessor(continueMBB);
12493   bumpMBB->addSuccessor(continueMBB);
12494
12495   // Take care of the PHI nodes.
12496   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12497           MI->getOperand(0).getReg())
12498     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12499     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12500
12501   // Delete the original pseudo instruction.
12502   MI->eraseFromParent();
12503
12504   // And we're done.
12505   return continueMBB;
12506 }
12507
12508 MachineBasicBlock *
12509 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12510                                           MachineBasicBlock *BB) const {
12511   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12512   DebugLoc DL = MI->getDebugLoc();
12513
12514   assert(!Subtarget->isTargetEnvMacho());
12515
12516   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12517   // non-trivial part is impdef of ESP.
12518
12519   if (Subtarget->isTargetWin64()) {
12520     if (Subtarget->isTargetCygMing()) {
12521       // ___chkstk(Mingw64):
12522       // Clobbers R10, R11, RAX and EFLAGS.
12523       // Updates RSP.
12524       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12525         .addExternalSymbol("___chkstk")
12526         .addReg(X86::RAX, RegState::Implicit)
12527         .addReg(X86::RSP, RegState::Implicit)
12528         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12529         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12530         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12531     } else {
12532       // __chkstk(MSVCRT): does not update stack pointer.
12533       // Clobbers R10, R11 and EFLAGS.
12534       // FIXME: RAX(allocated size) might be reused and not killed.
12535       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12536         .addExternalSymbol("__chkstk")
12537         .addReg(X86::RAX, RegState::Implicit)
12538         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12539       // RAX has the offset to subtracted from RSP.
12540       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12541         .addReg(X86::RSP)
12542         .addReg(X86::RAX);
12543     }
12544   } else {
12545     const char *StackProbeSymbol =
12546       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12547
12548     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12549       .addExternalSymbol(StackProbeSymbol)
12550       .addReg(X86::EAX, RegState::Implicit)
12551       .addReg(X86::ESP, RegState::Implicit)
12552       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12553       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12554       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12555   }
12556
12557   MI->eraseFromParent();   // The pseudo instruction is gone now.
12558   return BB;
12559 }
12560
12561 MachineBasicBlock *
12562 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12563                                       MachineBasicBlock *BB) const {
12564   // This is pretty easy.  We're taking the value that we received from
12565   // our load from the relocation, sticking it in either RDI (x86-64)
12566   // or EAX and doing an indirect call.  The return value will then
12567   // be in the normal return register.
12568   const X86InstrInfo *TII
12569     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12570   DebugLoc DL = MI->getDebugLoc();
12571   MachineFunction *F = BB->getParent();
12572
12573   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12574   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12575
12576   // Get a register mask for the lowered call.
12577   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12578   // proper register mask.
12579   const uint32_t *RegMask =
12580     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12581   if (Subtarget->is64Bit()) {
12582     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12583                                       TII->get(X86::MOV64rm), X86::RDI)
12584     .addReg(X86::RIP)
12585     .addImm(0).addReg(0)
12586     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12587                       MI->getOperand(3).getTargetFlags())
12588     .addReg(0);
12589     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12590     addDirectMem(MIB, X86::RDI);
12591     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12592   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12593     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12594                                       TII->get(X86::MOV32rm), X86::EAX)
12595     .addReg(0)
12596     .addImm(0).addReg(0)
12597     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12598                       MI->getOperand(3).getTargetFlags())
12599     .addReg(0);
12600     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12601     addDirectMem(MIB, X86::EAX);
12602     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12603   } else {
12604     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12605                                       TII->get(X86::MOV32rm), X86::EAX)
12606     .addReg(TII->getGlobalBaseReg(F))
12607     .addImm(0).addReg(0)
12608     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12609                       MI->getOperand(3).getTargetFlags())
12610     .addReg(0);
12611     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12612     addDirectMem(MIB, X86::EAX);
12613     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12614   }
12615
12616   MI->eraseFromParent(); // The pseudo instruction is gone now.
12617   return BB;
12618 }
12619
12620 MachineBasicBlock *
12621 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12622                                                MachineBasicBlock *BB) const {
12623   switch (MI->getOpcode()) {
12624   default: llvm_unreachable("Unexpected instr type to insert");
12625   case X86::TAILJMPd64:
12626   case X86::TAILJMPr64:
12627   case X86::TAILJMPm64:
12628     llvm_unreachable("TAILJMP64 would not be touched here.");
12629   case X86::TCRETURNdi64:
12630   case X86::TCRETURNri64:
12631   case X86::TCRETURNmi64:
12632     return BB;
12633   case X86::WIN_ALLOCA:
12634     return EmitLoweredWinAlloca(MI, BB);
12635   case X86::SEG_ALLOCA_32:
12636     return EmitLoweredSegAlloca(MI, BB, false);
12637   case X86::SEG_ALLOCA_64:
12638     return EmitLoweredSegAlloca(MI, BB, true);
12639   case X86::TLSCall_32:
12640   case X86::TLSCall_64:
12641     return EmitLoweredTLSCall(MI, BB);
12642   case X86::CMOV_GR8:
12643   case X86::CMOV_FR32:
12644   case X86::CMOV_FR64:
12645   case X86::CMOV_V4F32:
12646   case X86::CMOV_V2F64:
12647   case X86::CMOV_V2I64:
12648   case X86::CMOV_V8F32:
12649   case X86::CMOV_V4F64:
12650   case X86::CMOV_V4I64:
12651   case X86::CMOV_GR16:
12652   case X86::CMOV_GR32:
12653   case X86::CMOV_RFP32:
12654   case X86::CMOV_RFP64:
12655   case X86::CMOV_RFP80:
12656     return EmitLoweredSelect(MI, BB);
12657
12658   case X86::FP32_TO_INT16_IN_MEM:
12659   case X86::FP32_TO_INT32_IN_MEM:
12660   case X86::FP32_TO_INT64_IN_MEM:
12661   case X86::FP64_TO_INT16_IN_MEM:
12662   case X86::FP64_TO_INT32_IN_MEM:
12663   case X86::FP64_TO_INT64_IN_MEM:
12664   case X86::FP80_TO_INT16_IN_MEM:
12665   case X86::FP80_TO_INT32_IN_MEM:
12666   case X86::FP80_TO_INT64_IN_MEM: {
12667     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12668     DebugLoc DL = MI->getDebugLoc();
12669
12670     // Change the floating point control register to use "round towards zero"
12671     // mode when truncating to an integer value.
12672     MachineFunction *F = BB->getParent();
12673     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12674     addFrameReference(BuildMI(*BB, MI, DL,
12675                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12676
12677     // Load the old value of the high byte of the control word...
12678     unsigned OldCW =
12679       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12680     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12681                       CWFrameIdx);
12682
12683     // Set the high part to be round to zero...
12684     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12685       .addImm(0xC7F);
12686
12687     // Reload the modified control word now...
12688     addFrameReference(BuildMI(*BB, MI, DL,
12689                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12690
12691     // Restore the memory image of control word to original value
12692     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12693       .addReg(OldCW);
12694
12695     // Get the X86 opcode to use.
12696     unsigned Opc;
12697     switch (MI->getOpcode()) {
12698     default: llvm_unreachable("illegal opcode!");
12699     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12700     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12701     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12702     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12703     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12704     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12705     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12706     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12707     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12708     }
12709
12710     X86AddressMode AM;
12711     MachineOperand &Op = MI->getOperand(0);
12712     if (Op.isReg()) {
12713       AM.BaseType = X86AddressMode::RegBase;
12714       AM.Base.Reg = Op.getReg();
12715     } else {
12716       AM.BaseType = X86AddressMode::FrameIndexBase;
12717       AM.Base.FrameIndex = Op.getIndex();
12718     }
12719     Op = MI->getOperand(1);
12720     if (Op.isImm())
12721       AM.Scale = Op.getImm();
12722     Op = MI->getOperand(2);
12723     if (Op.isImm())
12724       AM.IndexReg = Op.getImm();
12725     Op = MI->getOperand(3);
12726     if (Op.isGlobal()) {
12727       AM.GV = Op.getGlobal();
12728     } else {
12729       AM.Disp = Op.getImm();
12730     }
12731     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12732                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12733
12734     // Reload the original control word now.
12735     addFrameReference(BuildMI(*BB, MI, DL,
12736                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12737
12738     MI->eraseFromParent();   // The pseudo instruction is gone now.
12739     return BB;
12740   }
12741     // String/text processing lowering.
12742   case X86::PCMPISTRM128REG:
12743   case X86::VPCMPISTRM128REG:
12744     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12745   case X86::PCMPISTRM128MEM:
12746   case X86::VPCMPISTRM128MEM:
12747     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12748   case X86::PCMPESTRM128REG:
12749   case X86::VPCMPESTRM128REG:
12750     return EmitPCMP(MI, BB, 5, false /* in mem */);
12751   case X86::PCMPESTRM128MEM:
12752   case X86::VPCMPESTRM128MEM:
12753     return EmitPCMP(MI, BB, 5, true /* in mem */);
12754
12755     // Thread synchronization.
12756   case X86::MONITOR:
12757     return EmitMonitor(MI, BB);
12758
12759     // Atomic Lowering.
12760   case X86::ATOMAND32:
12761     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12762                                                X86::AND32ri, X86::MOV32rm,
12763                                                X86::LCMPXCHG32,
12764                                                X86::NOT32r, X86::EAX,
12765                                                &X86::GR32RegClass);
12766   case X86::ATOMOR32:
12767     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12768                                                X86::OR32ri, X86::MOV32rm,
12769                                                X86::LCMPXCHG32,
12770                                                X86::NOT32r, X86::EAX,
12771                                                &X86::GR32RegClass);
12772   case X86::ATOMXOR32:
12773     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12774                                                X86::XOR32ri, X86::MOV32rm,
12775                                                X86::LCMPXCHG32,
12776                                                X86::NOT32r, X86::EAX,
12777                                                &X86::GR32RegClass);
12778   case X86::ATOMNAND32:
12779     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12780                                                X86::AND32ri, X86::MOV32rm,
12781                                                X86::LCMPXCHG32,
12782                                                X86::NOT32r, X86::EAX,
12783                                                &X86::GR32RegClass, true);
12784   case X86::ATOMMIN32:
12785     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12786   case X86::ATOMMAX32:
12787     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12788   case X86::ATOMUMIN32:
12789     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12790   case X86::ATOMUMAX32:
12791     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12792
12793   case X86::ATOMAND16:
12794     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12795                                                X86::AND16ri, X86::MOV16rm,
12796                                                X86::LCMPXCHG16,
12797                                                X86::NOT16r, X86::AX,
12798                                                &X86::GR16RegClass);
12799   case X86::ATOMOR16:
12800     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12801                                                X86::OR16ri, X86::MOV16rm,
12802                                                X86::LCMPXCHG16,
12803                                                X86::NOT16r, X86::AX,
12804                                                &X86::GR16RegClass);
12805   case X86::ATOMXOR16:
12806     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12807                                                X86::XOR16ri, X86::MOV16rm,
12808                                                X86::LCMPXCHG16,
12809                                                X86::NOT16r, X86::AX,
12810                                                &X86::GR16RegClass);
12811   case X86::ATOMNAND16:
12812     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12813                                                X86::AND16ri, X86::MOV16rm,
12814                                                X86::LCMPXCHG16,
12815                                                X86::NOT16r, X86::AX,
12816                                                &X86::GR16RegClass, true);
12817   case X86::ATOMMIN16:
12818     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12819   case X86::ATOMMAX16:
12820     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12821   case X86::ATOMUMIN16:
12822     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12823   case X86::ATOMUMAX16:
12824     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12825
12826   case X86::ATOMAND8:
12827     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12828                                                X86::AND8ri, X86::MOV8rm,
12829                                                X86::LCMPXCHG8,
12830                                                X86::NOT8r, X86::AL,
12831                                                &X86::GR8RegClass);
12832   case X86::ATOMOR8:
12833     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12834                                                X86::OR8ri, X86::MOV8rm,
12835                                                X86::LCMPXCHG8,
12836                                                X86::NOT8r, X86::AL,
12837                                                &X86::GR8RegClass);
12838   case X86::ATOMXOR8:
12839     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12840                                                X86::XOR8ri, X86::MOV8rm,
12841                                                X86::LCMPXCHG8,
12842                                                X86::NOT8r, X86::AL,
12843                                                &X86::GR8RegClass);
12844   case X86::ATOMNAND8:
12845     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12846                                                X86::AND8ri, X86::MOV8rm,
12847                                                X86::LCMPXCHG8,
12848                                                X86::NOT8r, X86::AL,
12849                                                &X86::GR8RegClass, true);
12850   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12851   // This group is for 64-bit host.
12852   case X86::ATOMAND64:
12853     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12854                                                X86::AND64ri32, X86::MOV64rm,
12855                                                X86::LCMPXCHG64,
12856                                                X86::NOT64r, X86::RAX,
12857                                                &X86::GR64RegClass);
12858   case X86::ATOMOR64:
12859     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12860                                                X86::OR64ri32, X86::MOV64rm,
12861                                                X86::LCMPXCHG64,
12862                                                X86::NOT64r, X86::RAX,
12863                                                &X86::GR64RegClass);
12864   case X86::ATOMXOR64:
12865     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12866                                                X86::XOR64ri32, X86::MOV64rm,
12867                                                X86::LCMPXCHG64,
12868                                                X86::NOT64r, X86::RAX,
12869                                                &X86::GR64RegClass);
12870   case X86::ATOMNAND64:
12871     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12872                                                X86::AND64ri32, X86::MOV64rm,
12873                                                X86::LCMPXCHG64,
12874                                                X86::NOT64r, X86::RAX,
12875                                                &X86::GR64RegClass, true);
12876   case X86::ATOMMIN64:
12877     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12878   case X86::ATOMMAX64:
12879     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12880   case X86::ATOMUMIN64:
12881     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12882   case X86::ATOMUMAX64:
12883     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12884
12885   // This group does 64-bit operations on a 32-bit host.
12886   case X86::ATOMAND6432:
12887     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12888                                                X86::AND32rr, X86::AND32rr,
12889                                                X86::AND32ri, X86::AND32ri,
12890                                                false);
12891   case X86::ATOMOR6432:
12892     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12893                                                X86::OR32rr, X86::OR32rr,
12894                                                X86::OR32ri, X86::OR32ri,
12895                                                false);
12896   case X86::ATOMXOR6432:
12897     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12898                                                X86::XOR32rr, X86::XOR32rr,
12899                                                X86::XOR32ri, X86::XOR32ri,
12900                                                false);
12901   case X86::ATOMNAND6432:
12902     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12903                                                X86::AND32rr, X86::AND32rr,
12904                                                X86::AND32ri, X86::AND32ri,
12905                                                true);
12906   case X86::ATOMADD6432:
12907     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12908                                                X86::ADD32rr, X86::ADC32rr,
12909                                                X86::ADD32ri, X86::ADC32ri,
12910                                                false);
12911   case X86::ATOMSUB6432:
12912     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12913                                                X86::SUB32rr, X86::SBB32rr,
12914                                                X86::SUB32ri, X86::SBB32ri,
12915                                                false);
12916   case X86::ATOMSWAP6432:
12917     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12918                                                X86::MOV32rr, X86::MOV32rr,
12919                                                X86::MOV32ri, X86::MOV32ri,
12920                                                false);
12921   case X86::VASTART_SAVE_XMM_REGS:
12922     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12923
12924   case X86::VAARG_64:
12925     return EmitVAARG64WithCustomInserter(MI, BB);
12926   }
12927 }
12928
12929 //===----------------------------------------------------------------------===//
12930 //                           X86 Optimization Hooks
12931 //===----------------------------------------------------------------------===//
12932
12933 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12934                                                        APInt &KnownZero,
12935                                                        APInt &KnownOne,
12936                                                        const SelectionDAG &DAG,
12937                                                        unsigned Depth) const {
12938   unsigned BitWidth = KnownZero.getBitWidth();
12939   unsigned Opc = Op.getOpcode();
12940   assert((Opc >= ISD::BUILTIN_OP_END ||
12941           Opc == ISD::INTRINSIC_WO_CHAIN ||
12942           Opc == ISD::INTRINSIC_W_CHAIN ||
12943           Opc == ISD::INTRINSIC_VOID) &&
12944          "Should use MaskedValueIsZero if you don't know whether Op"
12945          " is a target node!");
12946
12947   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12948   switch (Opc) {
12949   default: break;
12950   case X86ISD::ADD:
12951   case X86ISD::SUB:
12952   case X86ISD::ADC:
12953   case X86ISD::SBB:
12954   case X86ISD::SMUL:
12955   case X86ISD::UMUL:
12956   case X86ISD::INC:
12957   case X86ISD::DEC:
12958   case X86ISD::OR:
12959   case X86ISD::XOR:
12960   case X86ISD::AND:
12961     // These nodes' second result is a boolean.
12962     if (Op.getResNo() == 0)
12963       break;
12964     // Fallthrough
12965   case X86ISD::SETCC:
12966     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12967     break;
12968   case ISD::INTRINSIC_WO_CHAIN: {
12969     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12970     unsigned NumLoBits = 0;
12971     switch (IntId) {
12972     default: break;
12973     case Intrinsic::x86_sse_movmsk_ps:
12974     case Intrinsic::x86_avx_movmsk_ps_256:
12975     case Intrinsic::x86_sse2_movmsk_pd:
12976     case Intrinsic::x86_avx_movmsk_pd_256:
12977     case Intrinsic::x86_mmx_pmovmskb:
12978     case Intrinsic::x86_sse2_pmovmskb_128:
12979     case Intrinsic::x86_avx2_pmovmskb: {
12980       // High bits of movmskp{s|d}, pmovmskb are known zero.
12981       switch (IntId) {
12982         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12983         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12984         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12985         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12986         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12987         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12988         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12989         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12990       }
12991       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12992       break;
12993     }
12994     }
12995     break;
12996   }
12997   }
12998 }
12999
13000 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13001                                                          unsigned Depth) const {
13002   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13003   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13004     return Op.getValueType().getScalarType().getSizeInBits();
13005
13006   // Fallback case.
13007   return 1;
13008 }
13009
13010 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13011 /// node is a GlobalAddress + offset.
13012 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13013                                        const GlobalValue* &GA,
13014                                        int64_t &Offset) const {
13015   if (N->getOpcode() == X86ISD::Wrapper) {
13016     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13017       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13018       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13019       return true;
13020     }
13021   }
13022   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13023 }
13024
13025 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13026 /// same as extracting the high 128-bit part of 256-bit vector and then
13027 /// inserting the result into the low part of a new 256-bit vector
13028 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13029   EVT VT = SVOp->getValueType(0);
13030   unsigned NumElems = VT.getVectorNumElements();
13031
13032   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13033   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13034     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13035         SVOp->getMaskElt(j) >= 0)
13036       return false;
13037
13038   return true;
13039 }
13040
13041 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13042 /// same as extracting the low 128-bit part of 256-bit vector and then
13043 /// inserting the result into the high part of a new 256-bit vector
13044 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13045   EVT VT = SVOp->getValueType(0);
13046   unsigned NumElems = VT.getVectorNumElements();
13047
13048   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13049   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13050     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13051         SVOp->getMaskElt(j) >= 0)
13052       return false;
13053
13054   return true;
13055 }
13056
13057 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13058 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13059                                         TargetLowering::DAGCombinerInfo &DCI,
13060                                         const X86Subtarget* Subtarget) {
13061   DebugLoc dl = N->getDebugLoc();
13062   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13063   SDValue V1 = SVOp->getOperand(0);
13064   SDValue V2 = SVOp->getOperand(1);
13065   EVT VT = SVOp->getValueType(0);
13066   unsigned NumElems = VT.getVectorNumElements();
13067
13068   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13069       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13070     //
13071     //                   0,0,0,...
13072     //                      |
13073     //    V      UNDEF    BUILD_VECTOR    UNDEF
13074     //     \      /           \           /
13075     //  CONCAT_VECTOR         CONCAT_VECTOR
13076     //         \                  /
13077     //          \                /
13078     //          RESULT: V + zero extended
13079     //
13080     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13081         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13082         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13083       return SDValue();
13084
13085     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13086       return SDValue();
13087
13088     // To match the shuffle mask, the first half of the mask should
13089     // be exactly the first vector, and all the rest a splat with the
13090     // first element of the second one.
13091     for (unsigned i = 0; i != NumElems/2; ++i)
13092       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13093           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13094         return SDValue();
13095
13096     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13097     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13098       if (Ld->hasNUsesOfValue(1, 0)) {
13099         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13100         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13101         SDValue ResNode =
13102           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13103                                   Ld->getMemoryVT(),
13104                                   Ld->getPointerInfo(),
13105                                   Ld->getAlignment(),
13106                                   false/*isVolatile*/, true/*ReadMem*/,
13107                                   false/*WriteMem*/);
13108         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13109       }
13110     }
13111
13112     // Emit a zeroed vector and insert the desired subvector on its
13113     // first half.
13114     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13115     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13116     return DCI.CombineTo(N, InsV);
13117   }
13118
13119   //===--------------------------------------------------------------------===//
13120   // Combine some shuffles into subvector extracts and inserts:
13121   //
13122
13123   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13124   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13125     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13126     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13127     return DCI.CombineTo(N, InsV);
13128   }
13129
13130   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13131   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13132     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13133     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13134     return DCI.CombineTo(N, InsV);
13135   }
13136
13137   return SDValue();
13138 }
13139
13140 /// PerformShuffleCombine - Performs several different shuffle combines.
13141 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13142                                      TargetLowering::DAGCombinerInfo &DCI,
13143                                      const X86Subtarget *Subtarget) {
13144   DebugLoc dl = N->getDebugLoc();
13145   EVT VT = N->getValueType(0);
13146
13147   // Don't create instructions with illegal types after legalize types has run.
13148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13149   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13150     return SDValue();
13151
13152   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13153   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13154       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13155     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13156
13157   // Only handle 128 wide vector from here on.
13158   if (VT.getSizeInBits() != 128)
13159     return SDValue();
13160
13161   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13162   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13163   // consecutive, non-overlapping, and in the right order.
13164   SmallVector<SDValue, 16> Elts;
13165   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13166     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13167
13168   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13169 }
13170
13171
13172 /// DCI, PerformTruncateCombine - Converts truncate operation to
13173 /// a sequence of vector shuffle operations.
13174 /// It is possible when we truncate 256-bit vector to 128-bit vector
13175
13176 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13177                                                   DAGCombinerInfo &DCI) const {
13178   if (!DCI.isBeforeLegalizeOps())
13179     return SDValue();
13180
13181   if (!Subtarget->hasAVX())
13182     return SDValue();
13183
13184   EVT VT = N->getValueType(0);
13185   SDValue Op = N->getOperand(0);
13186   EVT OpVT = Op.getValueType();
13187   DebugLoc dl = N->getDebugLoc();
13188
13189   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13190
13191     if (Subtarget->hasAVX2()) {
13192       // AVX2: v4i64 -> v4i32
13193
13194       // VPERMD
13195       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13196
13197       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13198       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13199                                 ShufMask);
13200
13201       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13202                          DAG.getIntPtrConstant(0));
13203     }
13204
13205     // AVX: v4i64 -> v4i32
13206     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13207                                DAG.getIntPtrConstant(0));
13208
13209     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13210                                DAG.getIntPtrConstant(2));
13211
13212     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13213     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13214
13215     // PSHUFD
13216     static const int ShufMask1[] = {0, 2, 0, 0};
13217
13218     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13219     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13220
13221     // MOVLHPS
13222     static const int ShufMask2[] = {0, 1, 4, 5};
13223
13224     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13225   }
13226
13227   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13228
13229     if (Subtarget->hasAVX2()) {
13230       // AVX2: v8i32 -> v8i16
13231
13232       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13233
13234       // PSHUFB
13235       SmallVector<SDValue,32> pshufbMask;
13236       for (unsigned i = 0; i < 2; ++i) {
13237         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13238         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13239         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13240         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13241         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13242         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13243         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13244         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13245         for (unsigned j = 0; j < 8; ++j)
13246           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13247       }
13248       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13249                                &pshufbMask[0], 32);
13250       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13251
13252       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13253
13254       static const int ShufMask[] = {0,  2,  -1,  -1};
13255       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13256                                 &ShufMask[0]);
13257
13258       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13259                        DAG.getIntPtrConstant(0));
13260
13261       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13262     }
13263
13264     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13265                                DAG.getIntPtrConstant(0));
13266
13267     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13268                                DAG.getIntPtrConstant(4));
13269
13270     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13271     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13272
13273     // PSHUFB
13274     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13275                                    -1, -1, -1, -1, -1, -1, -1, -1};
13276
13277     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13278                                 ShufMask1);
13279     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13280                                 ShufMask1);
13281
13282     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13283     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13284
13285     // MOVLHPS
13286     static const int ShufMask2[] = {0, 1, 4, 5};
13287
13288     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13289     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13290   }
13291
13292   return SDValue();
13293 }
13294
13295 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13296 /// specific shuffle of a load can be folded into a single element load.
13297 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13298 /// shuffles have been customed lowered so we need to handle those here.
13299 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13300                                          TargetLowering::DAGCombinerInfo &DCI) {
13301   if (DCI.isBeforeLegalizeOps())
13302     return SDValue();
13303
13304   SDValue InVec = N->getOperand(0);
13305   SDValue EltNo = N->getOperand(1);
13306
13307   if (!isa<ConstantSDNode>(EltNo))
13308     return SDValue();
13309
13310   EVT VT = InVec.getValueType();
13311
13312   bool HasShuffleIntoBitcast = false;
13313   if (InVec.getOpcode() == ISD::BITCAST) {
13314     // Don't duplicate a load with other uses.
13315     if (!InVec.hasOneUse())
13316       return SDValue();
13317     EVT BCVT = InVec.getOperand(0).getValueType();
13318     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13319       return SDValue();
13320     InVec = InVec.getOperand(0);
13321     HasShuffleIntoBitcast = true;
13322   }
13323
13324   if (!isTargetShuffle(InVec.getOpcode()))
13325     return SDValue();
13326
13327   // Don't duplicate a load with other uses.
13328   if (!InVec.hasOneUse())
13329     return SDValue();
13330
13331   SmallVector<int, 16> ShuffleMask;
13332   bool UnaryShuffle;
13333   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13334                             UnaryShuffle))
13335     return SDValue();
13336
13337   // Select the input vector, guarding against out of range extract vector.
13338   unsigned NumElems = VT.getVectorNumElements();
13339   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13340   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13341   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13342                                          : InVec.getOperand(1);
13343
13344   // If inputs to shuffle are the same for both ops, then allow 2 uses
13345   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13346
13347   if (LdNode.getOpcode() == ISD::BITCAST) {
13348     // Don't duplicate a load with other uses.
13349     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13350       return SDValue();
13351
13352     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13353     LdNode = LdNode.getOperand(0);
13354   }
13355
13356   if (!ISD::isNormalLoad(LdNode.getNode()))
13357     return SDValue();
13358
13359   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13360
13361   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13362     return SDValue();
13363
13364   if (HasShuffleIntoBitcast) {
13365     // If there's a bitcast before the shuffle, check if the load type and
13366     // alignment is valid.
13367     unsigned Align = LN0->getAlignment();
13368     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13369     unsigned NewAlign = TLI.getTargetData()->
13370       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13371
13372     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13373       return SDValue();
13374   }
13375
13376   // All checks match so transform back to vector_shuffle so that DAG combiner
13377   // can finish the job
13378   DebugLoc dl = N->getDebugLoc();
13379
13380   // Create shuffle node taking into account the case that its a unary shuffle
13381   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13382   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13383                                  InVec.getOperand(0), Shuffle,
13384                                  &ShuffleMask[0]);
13385   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13386   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13387                      EltNo);
13388 }
13389
13390 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13391 /// generation and convert it from being a bunch of shuffles and extracts
13392 /// to a simple store and scalar loads to extract the elements.
13393 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13394                                          TargetLowering::DAGCombinerInfo &DCI) {
13395   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13396   if (NewOp.getNode())
13397     return NewOp;
13398
13399   SDValue InputVector = N->getOperand(0);
13400
13401   // Only operate on vectors of 4 elements, where the alternative shuffling
13402   // gets to be more expensive.
13403   if (InputVector.getValueType() != MVT::v4i32)
13404     return SDValue();
13405
13406   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13407   // single use which is a sign-extend or zero-extend, and all elements are
13408   // used.
13409   SmallVector<SDNode *, 4> Uses;
13410   unsigned ExtractedElements = 0;
13411   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13412        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13413     if (UI.getUse().getResNo() != InputVector.getResNo())
13414       return SDValue();
13415
13416     SDNode *Extract = *UI;
13417     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13418       return SDValue();
13419
13420     if (Extract->getValueType(0) != MVT::i32)
13421       return SDValue();
13422     if (!Extract->hasOneUse())
13423       return SDValue();
13424     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13425         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13426       return SDValue();
13427     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13428       return SDValue();
13429
13430     // Record which element was extracted.
13431     ExtractedElements |=
13432       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13433
13434     Uses.push_back(Extract);
13435   }
13436
13437   // If not all the elements were used, this may not be worthwhile.
13438   if (ExtractedElements != 15)
13439     return SDValue();
13440
13441   // Ok, we've now decided to do the transformation.
13442   DebugLoc dl = InputVector.getDebugLoc();
13443
13444   // Store the value to a temporary stack slot.
13445   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13446   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13447                             MachinePointerInfo(), false, false, 0);
13448
13449   // Replace each use (extract) with a load of the appropriate element.
13450   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13451        UE = Uses.end(); UI != UE; ++UI) {
13452     SDNode *Extract = *UI;
13453
13454     // cOMpute the element's address.
13455     SDValue Idx = Extract->getOperand(1);
13456     unsigned EltSize =
13457         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13458     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13459     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13460     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13461
13462     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13463                                      StackPtr, OffsetVal);
13464
13465     // Load the scalar.
13466     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13467                                      ScalarAddr, MachinePointerInfo(),
13468                                      false, false, false, 0);
13469
13470     // Replace the exact with the load.
13471     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13472   }
13473
13474   // The replacement was made in place; don't return anything.
13475   return SDValue();
13476 }
13477
13478 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13479 /// nodes.
13480 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13481                                     TargetLowering::DAGCombinerInfo &DCI,
13482                                     const X86Subtarget *Subtarget) {
13483   DebugLoc DL = N->getDebugLoc();
13484   SDValue Cond = N->getOperand(0);
13485   // Get the LHS/RHS of the select.
13486   SDValue LHS = N->getOperand(1);
13487   SDValue RHS = N->getOperand(2);
13488   EVT VT = LHS.getValueType();
13489
13490   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13491   // instructions match the semantics of the common C idiom x<y?x:y but not
13492   // x<=y?x:y, because of how they handle negative zero (which can be
13493   // ignored in unsafe-math mode).
13494   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13495       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13496       (Subtarget->hasSSE2() ||
13497        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13498     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13499
13500     unsigned Opcode = 0;
13501     // Check for x CC y ? x : y.
13502     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13503         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13504       switch (CC) {
13505       default: break;
13506       case ISD::SETULT:
13507         // Converting this to a min would handle NaNs incorrectly, and swapping
13508         // the operands would cause it to handle comparisons between positive
13509         // and negative zero incorrectly.
13510         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13511           if (!DAG.getTarget().Options.UnsafeFPMath &&
13512               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13513             break;
13514           std::swap(LHS, RHS);
13515         }
13516         Opcode = X86ISD::FMIN;
13517         break;
13518       case ISD::SETOLE:
13519         // Converting this to a min would handle comparisons between positive
13520         // and negative zero incorrectly.
13521         if (!DAG.getTarget().Options.UnsafeFPMath &&
13522             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13523           break;
13524         Opcode = X86ISD::FMIN;
13525         break;
13526       case ISD::SETULE:
13527         // Converting this to a min would handle both negative zeros and NaNs
13528         // incorrectly, but we can swap the operands to fix both.
13529         std::swap(LHS, RHS);
13530       case ISD::SETOLT:
13531       case ISD::SETLT:
13532       case ISD::SETLE:
13533         Opcode = X86ISD::FMIN;
13534         break;
13535
13536       case ISD::SETOGE:
13537         // Converting this to a max would handle comparisons between positive
13538         // and negative zero incorrectly.
13539         if (!DAG.getTarget().Options.UnsafeFPMath &&
13540             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13541           break;
13542         Opcode = X86ISD::FMAX;
13543         break;
13544       case ISD::SETUGT:
13545         // Converting this to a max would handle NaNs incorrectly, and swapping
13546         // the operands would cause it to handle comparisons between positive
13547         // and negative zero incorrectly.
13548         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13549           if (!DAG.getTarget().Options.UnsafeFPMath &&
13550               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13551             break;
13552           std::swap(LHS, RHS);
13553         }
13554         Opcode = X86ISD::FMAX;
13555         break;
13556       case ISD::SETUGE:
13557         // Converting this to a max would handle both negative zeros and NaNs
13558         // incorrectly, but we can swap the operands to fix both.
13559         std::swap(LHS, RHS);
13560       case ISD::SETOGT:
13561       case ISD::SETGT:
13562       case ISD::SETGE:
13563         Opcode = X86ISD::FMAX;
13564         break;
13565       }
13566     // Check for x CC y ? y : x -- a min/max with reversed arms.
13567     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13568                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13569       switch (CC) {
13570       default: break;
13571       case ISD::SETOGE:
13572         // Converting this to a min would handle comparisons between positive
13573         // and negative zero incorrectly, and swapping the operands would
13574         // cause it to handle NaNs incorrectly.
13575         if (!DAG.getTarget().Options.UnsafeFPMath &&
13576             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13577           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13578             break;
13579           std::swap(LHS, RHS);
13580         }
13581         Opcode = X86ISD::FMIN;
13582         break;
13583       case ISD::SETUGT:
13584         // Converting this to a min would handle NaNs incorrectly.
13585         if (!DAG.getTarget().Options.UnsafeFPMath &&
13586             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13587           break;
13588         Opcode = X86ISD::FMIN;
13589         break;
13590       case ISD::SETUGE:
13591         // Converting this to a min would handle both negative zeros and NaNs
13592         // incorrectly, but we can swap the operands to fix both.
13593         std::swap(LHS, RHS);
13594       case ISD::SETOGT:
13595       case ISD::SETGT:
13596       case ISD::SETGE:
13597         Opcode = X86ISD::FMIN;
13598         break;
13599
13600       case ISD::SETULT:
13601         // Converting this to a max would handle NaNs incorrectly.
13602         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13603           break;
13604         Opcode = X86ISD::FMAX;
13605         break;
13606       case ISD::SETOLE:
13607         // Converting this to a max would handle comparisons between positive
13608         // and negative zero incorrectly, and swapping the operands would
13609         // cause it to handle NaNs incorrectly.
13610         if (!DAG.getTarget().Options.UnsafeFPMath &&
13611             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13612           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13613             break;
13614           std::swap(LHS, RHS);
13615         }
13616         Opcode = X86ISD::FMAX;
13617         break;
13618       case ISD::SETULE:
13619         // Converting this to a max would handle both negative zeros and NaNs
13620         // incorrectly, but we can swap the operands to fix both.
13621         std::swap(LHS, RHS);
13622       case ISD::SETOLT:
13623       case ISD::SETLT:
13624       case ISD::SETLE:
13625         Opcode = X86ISD::FMAX;
13626         break;
13627       }
13628     }
13629
13630     if (Opcode)
13631       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13632   }
13633
13634   // If this is a select between two integer constants, try to do some
13635   // optimizations.
13636   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13637     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13638       // Don't do this for crazy integer types.
13639       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13640         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13641         // so that TrueC (the true value) is larger than FalseC.
13642         bool NeedsCondInvert = false;
13643
13644         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13645             // Efficiently invertible.
13646             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13647              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13648               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13649           NeedsCondInvert = true;
13650           std::swap(TrueC, FalseC);
13651         }
13652
13653         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13654         if (FalseC->getAPIntValue() == 0 &&
13655             TrueC->getAPIntValue().isPowerOf2()) {
13656           if (NeedsCondInvert) // Invert the condition if needed.
13657             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13658                                DAG.getConstant(1, Cond.getValueType()));
13659
13660           // Zero extend the condition if needed.
13661           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13662
13663           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13664           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13665                              DAG.getConstant(ShAmt, MVT::i8));
13666         }
13667
13668         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13669         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13670           if (NeedsCondInvert) // Invert the condition if needed.
13671             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13672                                DAG.getConstant(1, Cond.getValueType()));
13673
13674           // Zero extend the condition if needed.
13675           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13676                              FalseC->getValueType(0), Cond);
13677           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13678                              SDValue(FalseC, 0));
13679         }
13680
13681         // Optimize cases that will turn into an LEA instruction.  This requires
13682         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13683         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13684           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13685           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13686
13687           bool isFastMultiplier = false;
13688           if (Diff < 10) {
13689             switch ((unsigned char)Diff) {
13690               default: break;
13691               case 1:  // result = add base, cond
13692               case 2:  // result = lea base(    , cond*2)
13693               case 3:  // result = lea base(cond, cond*2)
13694               case 4:  // result = lea base(    , cond*4)
13695               case 5:  // result = lea base(cond, cond*4)
13696               case 8:  // result = lea base(    , cond*8)
13697               case 9:  // result = lea base(cond, cond*8)
13698                 isFastMultiplier = true;
13699                 break;
13700             }
13701           }
13702
13703           if (isFastMultiplier) {
13704             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13705             if (NeedsCondInvert) // Invert the condition if needed.
13706               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13707                                  DAG.getConstant(1, Cond.getValueType()));
13708
13709             // Zero extend the condition if needed.
13710             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13711                                Cond);
13712             // Scale the condition by the difference.
13713             if (Diff != 1)
13714               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13715                                  DAG.getConstant(Diff, Cond.getValueType()));
13716
13717             // Add the base if non-zero.
13718             if (FalseC->getAPIntValue() != 0)
13719               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13720                                  SDValue(FalseC, 0));
13721             return Cond;
13722           }
13723         }
13724       }
13725   }
13726
13727   // Canonicalize max and min:
13728   // (x > y) ? x : y -> (x >= y) ? x : y
13729   // (x < y) ? x : y -> (x <= y) ? x : y
13730   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13731   // the need for an extra compare
13732   // against zero. e.g.
13733   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13734   // subl   %esi, %edi
13735   // testl  %edi, %edi
13736   // movl   $0, %eax
13737   // cmovgl %edi, %eax
13738   // =>
13739   // xorl   %eax, %eax
13740   // subl   %esi, $edi
13741   // cmovsl %eax, %edi
13742   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13743       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13744       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13745     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13746     switch (CC) {
13747     default: break;
13748     case ISD::SETLT:
13749     case ISD::SETGT: {
13750       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13751       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13752                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13753       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13754     }
13755     }
13756   }
13757
13758   // If we know that this node is legal then we know that it is going to be
13759   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13760   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13761   // to simplify previous instructions.
13762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13764       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13765     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13766
13767     // Don't optimize vector selects that map to mask-registers.
13768     if (BitWidth == 1)
13769       return SDValue();
13770
13771     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13772     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13773
13774     APInt KnownZero, KnownOne;
13775     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13776                                           DCI.isBeforeLegalizeOps());
13777     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13778         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13779       DCI.CommitTargetLoweringOpt(TLO);
13780   }
13781
13782   return SDValue();
13783 }
13784
13785 // Check whether a boolean test is testing a boolean value generated by
13786 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
13787 // code.
13788 //
13789 // Simplify the following patterns:
13790 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
13791 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
13792 // to (Op EFLAGS Cond)
13793 //
13794 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
13795 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
13796 // to (Op EFLAGS !Cond)
13797 //
13798 // where Op could be BRCOND or CMOV.
13799 //
13800 static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
13801   // Quit if not CMP and SUB with its value result used.
13802   if (Cmp.getOpcode() != X86ISD::CMP &&
13803       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
13804       return SDValue();
13805
13806   // Quit if not used as a boolean value.
13807   if (CC != X86::COND_E && CC != X86::COND_NE)
13808     return SDValue();
13809
13810   // Check CMP operands. One of them should be 0 or 1 and the other should be
13811   // an SetCC or extended from it.
13812   SDValue Op1 = Cmp.getOperand(0);
13813   SDValue Op2 = Cmp.getOperand(1);
13814
13815   SDValue SetCC;
13816   const ConstantSDNode* C = 0;
13817   bool needOppositeCond = (CC == X86::COND_E);
13818
13819   if ((C = dyn_cast<ConstantSDNode>(Op1)))
13820     SetCC = Op2;
13821   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
13822     SetCC = Op1;
13823   else // Quit if all operands are not constants.
13824     return SDValue();
13825
13826   if (C->getZExtValue() == 1)
13827     needOppositeCond = !needOppositeCond;
13828   else if (C->getZExtValue() != 0)
13829     // Quit if the constant is neither 0 or 1.
13830     return SDValue();
13831
13832   // Skip 'zext' node.
13833   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
13834     SetCC = SetCC.getOperand(0);
13835
13836   // Quit if not SETCC.
13837   // FIXME: So far we only handle the boolean value generated from SETCC. If
13838   // there is other ways to generate boolean values, we need handle them here
13839   // as well.
13840   if (SetCC.getOpcode() != X86ISD::SETCC)
13841     return SDValue();
13842
13843   // Set the condition code or opposite one if necessary.
13844   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
13845   if (needOppositeCond)
13846     CC = X86::GetOppositeBranchCondition(CC);
13847
13848   return SetCC.getOperand(1);
13849 }
13850
13851 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13852 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13853                                   TargetLowering::DAGCombinerInfo &DCI) {
13854   DebugLoc DL = N->getDebugLoc();
13855
13856   // If the flag operand isn't dead, don't touch this CMOV.
13857   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13858     return SDValue();
13859
13860   SDValue FalseOp = N->getOperand(0);
13861   SDValue TrueOp = N->getOperand(1);
13862   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13863   SDValue Cond = N->getOperand(3);
13864
13865   if (CC == X86::COND_E || CC == X86::COND_NE) {
13866     switch (Cond.getOpcode()) {
13867     default: break;
13868     case X86ISD::BSR:
13869     case X86ISD::BSF:
13870       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13871       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13872         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13873     }
13874   }
13875
13876   SDValue Flags;
13877
13878   Flags = BoolTestSetCCCombine(Cond, CC);
13879   if (Flags.getNode()) {
13880     SDValue Ops[] = { FalseOp, TrueOp,
13881                       DAG.getConstant(CC, MVT::i8), Flags };
13882     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
13883                        Ops, array_lengthof(Ops));
13884   }
13885
13886   // If this is a select between two integer constants, try to do some
13887   // optimizations.  Note that the operands are ordered the opposite of SELECT
13888   // operands.
13889   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13890     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13891       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13892       // larger than FalseC (the false value).
13893       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13894         CC = X86::GetOppositeBranchCondition(CC);
13895         std::swap(TrueC, FalseC);
13896       }
13897
13898       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13899       // This is efficient for any integer data type (including i8/i16) and
13900       // shift amount.
13901       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13902         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13903                            DAG.getConstant(CC, MVT::i8), Cond);
13904
13905         // Zero extend the condition if needed.
13906         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13907
13908         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13909         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13910                            DAG.getConstant(ShAmt, MVT::i8));
13911         if (N->getNumValues() == 2)  // Dead flag value?
13912           return DCI.CombineTo(N, Cond, SDValue());
13913         return Cond;
13914       }
13915
13916       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13917       // for any integer data type, including i8/i16.
13918       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13919         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13920                            DAG.getConstant(CC, MVT::i8), Cond);
13921
13922         // Zero extend the condition if needed.
13923         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13924                            FalseC->getValueType(0), Cond);
13925         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13926                            SDValue(FalseC, 0));
13927
13928         if (N->getNumValues() == 2)  // Dead flag value?
13929           return DCI.CombineTo(N, Cond, SDValue());
13930         return Cond;
13931       }
13932
13933       // Optimize cases that will turn into an LEA instruction.  This requires
13934       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13935       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13936         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13937         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13938
13939         bool isFastMultiplier = false;
13940         if (Diff < 10) {
13941           switch ((unsigned char)Diff) {
13942           default: break;
13943           case 1:  // result = add base, cond
13944           case 2:  // result = lea base(    , cond*2)
13945           case 3:  // result = lea base(cond, cond*2)
13946           case 4:  // result = lea base(    , cond*4)
13947           case 5:  // result = lea base(cond, cond*4)
13948           case 8:  // result = lea base(    , cond*8)
13949           case 9:  // result = lea base(cond, cond*8)
13950             isFastMultiplier = true;
13951             break;
13952           }
13953         }
13954
13955         if (isFastMultiplier) {
13956           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13957           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13958                              DAG.getConstant(CC, MVT::i8), Cond);
13959           // Zero extend the condition if needed.
13960           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13961                              Cond);
13962           // Scale the condition by the difference.
13963           if (Diff != 1)
13964             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13965                                DAG.getConstant(Diff, Cond.getValueType()));
13966
13967           // Add the base if non-zero.
13968           if (FalseC->getAPIntValue() != 0)
13969             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13970                                SDValue(FalseC, 0));
13971           if (N->getNumValues() == 2)  // Dead flag value?
13972             return DCI.CombineTo(N, Cond, SDValue());
13973           return Cond;
13974         }
13975       }
13976     }
13977   }
13978   return SDValue();
13979 }
13980
13981
13982 /// PerformMulCombine - Optimize a single multiply with constant into two
13983 /// in order to implement it with two cheaper instructions, e.g.
13984 /// LEA + SHL, LEA + LEA.
13985 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13986                                  TargetLowering::DAGCombinerInfo &DCI) {
13987   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13988     return SDValue();
13989
13990   EVT VT = N->getValueType(0);
13991   if (VT != MVT::i64)
13992     return SDValue();
13993
13994   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13995   if (!C)
13996     return SDValue();
13997   uint64_t MulAmt = C->getZExtValue();
13998   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13999     return SDValue();
14000
14001   uint64_t MulAmt1 = 0;
14002   uint64_t MulAmt2 = 0;
14003   if ((MulAmt % 9) == 0) {
14004     MulAmt1 = 9;
14005     MulAmt2 = MulAmt / 9;
14006   } else if ((MulAmt % 5) == 0) {
14007     MulAmt1 = 5;
14008     MulAmt2 = MulAmt / 5;
14009   } else if ((MulAmt % 3) == 0) {
14010     MulAmt1 = 3;
14011     MulAmt2 = MulAmt / 3;
14012   }
14013   if (MulAmt2 &&
14014       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14015     DebugLoc DL = N->getDebugLoc();
14016
14017     if (isPowerOf2_64(MulAmt2) &&
14018         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14019       // If second multiplifer is pow2, issue it first. We want the multiply by
14020       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14021       // is an add.
14022       std::swap(MulAmt1, MulAmt2);
14023
14024     SDValue NewMul;
14025     if (isPowerOf2_64(MulAmt1))
14026       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14027                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14028     else
14029       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14030                            DAG.getConstant(MulAmt1, VT));
14031
14032     if (isPowerOf2_64(MulAmt2))
14033       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14034                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14035     else
14036       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14037                            DAG.getConstant(MulAmt2, VT));
14038
14039     // Do not add new nodes to DAG combiner worklist.
14040     DCI.CombineTo(N, NewMul, false);
14041   }
14042   return SDValue();
14043 }
14044
14045 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14046   SDValue N0 = N->getOperand(0);
14047   SDValue N1 = N->getOperand(1);
14048   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14049   EVT VT = N0.getValueType();
14050
14051   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14052   // since the result of setcc_c is all zero's or all ones.
14053   if (VT.isInteger() && !VT.isVector() &&
14054       N1C && N0.getOpcode() == ISD::AND &&
14055       N0.getOperand(1).getOpcode() == ISD::Constant) {
14056     SDValue N00 = N0.getOperand(0);
14057     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14058         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14059           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14060          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14061       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14062       APInt ShAmt = N1C->getAPIntValue();
14063       Mask = Mask.shl(ShAmt);
14064       if (Mask != 0)
14065         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14066                            N00, DAG.getConstant(Mask, VT));
14067     }
14068   }
14069
14070
14071   // Hardware support for vector shifts is sparse which makes us scalarize the
14072   // vector operations in many cases. Also, on sandybridge ADD is faster than
14073   // shl.
14074   // (shl V, 1) -> add V,V
14075   if (isSplatVector(N1.getNode())) {
14076     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14077     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14078     // We shift all of the values by one. In many cases we do not have
14079     // hardware support for this operation. This is better expressed as an ADD
14080     // of two values.
14081     if (N1C && (1 == N1C->getZExtValue())) {
14082       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14083     }
14084   }
14085
14086   return SDValue();
14087 }
14088
14089 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14090 ///                       when possible.
14091 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14092                                    TargetLowering::DAGCombinerInfo &DCI,
14093                                    const X86Subtarget *Subtarget) {
14094   EVT VT = N->getValueType(0);
14095   if (N->getOpcode() == ISD::SHL) {
14096     SDValue V = PerformSHLCombine(N, DAG);
14097     if (V.getNode()) return V;
14098   }
14099
14100   // On X86 with SSE2 support, we can transform this to a vector shift if
14101   // all elements are shifted by the same amount.  We can't do this in legalize
14102   // because the a constant vector is typically transformed to a constant pool
14103   // so we have no knowledge of the shift amount.
14104   if (!Subtarget->hasSSE2())
14105     return SDValue();
14106
14107   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14108       (!Subtarget->hasAVX2() ||
14109        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14110     return SDValue();
14111
14112   SDValue ShAmtOp = N->getOperand(1);
14113   EVT EltVT = VT.getVectorElementType();
14114   DebugLoc DL = N->getDebugLoc();
14115   SDValue BaseShAmt = SDValue();
14116   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14117     unsigned NumElts = VT.getVectorNumElements();
14118     unsigned i = 0;
14119     for (; i != NumElts; ++i) {
14120       SDValue Arg = ShAmtOp.getOperand(i);
14121       if (Arg.getOpcode() == ISD::UNDEF) continue;
14122       BaseShAmt = Arg;
14123       break;
14124     }
14125     // Handle the case where the build_vector is all undef
14126     // FIXME: Should DAG allow this?
14127     if (i == NumElts)
14128       return SDValue();
14129
14130     for (; i != NumElts; ++i) {
14131       SDValue Arg = ShAmtOp.getOperand(i);
14132       if (Arg.getOpcode() == ISD::UNDEF) continue;
14133       if (Arg != BaseShAmt) {
14134         return SDValue();
14135       }
14136     }
14137   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14138              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14139     SDValue InVec = ShAmtOp.getOperand(0);
14140     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14141       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14142       unsigned i = 0;
14143       for (; i != NumElts; ++i) {
14144         SDValue Arg = InVec.getOperand(i);
14145         if (Arg.getOpcode() == ISD::UNDEF) continue;
14146         BaseShAmt = Arg;
14147         break;
14148       }
14149     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14150        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14151          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14152          if (C->getZExtValue() == SplatIdx)
14153            BaseShAmt = InVec.getOperand(1);
14154        }
14155     }
14156     if (BaseShAmt.getNode() == 0) {
14157       // Don't create instructions with illegal types after legalize
14158       // types has run.
14159       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14160           !DCI.isBeforeLegalize())
14161         return SDValue();
14162
14163       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14164                               DAG.getIntPtrConstant(0));
14165     }
14166   } else
14167     return SDValue();
14168
14169   // The shift amount is an i32.
14170   if (EltVT.bitsGT(MVT::i32))
14171     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14172   else if (EltVT.bitsLT(MVT::i32))
14173     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14174
14175   // The shift amount is identical so we can do a vector shift.
14176   SDValue  ValOp = N->getOperand(0);
14177   switch (N->getOpcode()) {
14178   default:
14179     llvm_unreachable("Unknown shift opcode!");
14180   case ISD::SHL:
14181     switch (VT.getSimpleVT().SimpleTy) {
14182     default: return SDValue();
14183     case MVT::v2i64:
14184     case MVT::v4i32:
14185     case MVT::v8i16:
14186     case MVT::v4i64:
14187     case MVT::v8i32:
14188     case MVT::v16i16:
14189       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14190     }
14191   case ISD::SRA:
14192     switch (VT.getSimpleVT().SimpleTy) {
14193     default: return SDValue();
14194     case MVT::v4i32:
14195     case MVT::v8i16:
14196     case MVT::v8i32:
14197     case MVT::v16i16:
14198       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14199     }
14200   case ISD::SRL:
14201     switch (VT.getSimpleVT().SimpleTy) {
14202     default: return SDValue();
14203     case MVT::v2i64:
14204     case MVT::v4i32:
14205     case MVT::v8i16:
14206     case MVT::v4i64:
14207     case MVT::v8i32:
14208     case MVT::v16i16:
14209       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14210     }
14211   }
14212 }
14213
14214
14215 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14216 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14217 // and friends.  Likewise for OR -> CMPNEQSS.
14218 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14219                             TargetLowering::DAGCombinerInfo &DCI,
14220                             const X86Subtarget *Subtarget) {
14221   unsigned opcode;
14222
14223   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14224   // we're requiring SSE2 for both.
14225   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14226     SDValue N0 = N->getOperand(0);
14227     SDValue N1 = N->getOperand(1);
14228     SDValue CMP0 = N0->getOperand(1);
14229     SDValue CMP1 = N1->getOperand(1);
14230     DebugLoc DL = N->getDebugLoc();
14231
14232     // The SETCCs should both refer to the same CMP.
14233     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14234       return SDValue();
14235
14236     SDValue CMP00 = CMP0->getOperand(0);
14237     SDValue CMP01 = CMP0->getOperand(1);
14238     EVT     VT    = CMP00.getValueType();
14239
14240     if (VT == MVT::f32 || VT == MVT::f64) {
14241       bool ExpectingFlags = false;
14242       // Check for any users that want flags:
14243       for (SDNode::use_iterator UI = N->use_begin(),
14244              UE = N->use_end();
14245            !ExpectingFlags && UI != UE; ++UI)
14246         switch (UI->getOpcode()) {
14247         default:
14248         case ISD::BR_CC:
14249         case ISD::BRCOND:
14250         case ISD::SELECT:
14251           ExpectingFlags = true;
14252           break;
14253         case ISD::CopyToReg:
14254         case ISD::SIGN_EXTEND:
14255         case ISD::ZERO_EXTEND:
14256         case ISD::ANY_EXTEND:
14257           break;
14258         }
14259
14260       if (!ExpectingFlags) {
14261         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14262         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14263
14264         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14265           X86::CondCode tmp = cc0;
14266           cc0 = cc1;
14267           cc1 = tmp;
14268         }
14269
14270         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14271             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14272           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14273           X86ISD::NodeType NTOperator = is64BitFP ?
14274             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14275           // FIXME: need symbolic constants for these magic numbers.
14276           // See X86ATTInstPrinter.cpp:printSSECC().
14277           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14278           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14279                                               DAG.getConstant(x86cc, MVT::i8));
14280           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14281                                               OnesOrZeroesF);
14282           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14283                                       DAG.getConstant(1, MVT::i32));
14284           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14285           return OneBitOfTruth;
14286         }
14287       }
14288     }
14289   }
14290   return SDValue();
14291 }
14292
14293 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14294 /// so it can be folded inside ANDNP.
14295 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14296   EVT VT = N->getValueType(0);
14297
14298   // Match direct AllOnes for 128 and 256-bit vectors
14299   if (ISD::isBuildVectorAllOnes(N))
14300     return true;
14301
14302   // Look through a bit convert.
14303   if (N->getOpcode() == ISD::BITCAST)
14304     N = N->getOperand(0).getNode();
14305
14306   // Sometimes the operand may come from a insert_subvector building a 256-bit
14307   // allones vector
14308   if (VT.getSizeInBits() == 256 &&
14309       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14310     SDValue V1 = N->getOperand(0);
14311     SDValue V2 = N->getOperand(1);
14312
14313     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14314         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14315         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14316         ISD::isBuildVectorAllOnes(V2.getNode()))
14317       return true;
14318   }
14319
14320   return false;
14321 }
14322
14323 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14324                                  TargetLowering::DAGCombinerInfo &DCI,
14325                                  const X86Subtarget *Subtarget) {
14326   if (DCI.isBeforeLegalizeOps())
14327     return SDValue();
14328
14329   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14330   if (R.getNode())
14331     return R;
14332
14333   EVT VT = N->getValueType(0);
14334
14335   // Create ANDN, BLSI, and BLSR instructions
14336   // BLSI is X & (-X)
14337   // BLSR is X & (X-1)
14338   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14339     SDValue N0 = N->getOperand(0);
14340     SDValue N1 = N->getOperand(1);
14341     DebugLoc DL = N->getDebugLoc();
14342
14343     // Check LHS for not
14344     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14345       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14346     // Check RHS for not
14347     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14348       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14349
14350     // Check LHS for neg
14351     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14352         isZero(N0.getOperand(0)))
14353       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14354
14355     // Check RHS for neg
14356     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14357         isZero(N1.getOperand(0)))
14358       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14359
14360     // Check LHS for X-1
14361     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14362         isAllOnes(N0.getOperand(1)))
14363       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14364
14365     // Check RHS for X-1
14366     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14367         isAllOnes(N1.getOperand(1)))
14368       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14369
14370     return SDValue();
14371   }
14372
14373   // Want to form ANDNP nodes:
14374   // 1) In the hopes of then easily combining them with OR and AND nodes
14375   //    to form PBLEND/PSIGN.
14376   // 2) To match ANDN packed intrinsics
14377   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14378     return SDValue();
14379
14380   SDValue N0 = N->getOperand(0);
14381   SDValue N1 = N->getOperand(1);
14382   DebugLoc DL = N->getDebugLoc();
14383
14384   // Check LHS for vnot
14385   if (N0.getOpcode() == ISD::XOR &&
14386       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14387       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14388     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14389
14390   // Check RHS for vnot
14391   if (N1.getOpcode() == ISD::XOR &&
14392       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14393       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14394     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14395
14396   return SDValue();
14397 }
14398
14399 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14400                                 TargetLowering::DAGCombinerInfo &DCI,
14401                                 const X86Subtarget *Subtarget) {
14402   if (DCI.isBeforeLegalizeOps())
14403     return SDValue();
14404
14405   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14406   if (R.getNode())
14407     return R;
14408
14409   EVT VT = N->getValueType(0);
14410
14411   SDValue N0 = N->getOperand(0);
14412   SDValue N1 = N->getOperand(1);
14413
14414   // look for psign/blend
14415   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14416     if (!Subtarget->hasSSSE3() ||
14417         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14418       return SDValue();
14419
14420     // Canonicalize pandn to RHS
14421     if (N0.getOpcode() == X86ISD::ANDNP)
14422       std::swap(N0, N1);
14423     // or (and (m, y), (pandn m, x))
14424     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14425       SDValue Mask = N1.getOperand(0);
14426       SDValue X    = N1.getOperand(1);
14427       SDValue Y;
14428       if (N0.getOperand(0) == Mask)
14429         Y = N0.getOperand(1);
14430       if (N0.getOperand(1) == Mask)
14431         Y = N0.getOperand(0);
14432
14433       // Check to see if the mask appeared in both the AND and ANDNP and
14434       if (!Y.getNode())
14435         return SDValue();
14436
14437       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14438       // Look through mask bitcast.
14439       if (Mask.getOpcode() == ISD::BITCAST)
14440         Mask = Mask.getOperand(0);
14441       if (X.getOpcode() == ISD::BITCAST)
14442         X = X.getOperand(0);
14443       if (Y.getOpcode() == ISD::BITCAST)
14444         Y = Y.getOperand(0);
14445
14446       EVT MaskVT = Mask.getValueType();
14447
14448       // Validate that the Mask operand is a vector sra node.
14449       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14450       // there is no psrai.b
14451       if (Mask.getOpcode() != X86ISD::VSRAI)
14452         return SDValue();
14453
14454       // Check that the SRA is all signbits.
14455       SDValue SraC = Mask.getOperand(1);
14456       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14457       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14458       if ((SraAmt + 1) != EltBits)
14459         return SDValue();
14460
14461       DebugLoc DL = N->getDebugLoc();
14462
14463       // Now we know we at least have a plendvb with the mask val.  See if
14464       // we can form a psignb/w/d.
14465       // psign = x.type == y.type == mask.type && y = sub(0, x);
14466       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14467           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14468           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14469         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14470                "Unsupported VT for PSIGN");
14471         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14472         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14473       }
14474       // PBLENDVB only available on SSE 4.1
14475       if (!Subtarget->hasSSE41())
14476         return SDValue();
14477
14478       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14479
14480       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14481       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14482       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14483       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14484       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14485     }
14486   }
14487
14488   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14489     return SDValue();
14490
14491   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14492   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14493     std::swap(N0, N1);
14494   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14495     return SDValue();
14496   if (!N0.hasOneUse() || !N1.hasOneUse())
14497     return SDValue();
14498
14499   SDValue ShAmt0 = N0.getOperand(1);
14500   if (ShAmt0.getValueType() != MVT::i8)
14501     return SDValue();
14502   SDValue ShAmt1 = N1.getOperand(1);
14503   if (ShAmt1.getValueType() != MVT::i8)
14504     return SDValue();
14505   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14506     ShAmt0 = ShAmt0.getOperand(0);
14507   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14508     ShAmt1 = ShAmt1.getOperand(0);
14509
14510   DebugLoc DL = N->getDebugLoc();
14511   unsigned Opc = X86ISD::SHLD;
14512   SDValue Op0 = N0.getOperand(0);
14513   SDValue Op1 = N1.getOperand(0);
14514   if (ShAmt0.getOpcode() == ISD::SUB) {
14515     Opc = X86ISD::SHRD;
14516     std::swap(Op0, Op1);
14517     std::swap(ShAmt0, ShAmt1);
14518   }
14519
14520   unsigned Bits = VT.getSizeInBits();
14521   if (ShAmt1.getOpcode() == ISD::SUB) {
14522     SDValue Sum = ShAmt1.getOperand(0);
14523     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14524       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14525       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14526         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14527       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14528         return DAG.getNode(Opc, DL, VT,
14529                            Op0, Op1,
14530                            DAG.getNode(ISD::TRUNCATE, DL,
14531                                        MVT::i8, ShAmt0));
14532     }
14533   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14534     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14535     if (ShAmt0C &&
14536         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14537       return DAG.getNode(Opc, DL, VT,
14538                          N0.getOperand(0), N1.getOperand(0),
14539                          DAG.getNode(ISD::TRUNCATE, DL,
14540                                        MVT::i8, ShAmt0));
14541   }
14542
14543   return SDValue();
14544 }
14545
14546 // Generate NEG and CMOV for integer abs.
14547 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14548   EVT VT = N->getValueType(0);
14549
14550   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14551   // 8-bit integer abs to NEG and CMOV.
14552   if (VT.isInteger() && VT.getSizeInBits() == 8)
14553     return SDValue();
14554
14555   SDValue N0 = N->getOperand(0);
14556   SDValue N1 = N->getOperand(1);
14557   DebugLoc DL = N->getDebugLoc();
14558
14559   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14560   // and change it to SUB and CMOV.
14561   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14562       N0.getOpcode() == ISD::ADD &&
14563       N0.getOperand(1) == N1 &&
14564       N1.getOpcode() == ISD::SRA &&
14565       N1.getOperand(0) == N0.getOperand(0))
14566     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14567       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14568         // Generate SUB & CMOV.
14569         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14570                                   DAG.getConstant(0, VT), N0.getOperand(0));
14571
14572         SDValue Ops[] = { N0.getOperand(0), Neg,
14573                           DAG.getConstant(X86::COND_GE, MVT::i8),
14574                           SDValue(Neg.getNode(), 1) };
14575         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14576                            Ops, array_lengthof(Ops));
14577       }
14578   return SDValue();
14579 }
14580
14581 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14582 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14583                                  TargetLowering::DAGCombinerInfo &DCI,
14584                                  const X86Subtarget *Subtarget) {
14585   if (DCI.isBeforeLegalizeOps())
14586     return SDValue();
14587
14588   if (Subtarget->hasCMov()) {
14589     SDValue RV = performIntegerAbsCombine(N, DAG);
14590     if (RV.getNode())
14591       return RV;
14592   }
14593
14594   // Try forming BMI if it is available.
14595   if (!Subtarget->hasBMI())
14596     return SDValue();
14597
14598   EVT VT = N->getValueType(0);
14599
14600   if (VT != MVT::i32 && VT != MVT::i64)
14601     return SDValue();
14602
14603   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14604
14605   // Create BLSMSK instructions by finding X ^ (X-1)
14606   SDValue N0 = N->getOperand(0);
14607   SDValue N1 = N->getOperand(1);
14608   DebugLoc DL = N->getDebugLoc();
14609
14610   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14611       isAllOnes(N0.getOperand(1)))
14612     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14613
14614   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14615       isAllOnes(N1.getOperand(1)))
14616     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14617
14618   return SDValue();
14619 }
14620
14621 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14622 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14623                                   TargetLowering::DAGCombinerInfo &DCI,
14624                                   const X86Subtarget *Subtarget) {
14625   LoadSDNode *Ld = cast<LoadSDNode>(N);
14626   EVT RegVT = Ld->getValueType(0);
14627   EVT MemVT = Ld->getMemoryVT();
14628   DebugLoc dl = Ld->getDebugLoc();
14629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14630
14631   ISD::LoadExtType Ext = Ld->getExtensionType();
14632
14633   // If this is a vector EXT Load then attempt to optimize it using a
14634   // shuffle. We need SSE4 for the shuffles.
14635   // TODO: It is possible to support ZExt by zeroing the undef values
14636   // during the shuffle phase or after the shuffle.
14637   if (RegVT.isVector() && RegVT.isInteger() &&
14638       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14639     assert(MemVT != RegVT && "Cannot extend to the same type");
14640     assert(MemVT.isVector() && "Must load a vector from memory");
14641
14642     unsigned NumElems = RegVT.getVectorNumElements();
14643     unsigned RegSz = RegVT.getSizeInBits();
14644     unsigned MemSz = MemVT.getSizeInBits();
14645     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14646
14647     // All sizes must be a power of two.
14648     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14649       return SDValue();
14650
14651     // Attempt to load the original value using scalar loads.
14652     // Find the largest scalar type that divides the total loaded size.
14653     MVT SclrLoadTy = MVT::i8;
14654     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14655          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14656       MVT Tp = (MVT::SimpleValueType)tp;
14657       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14658         SclrLoadTy = Tp;
14659       }
14660     }
14661
14662     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14663     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14664         (64 <= MemSz))
14665       SclrLoadTy = MVT::f64;
14666
14667     // Calculate the number of scalar loads that we need to perform
14668     // in order to load our vector from memory.
14669     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14670
14671     // Represent our vector as a sequence of elements which are the
14672     // largest scalar that we can load.
14673     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14674       RegSz/SclrLoadTy.getSizeInBits());
14675
14676     // Represent the data using the same element type that is stored in
14677     // memory. In practice, we ''widen'' MemVT.
14678     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14679                                   RegSz/MemVT.getScalarType().getSizeInBits());
14680
14681     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14682       "Invalid vector type");
14683
14684     // We can't shuffle using an illegal type.
14685     if (!TLI.isTypeLegal(WideVecVT))
14686       return SDValue();
14687
14688     SmallVector<SDValue, 8> Chains;
14689     SDValue Ptr = Ld->getBasePtr();
14690     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14691                                         TLI.getPointerTy());
14692     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14693
14694     for (unsigned i = 0; i < NumLoads; ++i) {
14695       // Perform a single load.
14696       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14697                                        Ptr, Ld->getPointerInfo(),
14698                                        Ld->isVolatile(), Ld->isNonTemporal(),
14699                                        Ld->isInvariant(), Ld->getAlignment());
14700       Chains.push_back(ScalarLoad.getValue(1));
14701       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14702       // another round of DAGCombining.
14703       if (i == 0)
14704         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14705       else
14706         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14707                           ScalarLoad, DAG.getIntPtrConstant(i));
14708
14709       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14710     }
14711
14712     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14713                                Chains.size());
14714
14715     // Bitcast the loaded value to a vector of the original element type, in
14716     // the size of the target vector type.
14717     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14718     unsigned SizeRatio = RegSz/MemSz;
14719
14720     // Redistribute the loaded elements into the different locations.
14721     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14722     for (unsigned i = 0; i != NumElems; ++i)
14723       ShuffleVec[i*SizeRatio] = i;
14724
14725     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14726                                          DAG.getUNDEF(WideVecVT),
14727                                          &ShuffleVec[0]);
14728
14729     // Bitcast to the requested type.
14730     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14731     // Replace the original load with the new sequence
14732     // and return the new chain.
14733     return DCI.CombineTo(N, Shuff, TF, true);
14734   }
14735
14736   return SDValue();
14737 }
14738
14739 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14740 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14741                                    const X86Subtarget *Subtarget) {
14742   StoreSDNode *St = cast<StoreSDNode>(N);
14743   EVT VT = St->getValue().getValueType();
14744   EVT StVT = St->getMemoryVT();
14745   DebugLoc dl = St->getDebugLoc();
14746   SDValue StoredVal = St->getOperand(1);
14747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14748
14749   // If we are saving a concatenation of two XMM registers, perform two stores.
14750   // On Sandy Bridge, 256-bit memory operations are executed by two
14751   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14752   // memory  operation.
14753   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14754       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14755       StoredVal.getNumOperands() == 2) {
14756     SDValue Value0 = StoredVal.getOperand(0);
14757     SDValue Value1 = StoredVal.getOperand(1);
14758
14759     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14760     SDValue Ptr0 = St->getBasePtr();
14761     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14762
14763     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14764                                 St->getPointerInfo(), St->isVolatile(),
14765                                 St->isNonTemporal(), St->getAlignment());
14766     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14767                                 St->getPointerInfo(), St->isVolatile(),
14768                                 St->isNonTemporal(), St->getAlignment());
14769     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14770   }
14771
14772   // Optimize trunc store (of multiple scalars) to shuffle and store.
14773   // First, pack all of the elements in one place. Next, store to memory
14774   // in fewer chunks.
14775   if (St->isTruncatingStore() && VT.isVector()) {
14776     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14777     unsigned NumElems = VT.getVectorNumElements();
14778     assert(StVT != VT && "Cannot truncate to the same type");
14779     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14780     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14781
14782     // From, To sizes and ElemCount must be pow of two
14783     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14784     // We are going to use the original vector elt for storing.
14785     // Accumulated smaller vector elements must be a multiple of the store size.
14786     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14787
14788     unsigned SizeRatio  = FromSz / ToSz;
14789
14790     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14791
14792     // Create a type on which we perform the shuffle
14793     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14794             StVT.getScalarType(), NumElems*SizeRatio);
14795
14796     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14797
14798     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14799     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14800     for (unsigned i = 0; i != NumElems; ++i)
14801       ShuffleVec[i] = i * SizeRatio;
14802
14803     // Can't shuffle using an illegal type.
14804     if (!TLI.isTypeLegal(WideVecVT))
14805       return SDValue();
14806
14807     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14808                                          DAG.getUNDEF(WideVecVT),
14809                                          &ShuffleVec[0]);
14810     // At this point all of the data is stored at the bottom of the
14811     // register. We now need to save it to mem.
14812
14813     // Find the largest store unit
14814     MVT StoreType = MVT::i8;
14815     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14816          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14817       MVT Tp = (MVT::SimpleValueType)tp;
14818       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14819         StoreType = Tp;
14820     }
14821
14822     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14823     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14824         (64 <= NumElems * ToSz))
14825       StoreType = MVT::f64;
14826
14827     // Bitcast the original vector into a vector of store-size units
14828     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14829             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14830     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14831     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14832     SmallVector<SDValue, 8> Chains;
14833     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14834                                         TLI.getPointerTy());
14835     SDValue Ptr = St->getBasePtr();
14836
14837     // Perform one or more big stores into memory.
14838     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14839       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14840                                    StoreType, ShuffWide,
14841                                    DAG.getIntPtrConstant(i));
14842       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14843                                 St->getPointerInfo(), St->isVolatile(),
14844                                 St->isNonTemporal(), St->getAlignment());
14845       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14846       Chains.push_back(Ch);
14847     }
14848
14849     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14850                                Chains.size());
14851   }
14852
14853
14854   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14855   // the FP state in cases where an emms may be missing.
14856   // A preferable solution to the general problem is to figure out the right
14857   // places to insert EMMS.  This qualifies as a quick hack.
14858
14859   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14860   if (VT.getSizeInBits() != 64)
14861     return SDValue();
14862
14863   const Function *F = DAG.getMachineFunction().getFunction();
14864   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14865   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14866                      && Subtarget->hasSSE2();
14867   if ((VT.isVector() ||
14868        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14869       isa<LoadSDNode>(St->getValue()) &&
14870       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14871       St->getChain().hasOneUse() && !St->isVolatile()) {
14872     SDNode* LdVal = St->getValue().getNode();
14873     LoadSDNode *Ld = 0;
14874     int TokenFactorIndex = -1;
14875     SmallVector<SDValue, 8> Ops;
14876     SDNode* ChainVal = St->getChain().getNode();
14877     // Must be a store of a load.  We currently handle two cases:  the load
14878     // is a direct child, and it's under an intervening TokenFactor.  It is
14879     // possible to dig deeper under nested TokenFactors.
14880     if (ChainVal == LdVal)
14881       Ld = cast<LoadSDNode>(St->getChain());
14882     else if (St->getValue().hasOneUse() &&
14883              ChainVal->getOpcode() == ISD::TokenFactor) {
14884       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14885         if (ChainVal->getOperand(i).getNode() == LdVal) {
14886           TokenFactorIndex = i;
14887           Ld = cast<LoadSDNode>(St->getValue());
14888         } else
14889           Ops.push_back(ChainVal->getOperand(i));
14890       }
14891     }
14892
14893     if (!Ld || !ISD::isNormalLoad(Ld))
14894       return SDValue();
14895
14896     // If this is not the MMX case, i.e. we are just turning i64 load/store
14897     // into f64 load/store, avoid the transformation if there are multiple
14898     // uses of the loaded value.
14899     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14900       return SDValue();
14901
14902     DebugLoc LdDL = Ld->getDebugLoc();
14903     DebugLoc StDL = N->getDebugLoc();
14904     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14905     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14906     // pair instead.
14907     if (Subtarget->is64Bit() || F64IsLegal) {
14908       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14909       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14910                                   Ld->getPointerInfo(), Ld->isVolatile(),
14911                                   Ld->isNonTemporal(), Ld->isInvariant(),
14912                                   Ld->getAlignment());
14913       SDValue NewChain = NewLd.getValue(1);
14914       if (TokenFactorIndex != -1) {
14915         Ops.push_back(NewChain);
14916         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14917                                Ops.size());
14918       }
14919       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14920                           St->getPointerInfo(),
14921                           St->isVolatile(), St->isNonTemporal(),
14922                           St->getAlignment());
14923     }
14924
14925     // Otherwise, lower to two pairs of 32-bit loads / stores.
14926     SDValue LoAddr = Ld->getBasePtr();
14927     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14928                                  DAG.getConstant(4, MVT::i32));
14929
14930     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14931                                Ld->getPointerInfo(),
14932                                Ld->isVolatile(), Ld->isNonTemporal(),
14933                                Ld->isInvariant(), Ld->getAlignment());
14934     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14935                                Ld->getPointerInfo().getWithOffset(4),
14936                                Ld->isVolatile(), Ld->isNonTemporal(),
14937                                Ld->isInvariant(),
14938                                MinAlign(Ld->getAlignment(), 4));
14939
14940     SDValue NewChain = LoLd.getValue(1);
14941     if (TokenFactorIndex != -1) {
14942       Ops.push_back(LoLd);
14943       Ops.push_back(HiLd);
14944       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14945                              Ops.size());
14946     }
14947
14948     LoAddr = St->getBasePtr();
14949     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14950                          DAG.getConstant(4, MVT::i32));
14951
14952     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14953                                 St->getPointerInfo(),
14954                                 St->isVolatile(), St->isNonTemporal(),
14955                                 St->getAlignment());
14956     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14957                                 St->getPointerInfo().getWithOffset(4),
14958                                 St->isVolatile(),
14959                                 St->isNonTemporal(),
14960                                 MinAlign(St->getAlignment(), 4));
14961     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14962   }
14963   return SDValue();
14964 }
14965
14966 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14967 /// and return the operands for the horizontal operation in LHS and RHS.  A
14968 /// horizontal operation performs the binary operation on successive elements
14969 /// of its first operand, then on successive elements of its second operand,
14970 /// returning the resulting values in a vector.  For example, if
14971 ///   A = < float a0, float a1, float a2, float a3 >
14972 /// and
14973 ///   B = < float b0, float b1, float b2, float b3 >
14974 /// then the result of doing a horizontal operation on A and B is
14975 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14976 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14977 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14978 /// set to A, RHS to B, and the routine returns 'true'.
14979 /// Note that the binary operation should have the property that if one of the
14980 /// operands is UNDEF then the result is UNDEF.
14981 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14982   // Look for the following pattern: if
14983   //   A = < float a0, float a1, float a2, float a3 >
14984   //   B = < float b0, float b1, float b2, float b3 >
14985   // and
14986   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14987   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14988   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14989   // which is A horizontal-op B.
14990
14991   // At least one of the operands should be a vector shuffle.
14992   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14993       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14994     return false;
14995
14996   EVT VT = LHS.getValueType();
14997
14998   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14999          "Unsupported vector type for horizontal add/sub");
15000
15001   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15002   // operate independently on 128-bit lanes.
15003   unsigned NumElts = VT.getVectorNumElements();
15004   unsigned NumLanes = VT.getSizeInBits()/128;
15005   unsigned NumLaneElts = NumElts / NumLanes;
15006   assert((NumLaneElts % 2 == 0) &&
15007          "Vector type should have an even number of elements in each lane");
15008   unsigned HalfLaneElts = NumLaneElts/2;
15009
15010   // View LHS in the form
15011   //   LHS = VECTOR_SHUFFLE A, B, LMask
15012   // If LHS is not a shuffle then pretend it is the shuffle
15013   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15014   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15015   // type VT.
15016   SDValue A, B;
15017   SmallVector<int, 16> LMask(NumElts);
15018   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15019     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15020       A = LHS.getOperand(0);
15021     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15022       B = LHS.getOperand(1);
15023     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15024     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15025   } else {
15026     if (LHS.getOpcode() != ISD::UNDEF)
15027       A = LHS;
15028     for (unsigned i = 0; i != NumElts; ++i)
15029       LMask[i] = i;
15030   }
15031
15032   // Likewise, view RHS in the form
15033   //   RHS = VECTOR_SHUFFLE C, D, RMask
15034   SDValue C, D;
15035   SmallVector<int, 16> RMask(NumElts);
15036   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15037     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15038       C = RHS.getOperand(0);
15039     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15040       D = RHS.getOperand(1);
15041     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15042     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15043   } else {
15044     if (RHS.getOpcode() != ISD::UNDEF)
15045       C = RHS;
15046     for (unsigned i = 0; i != NumElts; ++i)
15047       RMask[i] = i;
15048   }
15049
15050   // Check that the shuffles are both shuffling the same vectors.
15051   if (!(A == C && B == D) && !(A == D && B == C))
15052     return false;
15053
15054   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15055   if (!A.getNode() && !B.getNode())
15056     return false;
15057
15058   // If A and B occur in reverse order in RHS, then "swap" them (which means
15059   // rewriting the mask).
15060   if (A != C)
15061     CommuteVectorShuffleMask(RMask, NumElts);
15062
15063   // At this point LHS and RHS are equivalent to
15064   //   LHS = VECTOR_SHUFFLE A, B, LMask
15065   //   RHS = VECTOR_SHUFFLE A, B, RMask
15066   // Check that the masks correspond to performing a horizontal operation.
15067   for (unsigned i = 0; i != NumElts; ++i) {
15068     int LIdx = LMask[i], RIdx = RMask[i];
15069
15070     // Ignore any UNDEF components.
15071     if (LIdx < 0 || RIdx < 0 ||
15072         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15073         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15074       continue;
15075
15076     // Check that successive elements are being operated on.  If not, this is
15077     // not a horizontal operation.
15078     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15079     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15080     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15081     if (!(LIdx == Index && RIdx == Index + 1) &&
15082         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15083       return false;
15084   }
15085
15086   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15087   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15088   return true;
15089 }
15090
15091 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15092 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15093                                   const X86Subtarget *Subtarget) {
15094   EVT VT = N->getValueType(0);
15095   SDValue LHS = N->getOperand(0);
15096   SDValue RHS = N->getOperand(1);
15097
15098   // Try to synthesize horizontal adds from adds of shuffles.
15099   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15100        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15101       isHorizontalBinOp(LHS, RHS, true))
15102     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15103   return SDValue();
15104 }
15105
15106 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15107 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15108                                   const X86Subtarget *Subtarget) {
15109   EVT VT = N->getValueType(0);
15110   SDValue LHS = N->getOperand(0);
15111   SDValue RHS = N->getOperand(1);
15112
15113   // Try to synthesize horizontal subs from subs of shuffles.
15114   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15115        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15116       isHorizontalBinOp(LHS, RHS, false))
15117     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15118   return SDValue();
15119 }
15120
15121 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15122 /// X86ISD::FXOR nodes.
15123 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15124   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15125   // F[X]OR(0.0, x) -> x
15126   // F[X]OR(x, 0.0) -> x
15127   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15128     if (C->getValueAPF().isPosZero())
15129       return N->getOperand(1);
15130   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15131     if (C->getValueAPF().isPosZero())
15132       return N->getOperand(0);
15133   return SDValue();
15134 }
15135
15136 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15137 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15138   // FAND(0.0, x) -> 0.0
15139   // FAND(x, 0.0) -> 0.0
15140   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15141     if (C->getValueAPF().isPosZero())
15142       return N->getOperand(0);
15143   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15144     if (C->getValueAPF().isPosZero())
15145       return N->getOperand(1);
15146   return SDValue();
15147 }
15148
15149 static SDValue PerformBTCombine(SDNode *N,
15150                                 SelectionDAG &DAG,
15151                                 TargetLowering::DAGCombinerInfo &DCI) {
15152   // BT ignores high bits in the bit index operand.
15153   SDValue Op1 = N->getOperand(1);
15154   if (Op1.hasOneUse()) {
15155     unsigned BitWidth = Op1.getValueSizeInBits();
15156     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15157     APInt KnownZero, KnownOne;
15158     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15159                                           !DCI.isBeforeLegalizeOps());
15160     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15161     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15162         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15163       DCI.CommitTargetLoweringOpt(TLO);
15164   }
15165   return SDValue();
15166 }
15167
15168 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15169   SDValue Op = N->getOperand(0);
15170   if (Op.getOpcode() == ISD::BITCAST)
15171     Op = Op.getOperand(0);
15172   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15173   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15174       VT.getVectorElementType().getSizeInBits() ==
15175       OpVT.getVectorElementType().getSizeInBits()) {
15176     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15177   }
15178   return SDValue();
15179 }
15180
15181 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15182                                   TargetLowering::DAGCombinerInfo &DCI,
15183                                   const X86Subtarget *Subtarget) {
15184   if (!DCI.isBeforeLegalizeOps())
15185     return SDValue();
15186
15187   if (!Subtarget->hasAVX())
15188     return SDValue();
15189
15190   EVT VT = N->getValueType(0);
15191   SDValue Op = N->getOperand(0);
15192   EVT OpVT = Op.getValueType();
15193   DebugLoc dl = N->getDebugLoc();
15194
15195   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15196       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15197
15198     if (Subtarget->hasAVX2())
15199       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15200
15201     // Optimize vectors in AVX mode
15202     // Sign extend  v8i16 to v8i32 and
15203     //              v4i32 to v4i64
15204     //
15205     // Divide input vector into two parts
15206     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15207     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15208     // concat the vectors to original VT
15209
15210     unsigned NumElems = OpVT.getVectorNumElements();
15211     SmallVector<int,8> ShufMask1(NumElems, -1);
15212     for (unsigned i = 0; i != NumElems/2; ++i)
15213       ShufMask1[i] = i;
15214
15215     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15216                                         &ShufMask1[0]);
15217
15218     SmallVector<int,8> ShufMask2(NumElems, -1);
15219     for (unsigned i = 0; i != NumElems/2; ++i)
15220       ShufMask2[i] = i + NumElems/2;
15221
15222     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15223                                         &ShufMask2[0]);
15224
15225     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15226                                   VT.getVectorNumElements()/2);
15227
15228     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15229     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15230
15231     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15232   }
15233   return SDValue();
15234 }
15235
15236 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15237                                  const X86Subtarget* Subtarget) {
15238   DebugLoc dl = N->getDebugLoc();
15239   EVT VT = N->getValueType(0);
15240
15241   EVT ScalarVT = VT.getScalarType();
15242   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA())
15243     return SDValue();
15244
15245   SDValue A = N->getOperand(0);
15246   SDValue B = N->getOperand(1);
15247   SDValue C = N->getOperand(2);
15248
15249   bool NegA = (A.getOpcode() == ISD::FNEG);
15250   bool NegB = (B.getOpcode() == ISD::FNEG);
15251   bool NegC = (C.getOpcode() == ISD::FNEG);
15252
15253   // Negative multiplication when NegA xor NegB
15254   bool NegMul = (NegA != NegB);
15255   if (NegA)
15256     A = A.getOperand(0);
15257   if (NegB)
15258     B = B.getOperand(0);
15259   if (NegC)
15260     C = C.getOperand(0);
15261
15262   unsigned Opcode;
15263   if (!NegMul)
15264     Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB;
15265   else
15266     Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB;
15267   return DAG.getNode(Opcode, dl, VT, A, B, C);
15268 }
15269
15270 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15271                                   TargetLowering::DAGCombinerInfo &DCI,
15272                                   const X86Subtarget *Subtarget) {
15273   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15274   //           (and (i32 x86isd::setcc_carry), 1)
15275   // This eliminates the zext. This transformation is necessary because
15276   // ISD::SETCC is always legalized to i8.
15277   DebugLoc dl = N->getDebugLoc();
15278   SDValue N0 = N->getOperand(0);
15279   EVT VT = N->getValueType(0);
15280   EVT OpVT = N0.getValueType();
15281
15282   if (N0.getOpcode() == ISD::AND &&
15283       N0.hasOneUse() &&
15284       N0.getOperand(0).hasOneUse()) {
15285     SDValue N00 = N0.getOperand(0);
15286     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15287       return SDValue();
15288     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15289     if (!C || C->getZExtValue() != 1)
15290       return SDValue();
15291     return DAG.getNode(ISD::AND, dl, VT,
15292                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15293                                    N00.getOperand(0), N00.getOperand(1)),
15294                        DAG.getConstant(1, VT));
15295   }
15296
15297   // Optimize vectors in AVX mode:
15298   //
15299   //   v8i16 -> v8i32
15300   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15301   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15302   //   Concat upper and lower parts.
15303   //
15304   //   v4i32 -> v4i64
15305   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15306   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15307   //   Concat upper and lower parts.
15308   //
15309   if (!DCI.isBeforeLegalizeOps())
15310     return SDValue();
15311
15312   if (!Subtarget->hasAVX())
15313     return SDValue();
15314
15315   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15316       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15317
15318     if (Subtarget->hasAVX2())
15319       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15320
15321     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15322     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15323     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15324
15325     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15326                                VT.getVectorNumElements()/2);
15327
15328     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15329     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15330
15331     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15332   }
15333
15334   return SDValue();
15335 }
15336
15337 // Optimize x == -y --> x+y == 0
15338 //          x != -y --> x+y != 0
15339 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15340   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15341   SDValue LHS = N->getOperand(0);
15342   SDValue RHS = N->getOperand(1);
15343
15344   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15345     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15346       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15347         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15348                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15349         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15350                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15351       }
15352   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15353     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15354       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15355         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15356                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15357         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15358                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15359       }
15360   return SDValue();
15361 }
15362
15363 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15364 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15365   DebugLoc DL = N->getDebugLoc();
15366   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15367   SDValue EFLAGS = N->getOperand(1);
15368
15369   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15370   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15371   // cases.
15372   if (CC == X86::COND_B)
15373     return DAG.getNode(ISD::AND, DL, MVT::i8,
15374                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15375                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15376                        DAG.getConstant(1, MVT::i8));
15377
15378   SDValue Flags;
15379
15380   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15381   if (Flags.getNode()) {
15382     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15383     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15384   }
15385
15386   return SDValue();
15387 }
15388
15389 // Optimize branch condition evaluation.
15390 //
15391 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15392                                     TargetLowering::DAGCombinerInfo &DCI,
15393                                     const X86Subtarget *Subtarget) {
15394   DebugLoc DL = N->getDebugLoc();
15395   SDValue Chain = N->getOperand(0);
15396   SDValue Dest = N->getOperand(1);
15397   SDValue EFLAGS = N->getOperand(3);
15398   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15399
15400   SDValue Flags;
15401
15402   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15403   if (Flags.getNode()) {
15404     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15405     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15406                        Flags);
15407   }
15408
15409   return SDValue();
15410 }
15411
15412 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15413   SDValue Op0 = N->getOperand(0);
15414   EVT InVT = Op0->getValueType(0);
15415
15416   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15417   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15418     DebugLoc dl = N->getDebugLoc();
15419     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15420     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15421     // Notice that we use SINT_TO_FP because we know that the high bits
15422     // are zero and SINT_TO_FP is better supported by the hardware.
15423     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15424   }
15425
15426   return SDValue();
15427 }
15428
15429 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15430                                         const X86TargetLowering *XTLI) {
15431   SDValue Op0 = N->getOperand(0);
15432   EVT InVT = Op0->getValueType(0);
15433
15434   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15435   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15436     DebugLoc dl = N->getDebugLoc();
15437     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15438     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15439     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15440   }
15441
15442   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15443   // a 32-bit target where SSE doesn't support i64->FP operations.
15444   if (Op0.getOpcode() == ISD::LOAD) {
15445     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15446     EVT VT = Ld->getValueType(0);
15447     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15448         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15449         !XTLI->getSubtarget()->is64Bit() &&
15450         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15451       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15452                                           Ld->getChain(), Op0, DAG);
15453       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15454       return FILDChain;
15455     }
15456   }
15457   return SDValue();
15458 }
15459
15460 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15461   EVT VT = N->getValueType(0);
15462
15463   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15464   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15465     DebugLoc dl = N->getDebugLoc();
15466     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15467     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15468     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15469   }
15470
15471   return SDValue();
15472 }
15473
15474 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15475 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15476                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15477   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15478   // the result is either zero or one (depending on the input carry bit).
15479   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15480   if (X86::isZeroNode(N->getOperand(0)) &&
15481       X86::isZeroNode(N->getOperand(1)) &&
15482       // We don't have a good way to replace an EFLAGS use, so only do this when
15483       // dead right now.
15484       SDValue(N, 1).use_empty()) {
15485     DebugLoc DL = N->getDebugLoc();
15486     EVT VT = N->getValueType(0);
15487     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15488     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15489                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15490                                            DAG.getConstant(X86::COND_B,MVT::i8),
15491                                            N->getOperand(2)),
15492                                DAG.getConstant(1, VT));
15493     return DCI.CombineTo(N, Res1, CarryOut);
15494   }
15495
15496   return SDValue();
15497 }
15498
15499 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15500 //      (add Y, (setne X, 0)) -> sbb -1, Y
15501 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15502 //      (sub (setne X, 0), Y) -> adc -1, Y
15503 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15504   DebugLoc DL = N->getDebugLoc();
15505
15506   // Look through ZExts.
15507   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15508   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15509     return SDValue();
15510
15511   SDValue SetCC = Ext.getOperand(0);
15512   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15513     return SDValue();
15514
15515   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15516   if (CC != X86::COND_E && CC != X86::COND_NE)
15517     return SDValue();
15518
15519   SDValue Cmp = SetCC.getOperand(1);
15520   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15521       !X86::isZeroNode(Cmp.getOperand(1)) ||
15522       !Cmp.getOperand(0).getValueType().isInteger())
15523     return SDValue();
15524
15525   SDValue CmpOp0 = Cmp.getOperand(0);
15526   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15527                                DAG.getConstant(1, CmpOp0.getValueType()));
15528
15529   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15530   if (CC == X86::COND_NE)
15531     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15532                        DL, OtherVal.getValueType(), OtherVal,
15533                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15534   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15535                      DL, OtherVal.getValueType(), OtherVal,
15536                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15537 }
15538
15539 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15540 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15541                                  const X86Subtarget *Subtarget) {
15542   EVT VT = N->getValueType(0);
15543   SDValue Op0 = N->getOperand(0);
15544   SDValue Op1 = N->getOperand(1);
15545
15546   // Try to synthesize horizontal adds from adds of shuffles.
15547   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15548        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15549       isHorizontalBinOp(Op0, Op1, true))
15550     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15551
15552   return OptimizeConditionalInDecrement(N, DAG);
15553 }
15554
15555 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15556                                  const X86Subtarget *Subtarget) {
15557   SDValue Op0 = N->getOperand(0);
15558   SDValue Op1 = N->getOperand(1);
15559
15560   // X86 can't encode an immediate LHS of a sub. See if we can push the
15561   // negation into a preceding instruction.
15562   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15563     // If the RHS of the sub is a XOR with one use and a constant, invert the
15564     // immediate. Then add one to the LHS of the sub so we can turn
15565     // X-Y -> X+~Y+1, saving one register.
15566     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15567         isa<ConstantSDNode>(Op1.getOperand(1))) {
15568       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15569       EVT VT = Op0.getValueType();
15570       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15571                                    Op1.getOperand(0),
15572                                    DAG.getConstant(~XorC, VT));
15573       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15574                          DAG.getConstant(C->getAPIntValue()+1, VT));
15575     }
15576   }
15577
15578   // Try to synthesize horizontal adds from adds of shuffles.
15579   EVT VT = N->getValueType(0);
15580   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15581        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15582       isHorizontalBinOp(Op0, Op1, true))
15583     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15584
15585   return OptimizeConditionalInDecrement(N, DAG);
15586 }
15587
15588 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15589                                              DAGCombinerInfo &DCI) const {
15590   SelectionDAG &DAG = DCI.DAG;
15591   switch (N->getOpcode()) {
15592   default: break;
15593   case ISD::EXTRACT_VECTOR_ELT:
15594     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15595   case ISD::VSELECT:
15596   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15597   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15598   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15599   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15600   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15601   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15602   case ISD::SHL:
15603   case ISD::SRA:
15604   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15605   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15606   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15607   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15608   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
15609   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15610   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15611   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15612   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15613   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15614   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15615   case X86ISD::FXOR:
15616   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15617   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15618   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15619   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15620   case ISD::ANY_EXTEND:
15621   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15622   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15623   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15624   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15625   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15626   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
15627   case X86ISD::SHUFP:       // Handle all target specific shuffles
15628   case X86ISD::PALIGN:
15629   case X86ISD::UNPCKH:
15630   case X86ISD::UNPCKL:
15631   case X86ISD::MOVHLPS:
15632   case X86ISD::MOVLHPS:
15633   case X86ISD::PSHUFD:
15634   case X86ISD::PSHUFHW:
15635   case X86ISD::PSHUFLW:
15636   case X86ISD::MOVSS:
15637   case X86ISD::MOVSD:
15638   case X86ISD::VPERMILP:
15639   case X86ISD::VPERM2X128:
15640   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15641   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
15642   }
15643
15644   return SDValue();
15645 }
15646
15647 /// isTypeDesirableForOp - Return true if the target has native support for
15648 /// the specified value type and it is 'desirable' to use the type for the
15649 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15650 /// instruction encodings are longer and some i16 instructions are slow.
15651 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15652   if (!isTypeLegal(VT))
15653     return false;
15654   if (VT != MVT::i16)
15655     return true;
15656
15657   switch (Opc) {
15658   default:
15659     return true;
15660   case ISD::LOAD:
15661   case ISD::SIGN_EXTEND:
15662   case ISD::ZERO_EXTEND:
15663   case ISD::ANY_EXTEND:
15664   case ISD::SHL:
15665   case ISD::SRL:
15666   case ISD::SUB:
15667   case ISD::ADD:
15668   case ISD::MUL:
15669   case ISD::AND:
15670   case ISD::OR:
15671   case ISD::XOR:
15672     return false;
15673   }
15674 }
15675
15676 /// IsDesirableToPromoteOp - This method query the target whether it is
15677 /// beneficial for dag combiner to promote the specified node. If true, it
15678 /// should return the desired promotion type by reference.
15679 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15680   EVT VT = Op.getValueType();
15681   if (VT != MVT::i16)
15682     return false;
15683
15684   bool Promote = false;
15685   bool Commute = false;
15686   switch (Op.getOpcode()) {
15687   default: break;
15688   case ISD::LOAD: {
15689     LoadSDNode *LD = cast<LoadSDNode>(Op);
15690     // If the non-extending load has a single use and it's not live out, then it
15691     // might be folded.
15692     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15693                                                      Op.hasOneUse()*/) {
15694       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15695              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15696         // The only case where we'd want to promote LOAD (rather then it being
15697         // promoted as an operand is when it's only use is liveout.
15698         if (UI->getOpcode() != ISD::CopyToReg)
15699           return false;
15700       }
15701     }
15702     Promote = true;
15703     break;
15704   }
15705   case ISD::SIGN_EXTEND:
15706   case ISD::ZERO_EXTEND:
15707   case ISD::ANY_EXTEND:
15708     Promote = true;
15709     break;
15710   case ISD::SHL:
15711   case ISD::SRL: {
15712     SDValue N0 = Op.getOperand(0);
15713     // Look out for (store (shl (load), x)).
15714     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15715       return false;
15716     Promote = true;
15717     break;
15718   }
15719   case ISD::ADD:
15720   case ISD::MUL:
15721   case ISD::AND:
15722   case ISD::OR:
15723   case ISD::XOR:
15724     Commute = true;
15725     // fallthrough
15726   case ISD::SUB: {
15727     SDValue N0 = Op.getOperand(0);
15728     SDValue N1 = Op.getOperand(1);
15729     if (!Commute && MayFoldLoad(N1))
15730       return false;
15731     // Avoid disabling potential load folding opportunities.
15732     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15733       return false;
15734     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15735       return false;
15736     Promote = true;
15737   }
15738   }
15739
15740   PVT = MVT::i32;
15741   return Promote;
15742 }
15743
15744 //===----------------------------------------------------------------------===//
15745 //                           X86 Inline Assembly Support
15746 //===----------------------------------------------------------------------===//
15747
15748 namespace {
15749   // Helper to match a string separated by whitespace.
15750   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15751     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15752
15753     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15754       StringRef piece(*args[i]);
15755       if (!s.startswith(piece)) // Check if the piece matches.
15756         return false;
15757
15758       s = s.substr(piece.size());
15759       StringRef::size_type pos = s.find_first_not_of(" \t");
15760       if (pos == 0) // We matched a prefix.
15761         return false;
15762
15763       s = s.substr(pos);
15764     }
15765
15766     return s.empty();
15767   }
15768   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15769 }
15770
15771 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15772   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15773
15774   std::string AsmStr = IA->getAsmString();
15775
15776   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15777   if (!Ty || Ty->getBitWidth() % 16 != 0)
15778     return false;
15779
15780   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15781   SmallVector<StringRef, 4> AsmPieces;
15782   SplitString(AsmStr, AsmPieces, ";\n");
15783
15784   switch (AsmPieces.size()) {
15785   default: return false;
15786   case 1:
15787     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15788     // we will turn this bswap into something that will be lowered to logical
15789     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15790     // lower so don't worry about this.
15791     // bswap $0
15792     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15793         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15794         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15795         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15796         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15797         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15798       // No need to check constraints, nothing other than the equivalent of
15799       // "=r,0" would be valid here.
15800       return IntrinsicLowering::LowerToByteSwap(CI);
15801     }
15802
15803     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15804     if (CI->getType()->isIntegerTy(16) &&
15805         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15806         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15807          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15808       AsmPieces.clear();
15809       const std::string &ConstraintsStr = IA->getConstraintString();
15810       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15811       std::sort(AsmPieces.begin(), AsmPieces.end());
15812       if (AsmPieces.size() == 4 &&
15813           AsmPieces[0] == "~{cc}" &&
15814           AsmPieces[1] == "~{dirflag}" &&
15815           AsmPieces[2] == "~{flags}" &&
15816           AsmPieces[3] == "~{fpsr}")
15817       return IntrinsicLowering::LowerToByteSwap(CI);
15818     }
15819     break;
15820   case 3:
15821     if (CI->getType()->isIntegerTy(32) &&
15822         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15823         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15824         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15825         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15826       AsmPieces.clear();
15827       const std::string &ConstraintsStr = IA->getConstraintString();
15828       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15829       std::sort(AsmPieces.begin(), AsmPieces.end());
15830       if (AsmPieces.size() == 4 &&
15831           AsmPieces[0] == "~{cc}" &&
15832           AsmPieces[1] == "~{dirflag}" &&
15833           AsmPieces[2] == "~{flags}" &&
15834           AsmPieces[3] == "~{fpsr}")
15835         return IntrinsicLowering::LowerToByteSwap(CI);
15836     }
15837
15838     if (CI->getType()->isIntegerTy(64)) {
15839       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15840       if (Constraints.size() >= 2 &&
15841           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15842           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15843         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15844         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15845             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15846             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15847           return IntrinsicLowering::LowerToByteSwap(CI);
15848       }
15849     }
15850     break;
15851   }
15852   return false;
15853 }
15854
15855
15856
15857 /// getConstraintType - Given a constraint letter, return the type of
15858 /// constraint it is for this target.
15859 X86TargetLowering::ConstraintType
15860 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15861   if (Constraint.size() == 1) {
15862     switch (Constraint[0]) {
15863     case 'R':
15864     case 'q':
15865     case 'Q':
15866     case 'f':
15867     case 't':
15868     case 'u':
15869     case 'y':
15870     case 'x':
15871     case 'Y':
15872     case 'l':
15873       return C_RegisterClass;
15874     case 'a':
15875     case 'b':
15876     case 'c':
15877     case 'd':
15878     case 'S':
15879     case 'D':
15880     case 'A':
15881       return C_Register;
15882     case 'I':
15883     case 'J':
15884     case 'K':
15885     case 'L':
15886     case 'M':
15887     case 'N':
15888     case 'G':
15889     case 'C':
15890     case 'e':
15891     case 'Z':
15892       return C_Other;
15893     default:
15894       break;
15895     }
15896   }
15897   return TargetLowering::getConstraintType(Constraint);
15898 }
15899
15900 /// Examine constraint type and operand type and determine a weight value.
15901 /// This object must already have been set up with the operand type
15902 /// and the current alternative constraint selected.
15903 TargetLowering::ConstraintWeight
15904   X86TargetLowering::getSingleConstraintMatchWeight(
15905     AsmOperandInfo &info, const char *constraint) const {
15906   ConstraintWeight weight = CW_Invalid;
15907   Value *CallOperandVal = info.CallOperandVal;
15908     // If we don't have a value, we can't do a match,
15909     // but allow it at the lowest weight.
15910   if (CallOperandVal == NULL)
15911     return CW_Default;
15912   Type *type = CallOperandVal->getType();
15913   // Look at the constraint type.
15914   switch (*constraint) {
15915   default:
15916     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15917   case 'R':
15918   case 'q':
15919   case 'Q':
15920   case 'a':
15921   case 'b':
15922   case 'c':
15923   case 'd':
15924   case 'S':
15925   case 'D':
15926   case 'A':
15927     if (CallOperandVal->getType()->isIntegerTy())
15928       weight = CW_SpecificReg;
15929     break;
15930   case 'f':
15931   case 't':
15932   case 'u':
15933       if (type->isFloatingPointTy())
15934         weight = CW_SpecificReg;
15935       break;
15936   case 'y':
15937       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15938         weight = CW_SpecificReg;
15939       break;
15940   case 'x':
15941   case 'Y':
15942     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15943         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15944       weight = CW_Register;
15945     break;
15946   case 'I':
15947     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15948       if (C->getZExtValue() <= 31)
15949         weight = CW_Constant;
15950     }
15951     break;
15952   case 'J':
15953     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15954       if (C->getZExtValue() <= 63)
15955         weight = CW_Constant;
15956     }
15957     break;
15958   case 'K':
15959     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15960       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15961         weight = CW_Constant;
15962     }
15963     break;
15964   case 'L':
15965     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15966       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15967         weight = CW_Constant;
15968     }
15969     break;
15970   case 'M':
15971     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15972       if (C->getZExtValue() <= 3)
15973         weight = CW_Constant;
15974     }
15975     break;
15976   case 'N':
15977     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15978       if (C->getZExtValue() <= 0xff)
15979         weight = CW_Constant;
15980     }
15981     break;
15982   case 'G':
15983   case 'C':
15984     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15985       weight = CW_Constant;
15986     }
15987     break;
15988   case 'e':
15989     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15990       if ((C->getSExtValue() >= -0x80000000LL) &&
15991           (C->getSExtValue() <= 0x7fffffffLL))
15992         weight = CW_Constant;
15993     }
15994     break;
15995   case 'Z':
15996     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15997       if (C->getZExtValue() <= 0xffffffff)
15998         weight = CW_Constant;
15999     }
16000     break;
16001   }
16002   return weight;
16003 }
16004
16005 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16006 /// with another that has more specific requirements based on the type of the
16007 /// corresponding operand.
16008 const char *X86TargetLowering::
16009 LowerXConstraint(EVT ConstraintVT) const {
16010   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16011   // 'f' like normal targets.
16012   if (ConstraintVT.isFloatingPoint()) {
16013     if (Subtarget->hasSSE2())
16014       return "Y";
16015     if (Subtarget->hasSSE1())
16016       return "x";
16017   }
16018
16019   return TargetLowering::LowerXConstraint(ConstraintVT);
16020 }
16021
16022 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16023 /// vector.  If it is invalid, don't add anything to Ops.
16024 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16025                                                      std::string &Constraint,
16026                                                      std::vector<SDValue>&Ops,
16027                                                      SelectionDAG &DAG) const {
16028   SDValue Result(0, 0);
16029
16030   // Only support length 1 constraints for now.
16031   if (Constraint.length() > 1) return;
16032
16033   char ConstraintLetter = Constraint[0];
16034   switch (ConstraintLetter) {
16035   default: break;
16036   case 'I':
16037     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16038       if (C->getZExtValue() <= 31) {
16039         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16040         break;
16041       }
16042     }
16043     return;
16044   case 'J':
16045     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16046       if (C->getZExtValue() <= 63) {
16047         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16048         break;
16049       }
16050     }
16051     return;
16052   case 'K':
16053     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16054       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16055         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16056         break;
16057       }
16058     }
16059     return;
16060   case 'N':
16061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16062       if (C->getZExtValue() <= 255) {
16063         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16064         break;
16065       }
16066     }
16067     return;
16068   case 'e': {
16069     // 32-bit signed value
16070     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16071       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16072                                            C->getSExtValue())) {
16073         // Widen to 64 bits here to get it sign extended.
16074         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16075         break;
16076       }
16077     // FIXME gcc accepts some relocatable values here too, but only in certain
16078     // memory models; it's complicated.
16079     }
16080     return;
16081   }
16082   case 'Z': {
16083     // 32-bit unsigned value
16084     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16085       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16086                                            C->getZExtValue())) {
16087         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16088         break;
16089       }
16090     }
16091     // FIXME gcc accepts some relocatable values here too, but only in certain
16092     // memory models; it's complicated.
16093     return;
16094   }
16095   case 'i': {
16096     // Literal immediates are always ok.
16097     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16098       // Widen to 64 bits here to get it sign extended.
16099       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16100       break;
16101     }
16102
16103     // In any sort of PIC mode addresses need to be computed at runtime by
16104     // adding in a register or some sort of table lookup.  These can't
16105     // be used as immediates.
16106     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16107       return;
16108
16109     // If we are in non-pic codegen mode, we allow the address of a global (with
16110     // an optional displacement) to be used with 'i'.
16111     GlobalAddressSDNode *GA = 0;
16112     int64_t Offset = 0;
16113
16114     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16115     while (1) {
16116       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16117         Offset += GA->getOffset();
16118         break;
16119       } else if (Op.getOpcode() == ISD::ADD) {
16120         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16121           Offset += C->getZExtValue();
16122           Op = Op.getOperand(0);
16123           continue;
16124         }
16125       } else if (Op.getOpcode() == ISD::SUB) {
16126         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16127           Offset += -C->getZExtValue();
16128           Op = Op.getOperand(0);
16129           continue;
16130         }
16131       }
16132
16133       // Otherwise, this isn't something we can handle, reject it.
16134       return;
16135     }
16136
16137     const GlobalValue *GV = GA->getGlobal();
16138     // If we require an extra load to get this address, as in PIC mode, we
16139     // can't accept it.
16140     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16141                                                         getTargetMachine())))
16142       return;
16143
16144     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16145                                         GA->getValueType(0), Offset);
16146     break;
16147   }
16148   }
16149
16150   if (Result.getNode()) {
16151     Ops.push_back(Result);
16152     return;
16153   }
16154   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16155 }
16156
16157 std::pair<unsigned, const TargetRegisterClass*>
16158 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16159                                                 EVT VT) const {
16160   // First, see if this is a constraint that directly corresponds to an LLVM
16161   // register class.
16162   if (Constraint.size() == 1) {
16163     // GCC Constraint Letters
16164     switch (Constraint[0]) {
16165     default: break;
16166       // TODO: Slight differences here in allocation order and leaving
16167       // RIP in the class. Do they matter any more here than they do
16168       // in the normal allocation?
16169     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16170       if (Subtarget->is64Bit()) {
16171         if (VT == MVT::i32 || VT == MVT::f32)
16172           return std::make_pair(0U, &X86::GR32RegClass);
16173         if (VT == MVT::i16)
16174           return std::make_pair(0U, &X86::GR16RegClass);
16175         if (VT == MVT::i8 || VT == MVT::i1)
16176           return std::make_pair(0U, &X86::GR8RegClass);
16177         if (VT == MVT::i64 || VT == MVT::f64)
16178           return std::make_pair(0U, &X86::GR64RegClass);
16179         break;
16180       }
16181       // 32-bit fallthrough
16182     case 'Q':   // Q_REGS
16183       if (VT == MVT::i32 || VT == MVT::f32)
16184         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16185       if (VT == MVT::i16)
16186         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16187       if (VT == MVT::i8 || VT == MVT::i1)
16188         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16189       if (VT == MVT::i64)
16190         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16191       break;
16192     case 'r':   // GENERAL_REGS
16193     case 'l':   // INDEX_REGS
16194       if (VT == MVT::i8 || VT == MVT::i1)
16195         return std::make_pair(0U, &X86::GR8RegClass);
16196       if (VT == MVT::i16)
16197         return std::make_pair(0U, &X86::GR16RegClass);
16198       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16199         return std::make_pair(0U, &X86::GR32RegClass);
16200       return std::make_pair(0U, &X86::GR64RegClass);
16201     case 'R':   // LEGACY_REGS
16202       if (VT == MVT::i8 || VT == MVT::i1)
16203         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16204       if (VT == MVT::i16)
16205         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16206       if (VT == MVT::i32 || !Subtarget->is64Bit())
16207         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16208       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16209     case 'f':  // FP Stack registers.
16210       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16211       // value to the correct fpstack register class.
16212       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16213         return std::make_pair(0U, &X86::RFP32RegClass);
16214       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16215         return std::make_pair(0U, &X86::RFP64RegClass);
16216       return std::make_pair(0U, &X86::RFP80RegClass);
16217     case 'y':   // MMX_REGS if MMX allowed.
16218       if (!Subtarget->hasMMX()) break;
16219       return std::make_pair(0U, &X86::VR64RegClass);
16220     case 'Y':   // SSE_REGS if SSE2 allowed
16221       if (!Subtarget->hasSSE2()) break;
16222       // FALL THROUGH.
16223     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16224       if (!Subtarget->hasSSE1()) break;
16225
16226       switch (VT.getSimpleVT().SimpleTy) {
16227       default: break;
16228       // Scalar SSE types.
16229       case MVT::f32:
16230       case MVT::i32:
16231         return std::make_pair(0U, &X86::FR32RegClass);
16232       case MVT::f64:
16233       case MVT::i64:
16234         return std::make_pair(0U, &X86::FR64RegClass);
16235       // Vector types.
16236       case MVT::v16i8:
16237       case MVT::v8i16:
16238       case MVT::v4i32:
16239       case MVT::v2i64:
16240       case MVT::v4f32:
16241       case MVT::v2f64:
16242         return std::make_pair(0U, &X86::VR128RegClass);
16243       // AVX types.
16244       case MVT::v32i8:
16245       case MVT::v16i16:
16246       case MVT::v8i32:
16247       case MVT::v4i64:
16248       case MVT::v8f32:
16249       case MVT::v4f64:
16250         return std::make_pair(0U, &X86::VR256RegClass);
16251       }
16252       break;
16253     }
16254   }
16255
16256   // Use the default implementation in TargetLowering to convert the register
16257   // constraint into a member of a register class.
16258   std::pair<unsigned, const TargetRegisterClass*> Res;
16259   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16260
16261   // Not found as a standard register?
16262   if (Res.second == 0) {
16263     // Map st(0) -> st(7) -> ST0
16264     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16265         tolower(Constraint[1]) == 's' &&
16266         tolower(Constraint[2]) == 't' &&
16267         Constraint[3] == '(' &&
16268         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16269         Constraint[5] == ')' &&
16270         Constraint[6] == '}') {
16271
16272       Res.first = X86::ST0+Constraint[4]-'0';
16273       Res.second = &X86::RFP80RegClass;
16274       return Res;
16275     }
16276
16277     // GCC allows "st(0)" to be called just plain "st".
16278     if (StringRef("{st}").equals_lower(Constraint)) {
16279       Res.first = X86::ST0;
16280       Res.second = &X86::RFP80RegClass;
16281       return Res;
16282     }
16283
16284     // flags -> EFLAGS
16285     if (StringRef("{flags}").equals_lower(Constraint)) {
16286       Res.first = X86::EFLAGS;
16287       Res.second = &X86::CCRRegClass;
16288       return Res;
16289     }
16290
16291     // 'A' means EAX + EDX.
16292     if (Constraint == "A") {
16293       Res.first = X86::EAX;
16294       Res.second = &X86::GR32_ADRegClass;
16295       return Res;
16296     }
16297     return Res;
16298   }
16299
16300   // Otherwise, check to see if this is a register class of the wrong value
16301   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16302   // turn into {ax},{dx}.
16303   if (Res.second->hasType(VT))
16304     return Res;   // Correct type already, nothing to do.
16305
16306   // All of the single-register GCC register classes map their values onto
16307   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16308   // really want an 8-bit or 32-bit register, map to the appropriate register
16309   // class and return the appropriate register.
16310   if (Res.second == &X86::GR16RegClass) {
16311     if (VT == MVT::i8) {
16312       unsigned DestReg = 0;
16313       switch (Res.first) {
16314       default: break;
16315       case X86::AX: DestReg = X86::AL; break;
16316       case X86::DX: DestReg = X86::DL; break;
16317       case X86::CX: DestReg = X86::CL; break;
16318       case X86::BX: DestReg = X86::BL; break;
16319       }
16320       if (DestReg) {
16321         Res.first = DestReg;
16322         Res.second = &X86::GR8RegClass;
16323       }
16324     } else if (VT == MVT::i32) {
16325       unsigned DestReg = 0;
16326       switch (Res.first) {
16327       default: break;
16328       case X86::AX: DestReg = X86::EAX; break;
16329       case X86::DX: DestReg = X86::EDX; break;
16330       case X86::CX: DestReg = X86::ECX; break;
16331       case X86::BX: DestReg = X86::EBX; break;
16332       case X86::SI: DestReg = X86::ESI; break;
16333       case X86::DI: DestReg = X86::EDI; break;
16334       case X86::BP: DestReg = X86::EBP; break;
16335       case X86::SP: DestReg = X86::ESP; break;
16336       }
16337       if (DestReg) {
16338         Res.first = DestReg;
16339         Res.second = &X86::GR32RegClass;
16340       }
16341     } else if (VT == MVT::i64) {
16342       unsigned DestReg = 0;
16343       switch (Res.first) {
16344       default: break;
16345       case X86::AX: DestReg = X86::RAX; break;
16346       case X86::DX: DestReg = X86::RDX; break;
16347       case X86::CX: DestReg = X86::RCX; break;
16348       case X86::BX: DestReg = X86::RBX; break;
16349       case X86::SI: DestReg = X86::RSI; break;
16350       case X86::DI: DestReg = X86::RDI; break;
16351       case X86::BP: DestReg = X86::RBP; break;
16352       case X86::SP: DestReg = X86::RSP; break;
16353       }
16354       if (DestReg) {
16355         Res.first = DestReg;
16356         Res.second = &X86::GR64RegClass;
16357       }
16358     }
16359   } else if (Res.second == &X86::FR32RegClass ||
16360              Res.second == &X86::FR64RegClass ||
16361              Res.second == &X86::VR128RegClass) {
16362     // Handle references to XMM physical registers that got mapped into the
16363     // wrong class.  This can happen with constraints like {xmm0} where the
16364     // target independent register mapper will just pick the first match it can
16365     // find, ignoring the required type.
16366
16367     if (VT == MVT::f32 || VT == MVT::i32)
16368       Res.second = &X86::FR32RegClass;
16369     else if (VT == MVT::f64 || VT == MVT::i64)
16370       Res.second = &X86::FR64RegClass;
16371     else if (X86::VR128RegClass.hasType(VT))
16372       Res.second = &X86::VR128RegClass;
16373     else if (X86::VR256RegClass.hasType(VT))
16374       Res.second = &X86::VR256RegClass;
16375   }
16376
16377   return Res;
16378 }