Make a bunch of lowering helper functions static instead of member functions. No...
[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.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   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   // Bypass i32 with i8 on Atom when compiling with O2
186   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187     addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
188
189   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190     // Setup Windows compiler runtime calls.
191     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193     setLibcallName(RTLIB::SREM_I64, "_allrem");
194     setLibcallName(RTLIB::UREM_I64, "_aullrem");
195     setLibcallName(RTLIB::MUL_I64, "_allmul");
196     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201
202     // The _ftol2 runtime function has an unusual calling conv, which
203     // is modeled by a special pseudo-instruction.
204     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, &X86::GR8RegClass);
225   addRegisterClass(MVT::i16, &X86::GR16RegClass);
226   addRegisterClass(MVT::i32, &X86::GR32RegClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257   } else if (!TM.Options.UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!TM.Options.UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!TM.Options.UseSoftFloat) {
315     // Since AVX is a superset of SSE3, only check for SSE here.
316     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317       // Expand FP_TO_UINT into a select.
318       // FIXME: We would like to use a Custom expander here eventually to do
319       // the optimal thing for SSE vs. the default expansion in the legalizer.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321     else
322       // With SSE3 we can use fisttpll to convert to a signed i64; without
323       // SSE, we're stuck with a fistpll.
324       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325   }
326
327   if (isTargetFTOL()) {
328     // Use the _ftol2 runtime function, which has a pseudo-instruction
329     // to handle its weird calling convention.
330     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331   }
332
333   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334   if (!X86ScalarSSEf64) {
335     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337     if (Subtarget->is64Bit()) {
338       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339       // Without SSE, i64->f64 goes through memory.
340       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341     }
342   }
343
344   // Scalar integer divide and remainder are lowered to use operations that
345   // produce two results, to match the available instructions. This exposes
346   // the two-result form to trivial CSE, which is able to combine x/y and x%y
347   // into a single instruction.
348   //
349   // Scalar integer multiply-high is also lowered to use two-result
350   // operations, to match the available instructions. However, plain multiply
351   // (low) operations are left as Legal, as there are single-result
352   // instructions for this in x86. Using the two-result multiply instructions
353   // when both high and low results are needed must be arranged by dagcombine.
354   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355     MVT VT = IntVTs[i];
356     setOperationAction(ISD::MULHS, VT, Expand);
357     setOperationAction(ISD::MULHU, VT, Expand);
358     setOperationAction(ISD::SDIV, VT, Expand);
359     setOperationAction(ISD::UDIV, VT, Expand);
360     setOperationAction(ISD::SREM, VT, Expand);
361     setOperationAction(ISD::UREM, VT, Expand);
362
363     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364     setOperationAction(ISD::ADDC, VT, Custom);
365     setOperationAction(ISD::ADDE, VT, Custom);
366     setOperationAction(ISD::SUBC, VT, Custom);
367     setOperationAction(ISD::SUBE, VT, Custom);
368   }
369
370   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374   if (Subtarget->is64Bit())
375     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385   // Promote the i8 variants and force them on up to i32 which has a shorter
386   // encoding.
387   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391   if (Subtarget->hasBMI()) {
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396   } else {
397     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399     if (Subtarget->is64Bit())
400       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401   }
402
403   if (Subtarget->hasLZCNT()) {
404     // When promoting the i8 variants, force them to i32 for a shorter
405     // encoding.
406     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412     if (Subtarget->is64Bit())
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414   } else {
415     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421     if (Subtarget->is64Bit()) {
422       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424     }
425   }
426
427   if (Subtarget->hasPOPCNT()) {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429   } else {
430     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433     if (Subtarget->is64Bit())
434       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435   }
436
437   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440   // These should be promoted to a larger select which is supported.
441   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442   // X86 wants to expand cmov itself.
443   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458   }
459   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460
461   // Darwin ABI issue.
462   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
463   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
464   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
465   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
469   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
470   if (Subtarget->is64Bit()) {
471     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
472     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
473     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
474     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
475     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
476   }
477   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
479   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
480   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
481   if (Subtarget->is64Bit()) {
482     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
483     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
484     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
485   }
486
487   if (Subtarget->hasSSE1())
488     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
489
490   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
491   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
492
493   // On X86 and X86-64, atomic operations are lowered to locked instructions.
494   // Locked instructions, in turn, have implicit fence semantics (all memory
495   // operations are flushed before issuing the locked instruction, and they
496   // are not buffered), so we can fold away the common pattern of
497   // fence-atomic-fence.
498   setShouldFoldAtomicFences(true);
499
500   // Expand certain atomics
501   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
502     MVT VT = IntVTs[i];
503     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506   }
507
508   if (!Subtarget->is64Bit()) {
509     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517   }
518
519   if (Subtarget->hasCmpxchg16b()) {
520     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
521   }
522
523   // FIXME - use subtarget debug flags
524   if (!Subtarget->isTargetDarwin() &&
525       !Subtarget->isTargetELF() &&
526       !Subtarget->isTargetCygMing()) {
527     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528   }
529
530   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
532   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
534   if (Subtarget->is64Bit()) {
535     setExceptionPointerRegister(X86::RAX);
536     setExceptionSelectorRegister(X86::RDX);
537   } else {
538     setExceptionPointerRegister(X86::EAX);
539     setExceptionSelectorRegister(X86::EDX);
540   }
541   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
543
544   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
546
547   setOperationAction(ISD::TRAP, MVT::Other, Legal);
548
549   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
551   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
552   if (Subtarget->is64Bit()) {
553     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
554     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
555   } else {
556     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
557     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
558   }
559
560   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
561   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
562
563   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565                        MVT::i64 : MVT::i32, Custom);
566   else if (TM.Options.EnableSegmentedStacks)
567     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568                        MVT::i64 : MVT::i32, Custom);
569   else
570     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571                        MVT::i64 : MVT::i32, Expand);
572
573   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574     // f32 and f64 use SSE.
575     // Set up the FP register classes.
576     addRegisterClass(MVT::f32, &X86::FR32RegClass);
577     addRegisterClass(MVT::f64, &X86::FR64RegClass);
578
579     // Use ANDPD to simulate FABS.
580     setOperationAction(ISD::FABS , MVT::f64, Custom);
581     setOperationAction(ISD::FABS , MVT::f32, Custom);
582
583     // Use XORP to simulate FNEG.
584     setOperationAction(ISD::FNEG , MVT::f64, Custom);
585     setOperationAction(ISD::FNEG , MVT::f32, Custom);
586
587     // Use ANDPD and ORPD to simulate FCOPYSIGN.
588     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
590
591     // Lower this to FGETSIGNx86 plus an AND.
592     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
594
595     // We don't support sin/cos/fmod
596     setOperationAction(ISD::FSIN , MVT::f64, Expand);
597     setOperationAction(ISD::FCOS , MVT::f64, Expand);
598     setOperationAction(ISD::FSIN , MVT::f32, Expand);
599     setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601     // Expand FP immediates into loads from the stack, except for the special
602     // cases we handle.
603     addLegalFPImmediate(APFloat(+0.0)); // xorpd
604     addLegalFPImmediate(APFloat(+0.0f)); // xorps
605   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606     // Use SSE for f32, x87 for f64.
607     // Set up the FP register classes.
608     addRegisterClass(MVT::f32, &X86::FR32RegClass);
609     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
610
611     // Use ANDPS to simulate FABS.
612     setOperationAction(ISD::FABS , MVT::f32, Custom);
613
614     // Use XORP to simulate FNEG.
615     setOperationAction(ISD::FNEG , MVT::f32, Custom);
616
617     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
618
619     // Use ANDPS and ORPS to simulate FCOPYSIGN.
620     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
622
623     // We don't support sin/cos/fmod
624     setOperationAction(ISD::FSIN , MVT::f32, Expand);
625     setOperationAction(ISD::FCOS , MVT::f32, Expand);
626
627     // Special cases we handle for FP constants.
628     addLegalFPImmediate(APFloat(+0.0f)); // xorps
629     addLegalFPImmediate(APFloat(+0.0)); // FLD0
630     addLegalFPImmediate(APFloat(+1.0)); // FLD1
631     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633
634     if (!TM.Options.UnsafeFPMath) {
635       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
636       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
637     }
638   } else if (!TM.Options.UseSoftFloat) {
639     // f32 and f64 in x87.
640     // Set up the FP register classes.
641     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
643
644     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
645     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
648
649     if (!TM.Options.UnsafeFPMath) {
650       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
651       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
652     }
653     addLegalFPImmediate(APFloat(+0.0)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
661   }
662
663   // We don't support FMA.
664   setOperationAction(ISD::FMA, MVT::f64, Expand);
665   setOperationAction(ISD::FMA, MVT::f32, Expand);
666
667   // Long double always uses X87.
668   if (!TM.Options.UseSoftFloat) {
669     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
672     {
673       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674       addLegalFPImmediate(TmpFlt);  // FLD0
675       TmpFlt.changeSign();
676       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
677
678       bool ignored;
679       APFloat TmpFlt2(+1.0);
680       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
681                       &ignored);
682       addLegalFPImmediate(TmpFlt2);  // FLD1
683       TmpFlt2.changeSign();
684       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
685     }
686
687     if (!TM.Options.UnsafeFPMath) {
688       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
689       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
690     }
691
692     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
694     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
696     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697     setOperationAction(ISD::FMA, MVT::f80, Expand);
698   }
699
700   // Always use a library call for pow.
701   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
702   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
703   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
704
705   setOperationAction(ISD::FLOG, MVT::f80, Expand);
706   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708   setOperationAction(ISD::FEXP, MVT::f80, Expand);
709   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
710
711   // First set operation action for all vector types to either promote
712   // (for widening) or expand (for scalarization). Then we will selectively
713   // turn on ones that can be effectively codegen'd.
714   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
775     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777       setTruncStoreAction((MVT::SimpleValueType)VT,
778                           (MVT::SimpleValueType)InnerVT, Expand);
779     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
782   }
783
784   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785   // with -msoft-float, disable use of MMX as well.
786   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788     // No operations on x86mmx supported, everything uses intrinsics.
789   }
790
791   // MMX-sized vectors (other than x86mmx) are expected to be expanded
792   // into smaller operations.
793   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
794   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
795   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
796   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
797   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
798   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
799   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
800   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
801   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
802   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
803   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
804   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
805   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
806   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
807   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
808   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
809   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
810   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
811   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
812   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
813   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
814   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
815   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
816   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
817   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
818   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
819   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
820   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
821   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
822
823   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
825
826     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
832     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
833     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
834     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
835     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
836     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
838   }
839
840   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
842
843     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844     // registers cannot be used even for integer operations.
845     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
849
850     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
851     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
852     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
853     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
854     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
855     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
856     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
857     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
858     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
859     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
860     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
861     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
862     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
863     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
864     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
865     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
866     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
867
868     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
869     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
870     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
871     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
872
873     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
874     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
877     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
878
879     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881       MVT 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,       VT, Custom);
889       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891     }
892
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900     if (Subtarget->is64Bit()) {
901       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903     }
904
905     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907       MVT VT = (MVT::SimpleValueType)i;
908
909       // Do not attempt to promote non-128-bit vectors
910       if (!VT.is128BitVector())
911         continue;
912
913       setOperationAction(ISD::AND,    VT, Promote);
914       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915       setOperationAction(ISD::OR,     VT, Promote);
916       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917       setOperationAction(ISD::XOR,    VT, Promote);
918       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919       setOperationAction(ISD::LOAD,   VT, Promote);
920       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921       setOperationAction(ISD::SELECT, VT, Promote);
922       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923     }
924
925     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
926
927     // Custom lower v2i64 and v2f64 selects.
928     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
929     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
930     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
931     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
932
933     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
934     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
935
936     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
937   }
938
939   if (Subtarget->hasSSE41()) {
940     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
945     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
946     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
947     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
948     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
949     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
950
951     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
952     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
958     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
961     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
962
963     // i8 and i16 vectors are custom , because the source register and source
964     // source memory operand types are not the same width.  f32 vectors are
965     // custom since the immediate controlling the insert encodes additional
966     // information.
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
971
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
973     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
974     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
975     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
976
977     // FIXME: these should be Legal but thats only for the case where
978     // the index is constant.  For now custom expand to deal with that.
979     if (Subtarget->is64Bit()) {
980       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
981       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
982     }
983   }
984
985   if (Subtarget->hasSSE2()) {
986     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
987     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
988
989     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
990     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
991
992     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
993     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
994
995     if (Subtarget->hasAVX2()) {
996       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
997       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
998
999       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1000       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1001
1002       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1003     } else {
1004       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1005       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1006
1007       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1008       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1009
1010       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1011     }
1012   }
1013
1014   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1016     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1019     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1021
1022     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1025
1026     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1028     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1031     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1032     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1033     setOperationAction(ISD::FABS,               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::FFLOOR,             MVT::v4f64, Legal);
1041     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1042     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1043
1044     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1045     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1046     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1047
1048     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1049
1050     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1051     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1052
1053     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1054     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1055
1056     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1057     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1058
1059     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1060     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1061     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1062     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1063
1064     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1065     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1066     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1067
1068     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1069     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1070     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1071     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1072
1073     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1074       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1075       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1076       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1077       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1078       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1079       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1080     }
1081
1082     if (Subtarget->hasAVX2()) {
1083       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1084       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1085       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1086       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1087
1088       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1089       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1090       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1091       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1092
1093       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1094       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1095       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1096       // Don't lower v32i8 because there is no 128-bit byte mul
1097
1098       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1099
1100       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1101       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1102
1103       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1104       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1105
1106       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1107     } else {
1108       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1109       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1110       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1111       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1112
1113       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1114       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1115       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1116       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1117
1118       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1119       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1120       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1121       // Don't lower v32i8 because there is no 128-bit byte mul
1122
1123       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1124       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1125
1126       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1127       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1128
1129       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1130     }
1131
1132     // Custom lower several nodes for 256-bit types.
1133     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1134              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1135       MVT VT = (MVT::SimpleValueType)i;
1136
1137       // Extract subvector is special because the value type
1138       // (result) is 128-bit but the source is 256-bit wide.
1139       if (VT.is128BitVector())
1140         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1141
1142       // Do not attempt to custom lower other non-256-bit vectors
1143       if (!VT.is256BitVector())
1144         continue;
1145
1146       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1147       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1150       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1151       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1152       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1153     }
1154
1155     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1156     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1157       MVT VT = (MVT::SimpleValueType)i;
1158
1159       // Do not attempt to promote non-256-bit vectors
1160       if (!VT.is256BitVector())
1161         continue;
1162
1163       setOperationAction(ISD::AND,    VT, Promote);
1164       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1165       setOperationAction(ISD::OR,     VT, Promote);
1166       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1167       setOperationAction(ISD::XOR,    VT, Promote);
1168       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1169       setOperationAction(ISD::LOAD,   VT, Promote);
1170       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1171       setOperationAction(ISD::SELECT, VT, Promote);
1172       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1173     }
1174   }
1175
1176   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1177   // of this type with custom code.
1178   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1179            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1180     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1181                        Custom);
1182   }
1183
1184   // We want to custom lower some of our intrinsics.
1185   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1186   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1187
1188
1189   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1190   // handle type legalization for these operations here.
1191   //
1192   // FIXME: We really should do custom legalization for addition and
1193   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1194   // than generic legalization for 64-bit multiplication-with-overflow, though.
1195   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1196     // Add/Sub/Mul with overflow operations are custom lowered.
1197     MVT VT = IntVTs[i];
1198     setOperationAction(ISD::SADDO, VT, Custom);
1199     setOperationAction(ISD::UADDO, VT, Custom);
1200     setOperationAction(ISD::SSUBO, VT, Custom);
1201     setOperationAction(ISD::USUBO, VT, Custom);
1202     setOperationAction(ISD::SMULO, VT, Custom);
1203     setOperationAction(ISD::UMULO, VT, Custom);
1204   }
1205
1206   // There are no 8-bit 3-address imul/mul instructions
1207   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1208   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1209
1210   if (!Subtarget->is64Bit()) {
1211     // These libcalls are not available in 32-bit.
1212     setLibcallName(RTLIB::SHL_I128, 0);
1213     setLibcallName(RTLIB::SRL_I128, 0);
1214     setLibcallName(RTLIB::SRA_I128, 0);
1215   }
1216
1217   // We have target-specific dag combine patterns for the following nodes:
1218   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1219   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1220   setTargetDAGCombine(ISD::VSELECT);
1221   setTargetDAGCombine(ISD::SELECT);
1222   setTargetDAGCombine(ISD::SHL);
1223   setTargetDAGCombine(ISD::SRA);
1224   setTargetDAGCombine(ISD::SRL);
1225   setTargetDAGCombine(ISD::OR);
1226   setTargetDAGCombine(ISD::AND);
1227   setTargetDAGCombine(ISD::ADD);
1228   setTargetDAGCombine(ISD::FADD);
1229   setTargetDAGCombine(ISD::FSUB);
1230   setTargetDAGCombine(ISD::FMA);
1231   setTargetDAGCombine(ISD::SUB);
1232   setTargetDAGCombine(ISD::LOAD);
1233   setTargetDAGCombine(ISD::STORE);
1234   setTargetDAGCombine(ISD::ZERO_EXTEND);
1235   setTargetDAGCombine(ISD::ANY_EXTEND);
1236   setTargetDAGCombine(ISD::SIGN_EXTEND);
1237   setTargetDAGCombine(ISD::TRUNCATE);
1238   setTargetDAGCombine(ISD::UINT_TO_FP);
1239   setTargetDAGCombine(ISD::SINT_TO_FP);
1240   setTargetDAGCombine(ISD::SETCC);
1241   setTargetDAGCombine(ISD::FP_TO_SINT);
1242   if (Subtarget->is64Bit())
1243     setTargetDAGCombine(ISD::MUL);
1244   setTargetDAGCombine(ISD::XOR);
1245
1246   computeRegisterProperties();
1247
1248   // On Darwin, -Os means optimize for size without hurting performance,
1249   // do not reduce the limit.
1250   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1251   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1252   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1253   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1254   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1255   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1256   setPrefLoopAlignment(4); // 2^4 bytes.
1257   benefitFromCodePlacementOpt = true;
1258
1259   // Predictable cmov don't hurt on atom because it's in-order.
1260   predictableSelectIsExpensive = !Subtarget->isAtom();
1261
1262   setPrefFunctionAlignment(4); // 2^4 bytes.
1263 }
1264
1265
1266 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1267   if (!VT.isVector()) return MVT::i8;
1268   return VT.changeVectorElementTypeToInteger();
1269 }
1270
1271
1272 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1273 /// the desired ByVal argument alignment.
1274 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1275   if (MaxAlign == 16)
1276     return;
1277   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1278     if (VTy->getBitWidth() == 128)
1279       MaxAlign = 16;
1280   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1281     unsigned EltAlign = 0;
1282     getMaxByValAlign(ATy->getElementType(), EltAlign);
1283     if (EltAlign > MaxAlign)
1284       MaxAlign = EltAlign;
1285   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1286     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1287       unsigned EltAlign = 0;
1288       getMaxByValAlign(STy->getElementType(i), EltAlign);
1289       if (EltAlign > MaxAlign)
1290         MaxAlign = EltAlign;
1291       if (MaxAlign == 16)
1292         break;
1293     }
1294   }
1295 }
1296
1297 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1298 /// function arguments in the caller parameter area. For X86, aggregates
1299 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1300 /// are at 4-byte boundaries.
1301 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1302   if (Subtarget->is64Bit()) {
1303     // Max of 8 and alignment of type.
1304     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1305     if (TyAlign > 8)
1306       return TyAlign;
1307     return 8;
1308   }
1309
1310   unsigned Align = 4;
1311   if (Subtarget->hasSSE1())
1312     getMaxByValAlign(Ty, Align);
1313   return Align;
1314 }
1315
1316 /// getOptimalMemOpType - Returns the target specific optimal type for load
1317 /// and store operations as a result of memset, memcpy, and memmove
1318 /// lowering. If DstAlign is zero that means it's safe to destination
1319 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1320 /// means there isn't a need to check it against alignment requirement,
1321 /// probably because the source does not need to be loaded. If
1322 /// 'IsZeroVal' is true, that means it's safe to return a
1323 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1324 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1325 /// constant so it does not need to be loaded.
1326 /// It returns EVT::Other if the type should be determined using generic
1327 /// target-independent logic.
1328 EVT
1329 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1330                                        unsigned DstAlign, unsigned SrcAlign,
1331                                        bool IsZeroVal,
1332                                        bool MemcpyStrSrc,
1333                                        MachineFunction &MF) const {
1334   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1335   // linux.  This is because the stack realignment code can't handle certain
1336   // cases like PR2962.  This should be removed when PR2962 is fixed.
1337   const Function *F = MF.getFunction();
1338   if (IsZeroVal &&
1339       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1340     if (Size >= 16 &&
1341         (Subtarget->isUnalignedMemAccessFast() ||
1342          ((DstAlign == 0 || DstAlign >= 16) &&
1343           (SrcAlign == 0 || SrcAlign >= 16))) &&
1344         Subtarget->getStackAlignment() >= 16) {
1345       if (Subtarget->getStackAlignment() >= 32) {
1346         if (Subtarget->hasAVX2())
1347           return MVT::v8i32;
1348         if (Subtarget->hasAVX())
1349           return MVT::v8f32;
1350       }
1351       if (Subtarget->hasSSE2())
1352         return MVT::v4i32;
1353       if (Subtarget->hasSSE1())
1354         return MVT::v4f32;
1355     } else if (!MemcpyStrSrc && Size >= 8 &&
1356                !Subtarget->is64Bit() &&
1357                Subtarget->getStackAlignment() >= 8 &&
1358                Subtarget->hasSSE2()) {
1359       // Do not use f64 to lower memcpy if source is string constant. It's
1360       // better to use i32 to avoid the loads.
1361       return MVT::f64;
1362     }
1363   }
1364   if (Subtarget->is64Bit() && Size >= 8)
1365     return MVT::i64;
1366   return MVT::i32;
1367 }
1368
1369 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1370 /// current function.  The returned value is a member of the
1371 /// MachineJumpTableInfo::JTEntryKind enum.
1372 unsigned X86TargetLowering::getJumpTableEncoding() const {
1373   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1374   // symbol.
1375   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1376       Subtarget->isPICStyleGOT())
1377     return MachineJumpTableInfo::EK_Custom32;
1378
1379   // Otherwise, use the normal jump table encoding heuristics.
1380   return TargetLowering::getJumpTableEncoding();
1381 }
1382
1383 const MCExpr *
1384 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1385                                              const MachineBasicBlock *MBB,
1386                                              unsigned uid,MCContext &Ctx) const{
1387   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1388          Subtarget->isPICStyleGOT());
1389   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1390   // entries.
1391   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1392                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1393 }
1394
1395 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1396 /// jumptable.
1397 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1398                                                     SelectionDAG &DAG) const {
1399   if (!Subtarget->is64Bit())
1400     // This doesn't have DebugLoc associated with it, but is not really the
1401     // same as a Register.
1402     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1403   return Table;
1404 }
1405
1406 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1407 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1408 /// MCExpr.
1409 const MCExpr *X86TargetLowering::
1410 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1411                              MCContext &Ctx) const {
1412   // X86-64 uses RIP relative addressing based on the jump table label.
1413   if (Subtarget->isPICStyleRIPRel())
1414     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1415
1416   // Otherwise, the reference is relative to the PIC base.
1417   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1418 }
1419
1420 // FIXME: Why this routine is here? Move to RegInfo!
1421 std::pair<const TargetRegisterClass*, uint8_t>
1422 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1423   const TargetRegisterClass *RRC = 0;
1424   uint8_t Cost = 1;
1425   switch (VT.getSimpleVT().SimpleTy) {
1426   default:
1427     return TargetLowering::findRepresentativeClass(VT);
1428   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1429     RRC = Subtarget->is64Bit() ?
1430       (const TargetRegisterClass*)&X86::GR64RegClass :
1431       (const TargetRegisterClass*)&X86::GR32RegClass;
1432     break;
1433   case MVT::x86mmx:
1434     RRC = &X86::VR64RegClass;
1435     break;
1436   case MVT::f32: case MVT::f64:
1437   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1438   case MVT::v4f32: case MVT::v2f64:
1439   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1440   case MVT::v4f64:
1441     RRC = &X86::VR128RegClass;
1442     break;
1443   }
1444   return std::make_pair(RRC, Cost);
1445 }
1446
1447 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1448                                                unsigned &Offset) const {
1449   if (!Subtarget->isTargetLinux())
1450     return false;
1451
1452   if (Subtarget->is64Bit()) {
1453     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1454     Offset = 0x28;
1455     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1456       AddressSpace = 256;
1457     else
1458       AddressSpace = 257;
1459   } else {
1460     // %gs:0x14 on i386
1461     Offset = 0x14;
1462     AddressSpace = 256;
1463   }
1464   return true;
1465 }
1466
1467
1468 //===----------------------------------------------------------------------===//
1469 //               Return Value Calling Convention Implementation
1470 //===----------------------------------------------------------------------===//
1471
1472 #include "X86GenCallingConv.inc"
1473
1474 bool
1475 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1476                                   MachineFunction &MF, bool isVarArg,
1477                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1478                         LLVMContext &Context) const {
1479   SmallVector<CCValAssign, 16> RVLocs;
1480   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1481                  RVLocs, Context);
1482   return CCInfo.CheckReturn(Outs, RetCC_X86);
1483 }
1484
1485 SDValue
1486 X86TargetLowering::LowerReturn(SDValue Chain,
1487                                CallingConv::ID CallConv, bool isVarArg,
1488                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1489                                const SmallVectorImpl<SDValue> &OutVals,
1490                                DebugLoc dl, SelectionDAG &DAG) const {
1491   MachineFunction &MF = DAG.getMachineFunction();
1492   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1493
1494   SmallVector<CCValAssign, 16> RVLocs;
1495   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1496                  RVLocs, *DAG.getContext());
1497   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1498
1499   // Add the regs to the liveout set for the function.
1500   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1501   for (unsigned i = 0; i != RVLocs.size(); ++i)
1502     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1503       MRI.addLiveOut(RVLocs[i].getLocReg());
1504
1505   SDValue Flag;
1506
1507   SmallVector<SDValue, 6> RetOps;
1508   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1509   // Operand #1 = Bytes To Pop
1510   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1511                    MVT::i16));
1512
1513   // Copy the result values into the output registers.
1514   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1515     CCValAssign &VA = RVLocs[i];
1516     assert(VA.isRegLoc() && "Can only return in registers!");
1517     SDValue ValToCopy = OutVals[i];
1518     EVT ValVT = ValToCopy.getValueType();
1519
1520     // Promote values to the appropriate types
1521     if (VA.getLocInfo() == CCValAssign::SExt)
1522       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1523     else if (VA.getLocInfo() == CCValAssign::ZExt)
1524       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1525     else if (VA.getLocInfo() == CCValAssign::AExt)
1526       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1527     else if (VA.getLocInfo() == CCValAssign::BCvt)
1528       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1529
1530     // If this is x86-64, and we disabled SSE, we can't return FP values,
1531     // or SSE or MMX vectors.
1532     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1533          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1534           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1535       report_fatal_error("SSE register return with SSE disabled");
1536     }
1537     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1538     // llvm-gcc has never done it right and no one has noticed, so this
1539     // should be OK for now.
1540     if (ValVT == MVT::f64 &&
1541         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1542       report_fatal_error("SSE2 register return with SSE2 disabled");
1543
1544     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1545     // the RET instruction and handled by the FP Stackifier.
1546     if (VA.getLocReg() == X86::ST0 ||
1547         VA.getLocReg() == X86::ST1) {
1548       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1549       // change the value to the FP stack register class.
1550       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1551         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1552       RetOps.push_back(ValToCopy);
1553       // Don't emit a copytoreg.
1554       continue;
1555     }
1556
1557     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1558     // which is returned in RAX / RDX.
1559     if (Subtarget->is64Bit()) {
1560       if (ValVT == MVT::x86mmx) {
1561         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1562           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1563           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1564                                   ValToCopy);
1565           // If we don't have SSE2 available, convert to v4f32 so the generated
1566           // register is legal.
1567           if (!Subtarget->hasSSE2())
1568             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1569         }
1570       }
1571     }
1572
1573     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1574     Flag = Chain.getValue(1);
1575   }
1576
1577   // The x86-64 ABI for returning structs by value requires that we copy
1578   // the sret argument into %rax for the return. We saved the argument into
1579   // a virtual register in the entry block, so now we copy the value out
1580   // and into %rax.
1581   if (Subtarget->is64Bit() &&
1582       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1583     MachineFunction &MF = DAG.getMachineFunction();
1584     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1585     unsigned Reg = FuncInfo->getSRetReturnReg();
1586     assert(Reg &&
1587            "SRetReturnReg should have been set in LowerFormalArguments().");
1588     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1589
1590     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1591     Flag = Chain.getValue(1);
1592
1593     // RAX now acts like a return value.
1594     MRI.addLiveOut(X86::RAX);
1595   }
1596
1597   RetOps[0] = Chain;  // Update chain.
1598
1599   // Add the flag if we have it.
1600   if (Flag.getNode())
1601     RetOps.push_back(Flag);
1602
1603   return DAG.getNode(X86ISD::RET_FLAG, dl,
1604                      MVT::Other, &RetOps[0], RetOps.size());
1605 }
1606
1607 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1608   if (N->getNumValues() != 1)
1609     return false;
1610   if (!N->hasNUsesOfValue(1, 0))
1611     return false;
1612
1613   SDValue TCChain = Chain;
1614   SDNode *Copy = *N->use_begin();
1615   if (Copy->getOpcode() == ISD::CopyToReg) {
1616     // If the copy has a glue operand, we conservatively assume it isn't safe to
1617     // perform a tail call.
1618     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1619       return false;
1620     TCChain = Copy->getOperand(0);
1621   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1622     return false;
1623
1624   bool HasRet = false;
1625   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1626        UI != UE; ++UI) {
1627     if (UI->getOpcode() != X86ISD::RET_FLAG)
1628       return false;
1629     HasRet = true;
1630   }
1631
1632   if (!HasRet)
1633     return false;
1634
1635   Chain = TCChain;
1636   return true;
1637 }
1638
1639 EVT
1640 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1641                                             ISD::NodeType ExtendKind) const {
1642   MVT ReturnMVT;
1643   // TODO: Is this also valid on 32-bit?
1644   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1645     ReturnMVT = MVT::i8;
1646   else
1647     ReturnMVT = MVT::i32;
1648
1649   EVT MinVT = getRegisterType(Context, ReturnMVT);
1650   return VT.bitsLT(MinVT) ? MinVT : VT;
1651 }
1652
1653 /// LowerCallResult - Lower the result values of a call into the
1654 /// appropriate copies out of appropriate physical registers.
1655 ///
1656 SDValue
1657 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1658                                    CallingConv::ID CallConv, bool isVarArg,
1659                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1660                                    DebugLoc dl, SelectionDAG &DAG,
1661                                    SmallVectorImpl<SDValue> &InVals) const {
1662
1663   // Assign locations to each value returned by this call.
1664   SmallVector<CCValAssign, 16> RVLocs;
1665   bool Is64Bit = Subtarget->is64Bit();
1666   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1667                  getTargetMachine(), RVLocs, *DAG.getContext());
1668   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1669
1670   // Copy all of the result registers out of their specified physreg.
1671   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1672     CCValAssign &VA = RVLocs[i];
1673     EVT CopyVT = VA.getValVT();
1674
1675     // If this is x86-64, and we disabled SSE, we can't return FP values
1676     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1677         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1678       report_fatal_error("SSE register return with SSE disabled");
1679     }
1680
1681     SDValue Val;
1682
1683     // If this is a call to a function that returns an fp value on the floating
1684     // point stack, we must guarantee the value is popped from the stack, so
1685     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1686     // if the return value is not used. We use the FpPOP_RETVAL instruction
1687     // instead.
1688     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1689       // If we prefer to use the value in xmm registers, copy it out as f80 and
1690       // use a truncate to move it from fp stack reg to xmm reg.
1691       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1692       SDValue Ops[] = { Chain, InFlag };
1693       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1694                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1695       Val = Chain.getValue(0);
1696
1697       // Round the f80 to the right size, which also moves it to the appropriate
1698       // xmm register.
1699       if (CopyVT != VA.getValVT())
1700         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1701                           // This truncation won't change the value.
1702                           DAG.getIntPtrConstant(1));
1703     } else {
1704       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1705                                  CopyVT, InFlag).getValue(1);
1706       Val = Chain.getValue(0);
1707     }
1708     InFlag = Chain.getValue(2);
1709     InVals.push_back(Val);
1710   }
1711
1712   return Chain;
1713 }
1714
1715
1716 //===----------------------------------------------------------------------===//
1717 //                C & StdCall & Fast Calling Convention implementation
1718 //===----------------------------------------------------------------------===//
1719 //  StdCall calling convention seems to be standard for many Windows' API
1720 //  routines and around. It differs from C calling convention just a little:
1721 //  callee should clean up the stack, not caller. Symbols should be also
1722 //  decorated in some fancy way :) It doesn't support any vector arguments.
1723 //  For info on fast calling convention see Fast Calling Convention (tail call)
1724 //  implementation LowerX86_32FastCCCallTo.
1725
1726 /// CallIsStructReturn - Determines whether a call uses struct return
1727 /// semantics.
1728 enum StructReturnType {
1729   NotStructReturn,
1730   RegStructReturn,
1731   StackStructReturn
1732 };
1733 static StructReturnType
1734 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1735   if (Outs.empty())
1736     return NotStructReturn;
1737
1738   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1739   if (!Flags.isSRet())
1740     return NotStructReturn;
1741   if (Flags.isInReg())
1742     return RegStructReturn;
1743   return StackStructReturn;
1744 }
1745
1746 /// ArgsAreStructReturn - Determines whether a function uses struct
1747 /// return semantics.
1748 static StructReturnType
1749 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1750   if (Ins.empty())
1751     return NotStructReturn;
1752
1753   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1754   if (!Flags.isSRet())
1755     return NotStructReturn;
1756   if (Flags.isInReg())
1757     return RegStructReturn;
1758   return StackStructReturn;
1759 }
1760
1761 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1762 /// by "Src" to address "Dst" with size and alignment information specified by
1763 /// the specific parameter attribute. The copy will be passed as a byval
1764 /// function parameter.
1765 static SDValue
1766 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1767                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1768                           DebugLoc dl) {
1769   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1770
1771   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1772                        /*isVolatile*/false, /*AlwaysInline=*/true,
1773                        MachinePointerInfo(), MachinePointerInfo());
1774 }
1775
1776 /// IsTailCallConvention - Return true if the calling convention is one that
1777 /// supports tail call optimization.
1778 static bool IsTailCallConvention(CallingConv::ID CC) {
1779   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1780 }
1781
1782 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1783   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1784     return false;
1785
1786   CallSite CS(CI);
1787   CallingConv::ID CalleeCC = CS.getCallingConv();
1788   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1789     return false;
1790
1791   return true;
1792 }
1793
1794 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1795 /// a tailcall target by changing its ABI.
1796 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1797                                    bool GuaranteedTailCallOpt) {
1798   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1799 }
1800
1801 SDValue
1802 X86TargetLowering::LowerMemArgument(SDValue Chain,
1803                                     CallingConv::ID CallConv,
1804                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1805                                     DebugLoc dl, SelectionDAG &DAG,
1806                                     const CCValAssign &VA,
1807                                     MachineFrameInfo *MFI,
1808                                     unsigned i) const {
1809   // Create the nodes corresponding to a load from this parameter slot.
1810   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1811   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1812                               getTargetMachine().Options.GuaranteedTailCallOpt);
1813   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1814   EVT ValVT;
1815
1816   // If value is passed by pointer we have address passed instead of the value
1817   // itself.
1818   if (VA.getLocInfo() == CCValAssign::Indirect)
1819     ValVT = VA.getLocVT();
1820   else
1821     ValVT = VA.getValVT();
1822
1823   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1824   // changed with more analysis.
1825   // In case of tail call optimization mark all arguments mutable. Since they
1826   // could be overwritten by lowering of arguments in case of a tail call.
1827   if (Flags.isByVal()) {
1828     unsigned Bytes = Flags.getByValSize();
1829     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1830     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1831     return DAG.getFrameIndex(FI, getPointerTy());
1832   } else {
1833     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1834                                     VA.getLocMemOffset(), isImmutable);
1835     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1836     return DAG.getLoad(ValVT, dl, Chain, FIN,
1837                        MachinePointerInfo::getFixedStack(FI),
1838                        false, false, false, 0);
1839   }
1840 }
1841
1842 SDValue
1843 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1844                                         CallingConv::ID CallConv,
1845                                         bool isVarArg,
1846                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1847                                         DebugLoc dl,
1848                                         SelectionDAG &DAG,
1849                                         SmallVectorImpl<SDValue> &InVals)
1850                                           const {
1851   MachineFunction &MF = DAG.getMachineFunction();
1852   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1853
1854   const Function* Fn = MF.getFunction();
1855   if (Fn->hasExternalLinkage() &&
1856       Subtarget->isTargetCygMing() &&
1857       Fn->getName() == "main")
1858     FuncInfo->setForceFramePointer(true);
1859
1860   MachineFrameInfo *MFI = MF.getFrameInfo();
1861   bool Is64Bit = Subtarget->is64Bit();
1862   bool IsWindows = Subtarget->isTargetWindows();
1863   bool IsWin64 = Subtarget->isTargetWin64();
1864
1865   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1866          "Var args not supported with calling convention fastcc or ghc");
1867
1868   // Assign locations to all of the incoming arguments.
1869   SmallVector<CCValAssign, 16> ArgLocs;
1870   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1871                  ArgLocs, *DAG.getContext());
1872
1873   // Allocate shadow area for Win64
1874   if (IsWin64) {
1875     CCInfo.AllocateStack(32, 8);
1876   }
1877
1878   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1879
1880   unsigned LastVal = ~0U;
1881   SDValue ArgValue;
1882   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1883     CCValAssign &VA = ArgLocs[i];
1884     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1885     // places.
1886     assert(VA.getValNo() != LastVal &&
1887            "Don't support value assigned to multiple locs yet");
1888     (void)LastVal;
1889     LastVal = VA.getValNo();
1890
1891     if (VA.isRegLoc()) {
1892       EVT RegVT = VA.getLocVT();
1893       const TargetRegisterClass *RC;
1894       if (RegVT == MVT::i32)
1895         RC = &X86::GR32RegClass;
1896       else if (Is64Bit && RegVT == MVT::i64)
1897         RC = &X86::GR64RegClass;
1898       else if (RegVT == MVT::f32)
1899         RC = &X86::FR32RegClass;
1900       else if (RegVT == MVT::f64)
1901         RC = &X86::FR64RegClass;
1902       else if (RegVT.is256BitVector())
1903         RC = &X86::VR256RegClass;
1904       else if (RegVT.is128BitVector())
1905         RC = &X86::VR128RegClass;
1906       else if (RegVT == MVT::x86mmx)
1907         RC = &X86::VR64RegClass;
1908       else
1909         llvm_unreachable("Unknown argument type!");
1910
1911       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1912       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1913
1914       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1915       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1916       // right size.
1917       if (VA.getLocInfo() == CCValAssign::SExt)
1918         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1919                                DAG.getValueType(VA.getValVT()));
1920       else if (VA.getLocInfo() == CCValAssign::ZExt)
1921         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1922                                DAG.getValueType(VA.getValVT()));
1923       else if (VA.getLocInfo() == CCValAssign::BCvt)
1924         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1925
1926       if (VA.isExtInLoc()) {
1927         // Handle MMX values passed in XMM regs.
1928         if (RegVT.isVector()) {
1929           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1930                                  ArgValue);
1931         } else
1932           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1933       }
1934     } else {
1935       assert(VA.isMemLoc());
1936       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1937     }
1938
1939     // If value is passed via pointer - do a load.
1940     if (VA.getLocInfo() == CCValAssign::Indirect)
1941       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1942                              MachinePointerInfo(), false, false, false, 0);
1943
1944     InVals.push_back(ArgValue);
1945   }
1946
1947   // The x86-64 ABI for returning structs by value requires that we copy
1948   // the sret argument into %rax for the return. Save the argument into
1949   // a virtual register so that we can access it from the return points.
1950   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1951     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1952     unsigned Reg = FuncInfo->getSRetReturnReg();
1953     if (!Reg) {
1954       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1955       FuncInfo->setSRetReturnReg(Reg);
1956     }
1957     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1958     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1959   }
1960
1961   unsigned StackSize = CCInfo.getNextStackOffset();
1962   // Align stack specially for tail calls.
1963   if (FuncIsMadeTailCallSafe(CallConv,
1964                              MF.getTarget().Options.GuaranteedTailCallOpt))
1965     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1966
1967   // If the function takes variable number of arguments, make a frame index for
1968   // the start of the first vararg value... for expansion of llvm.va_start.
1969   if (isVarArg) {
1970     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1971                     CallConv != CallingConv::X86_ThisCall)) {
1972       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1973     }
1974     if (Is64Bit) {
1975       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1976
1977       // FIXME: We should really autogenerate these arrays
1978       static const uint16_t GPR64ArgRegsWin64[] = {
1979         X86::RCX, X86::RDX, X86::R8,  X86::R9
1980       };
1981       static const uint16_t GPR64ArgRegs64Bit[] = {
1982         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1983       };
1984       static const uint16_t XMMArgRegs64Bit[] = {
1985         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1986         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1987       };
1988       const uint16_t *GPR64ArgRegs;
1989       unsigned NumXMMRegs = 0;
1990
1991       if (IsWin64) {
1992         // The XMM registers which might contain var arg parameters are shadowed
1993         // in their paired GPR.  So we only need to save the GPR to their home
1994         // slots.
1995         TotalNumIntRegs = 4;
1996         GPR64ArgRegs = GPR64ArgRegsWin64;
1997       } else {
1998         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1999         GPR64ArgRegs = GPR64ArgRegs64Bit;
2000
2001         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2002                                                 TotalNumXMMRegs);
2003       }
2004       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2005                                                        TotalNumIntRegs);
2006
2007       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2008       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2009              "SSE register cannot be used when SSE is disabled!");
2010       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2011                NoImplicitFloatOps) &&
2012              "SSE register cannot be used when SSE is disabled!");
2013       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2014           !Subtarget->hasSSE1())
2015         // Kernel mode asks for SSE to be disabled, so don't push them
2016         // on the stack.
2017         TotalNumXMMRegs = 0;
2018
2019       if (IsWin64) {
2020         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2021         // Get to the caller-allocated home save location.  Add 8 to account
2022         // for the return address.
2023         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2024         FuncInfo->setRegSaveFrameIndex(
2025           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2026         // Fixup to set vararg frame on shadow area (4 x i64).
2027         if (NumIntRegs < 4)
2028           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2029       } else {
2030         // For X86-64, if there are vararg parameters that are passed via
2031         // registers, then we must store them to their spots on the stack so
2032         // they may be loaded by deferencing the result of va_next.
2033         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2034         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2035         FuncInfo->setRegSaveFrameIndex(
2036           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2037                                false));
2038       }
2039
2040       // Store the integer parameter registers.
2041       SmallVector<SDValue, 8> MemOps;
2042       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2043                                         getPointerTy());
2044       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2045       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2046         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2047                                   DAG.getIntPtrConstant(Offset));
2048         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2049                                      &X86::GR64RegClass);
2050         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2051         SDValue Store =
2052           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2053                        MachinePointerInfo::getFixedStack(
2054                          FuncInfo->getRegSaveFrameIndex(), Offset),
2055                        false, false, 0);
2056         MemOps.push_back(Store);
2057         Offset += 8;
2058       }
2059
2060       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2061         // Now store the XMM (fp + vector) parameter registers.
2062         SmallVector<SDValue, 11> SaveXMMOps;
2063         SaveXMMOps.push_back(Chain);
2064
2065         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2066         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2067         SaveXMMOps.push_back(ALVal);
2068
2069         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2070                                FuncInfo->getRegSaveFrameIndex()));
2071         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2072                                FuncInfo->getVarArgsFPOffset()));
2073
2074         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2075           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2076                                        &X86::VR128RegClass);
2077           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2078           SaveXMMOps.push_back(Val);
2079         }
2080         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2081                                      MVT::Other,
2082                                      &SaveXMMOps[0], SaveXMMOps.size()));
2083       }
2084
2085       if (!MemOps.empty())
2086         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2087                             &MemOps[0], MemOps.size());
2088     }
2089   }
2090
2091   // Some CCs need callee pop.
2092   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2093                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2094     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2095   } else {
2096     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2097     // If this is an sret function, the return should pop the hidden pointer.
2098     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2099         argsAreStructReturn(Ins) == StackStructReturn)
2100       FuncInfo->setBytesToPopOnReturn(4);
2101   }
2102
2103   if (!Is64Bit) {
2104     // RegSaveFrameIndex is X86-64 only.
2105     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2106     if (CallConv == CallingConv::X86_FastCall ||
2107         CallConv == CallingConv::X86_ThisCall)
2108       // fastcc functions can't have varargs.
2109       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2110   }
2111
2112   FuncInfo->setArgumentStackSize(StackSize);
2113
2114   return Chain;
2115 }
2116
2117 SDValue
2118 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2119                                     SDValue StackPtr, SDValue Arg,
2120                                     DebugLoc dl, SelectionDAG &DAG,
2121                                     const CCValAssign &VA,
2122                                     ISD::ArgFlagsTy Flags) const {
2123   unsigned LocMemOffset = VA.getLocMemOffset();
2124   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2125   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2126   if (Flags.isByVal())
2127     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2128
2129   return DAG.getStore(Chain, dl, Arg, PtrOff,
2130                       MachinePointerInfo::getStack(LocMemOffset),
2131                       false, false, 0);
2132 }
2133
2134 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2135 /// optimization is performed and it is required.
2136 SDValue
2137 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2138                                            SDValue &OutRetAddr, SDValue Chain,
2139                                            bool IsTailCall, bool Is64Bit,
2140                                            int FPDiff, DebugLoc dl) const {
2141   // Adjust the Return address stack slot.
2142   EVT VT = getPointerTy();
2143   OutRetAddr = getReturnAddressFrameIndex(DAG);
2144
2145   // Load the "old" Return address.
2146   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2147                            false, false, false, 0);
2148   return SDValue(OutRetAddr.getNode(), 1);
2149 }
2150
2151 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2152 /// optimization is performed and it is required (FPDiff!=0).
2153 static SDValue
2154 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2155                          SDValue Chain, SDValue RetAddrFrIdx,
2156                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2157   // Store the return address to the appropriate stack slot.
2158   if (!FPDiff) return Chain;
2159   // Calculate the new stack slot for the return address.
2160   int SlotSize = Is64Bit ? 8 : 4;
2161   int NewReturnAddrFI =
2162     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2163   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2164   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2165   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2166                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2167                        false, false, 0);
2168   return Chain;
2169 }
2170
2171 SDValue
2172 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2173                              SmallVectorImpl<SDValue> &InVals) const {
2174   SelectionDAG &DAG                     = CLI.DAG;
2175   DebugLoc &dl                          = CLI.DL;
2176   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2177   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2178   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2179   SDValue Chain                         = CLI.Chain;
2180   SDValue Callee                        = CLI.Callee;
2181   CallingConv::ID CallConv              = CLI.CallConv;
2182   bool &isTailCall                      = CLI.IsTailCall;
2183   bool isVarArg                         = CLI.IsVarArg;
2184
2185   MachineFunction &MF = DAG.getMachineFunction();
2186   bool Is64Bit        = Subtarget->is64Bit();
2187   bool IsWin64        = Subtarget->isTargetWin64();
2188   bool IsWindows      = Subtarget->isTargetWindows();
2189   StructReturnType SR = callIsStructReturn(Outs);
2190   bool IsSibcall      = false;
2191
2192   if (MF.getTarget().Options.DisableTailCalls)
2193     isTailCall = false;
2194
2195   if (isTailCall) {
2196     // Check if it's really possible to do a tail call.
2197     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2198                     isVarArg, SR != NotStructReturn,
2199                     MF.getFunction()->hasStructRetAttr(),
2200                     Outs, OutVals, Ins, DAG);
2201
2202     // Sibcalls are automatically detected tailcalls which do not require
2203     // ABI changes.
2204     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2205       IsSibcall = true;
2206
2207     if (isTailCall)
2208       ++NumTailCalls;
2209   }
2210
2211   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2212          "Var args not supported with calling convention fastcc or ghc");
2213
2214   // Analyze operands of the call, assigning locations to each operand.
2215   SmallVector<CCValAssign, 16> ArgLocs;
2216   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2217                  ArgLocs, *DAG.getContext());
2218
2219   // Allocate shadow area for Win64
2220   if (IsWin64) {
2221     CCInfo.AllocateStack(32, 8);
2222   }
2223
2224   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2225
2226   // Get a count of how many bytes are to be pushed on the stack.
2227   unsigned NumBytes = CCInfo.getNextStackOffset();
2228   if (IsSibcall)
2229     // This is a sibcall. The memory operands are available in caller's
2230     // own caller's stack.
2231     NumBytes = 0;
2232   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2233            IsTailCallConvention(CallConv))
2234     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2235
2236   int FPDiff = 0;
2237   if (isTailCall && !IsSibcall) {
2238     // Lower arguments at fp - stackoffset + fpdiff.
2239     unsigned NumBytesCallerPushed =
2240       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2241     FPDiff = NumBytesCallerPushed - NumBytes;
2242
2243     // Set the delta of movement of the returnaddr stackslot.
2244     // But only set if delta is greater than previous delta.
2245     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2246       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2247   }
2248
2249   if (!IsSibcall)
2250     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2251
2252   SDValue RetAddrFrIdx;
2253   // Load return address for tail calls.
2254   if (isTailCall && FPDiff)
2255     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2256                                     Is64Bit, FPDiff, dl);
2257
2258   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2259   SmallVector<SDValue, 8> MemOpChains;
2260   SDValue StackPtr;
2261
2262   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2263   // of tail call optimization arguments are handle later.
2264   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2265     CCValAssign &VA = ArgLocs[i];
2266     EVT RegVT = VA.getLocVT();
2267     SDValue Arg = OutVals[i];
2268     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2269     bool isByVal = Flags.isByVal();
2270
2271     // Promote the value if needed.
2272     switch (VA.getLocInfo()) {
2273     default: llvm_unreachable("Unknown loc info!");
2274     case CCValAssign::Full: break;
2275     case CCValAssign::SExt:
2276       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2277       break;
2278     case CCValAssign::ZExt:
2279       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2280       break;
2281     case CCValAssign::AExt:
2282       if (RegVT.is128BitVector()) {
2283         // Special case: passing MMX values in XMM registers.
2284         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2285         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2286         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2287       } else
2288         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2289       break;
2290     case CCValAssign::BCvt:
2291       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2292       break;
2293     case CCValAssign::Indirect: {
2294       // Store the argument.
2295       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2296       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2297       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2298                            MachinePointerInfo::getFixedStack(FI),
2299                            false, false, 0);
2300       Arg = SpillSlot;
2301       break;
2302     }
2303     }
2304
2305     if (VA.isRegLoc()) {
2306       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2307       if (isVarArg && IsWin64) {
2308         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2309         // shadow reg if callee is a varargs function.
2310         unsigned ShadowReg = 0;
2311         switch (VA.getLocReg()) {
2312         case X86::XMM0: ShadowReg = X86::RCX; break;
2313         case X86::XMM1: ShadowReg = X86::RDX; break;
2314         case X86::XMM2: ShadowReg = X86::R8; break;
2315         case X86::XMM3: ShadowReg = X86::R9; break;
2316         }
2317         if (ShadowReg)
2318           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2319       }
2320     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2321       assert(VA.isMemLoc());
2322       if (StackPtr.getNode() == 0)
2323         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2324       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2325                                              dl, DAG, VA, Flags));
2326     }
2327   }
2328
2329   if (!MemOpChains.empty())
2330     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2331                         &MemOpChains[0], MemOpChains.size());
2332
2333   if (Subtarget->isPICStyleGOT()) {
2334     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2335     // GOT pointer.
2336     if (!isTailCall) {
2337       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2338                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2339     } else {
2340       // If we are tail calling and generating PIC/GOT style code load the
2341       // address of the callee into ECX. The value in ecx is used as target of
2342       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2343       // for tail calls on PIC/GOT architectures. Normally we would just put the
2344       // address of GOT into ebx and then call target@PLT. But for tail calls
2345       // ebx would be restored (since ebx is callee saved) before jumping to the
2346       // target@PLT.
2347
2348       // Note: The actual moving to ECX is done further down.
2349       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2350       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2351           !G->getGlobal()->hasProtectedVisibility())
2352         Callee = LowerGlobalAddress(Callee, DAG);
2353       else if (isa<ExternalSymbolSDNode>(Callee))
2354         Callee = LowerExternalSymbol(Callee, DAG);
2355     }
2356   }
2357
2358   if (Is64Bit && isVarArg && !IsWin64) {
2359     // From AMD64 ABI document:
2360     // For calls that may call functions that use varargs or stdargs
2361     // (prototype-less calls or calls to functions containing ellipsis (...) in
2362     // the declaration) %al is used as hidden argument to specify the number
2363     // of SSE registers used. The contents of %al do not need to match exactly
2364     // the number of registers, but must be an ubound on the number of SSE
2365     // registers used and is in the range 0 - 8 inclusive.
2366
2367     // Count the number of XMM registers allocated.
2368     static const uint16_t XMMArgRegs[] = {
2369       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2370       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2371     };
2372     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2373     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2374            && "SSE registers cannot be used when SSE is disabled");
2375
2376     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2377                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2378   }
2379
2380   // For tail calls lower the arguments to the 'real' stack slot.
2381   if (isTailCall) {
2382     // Force all the incoming stack arguments to be loaded from the stack
2383     // before any new outgoing arguments are stored to the stack, because the
2384     // outgoing stack slots may alias the incoming argument stack slots, and
2385     // the alias isn't otherwise explicit. This is slightly more conservative
2386     // than necessary, because it means that each store effectively depends
2387     // on every argument instead of just those arguments it would clobber.
2388     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2389
2390     SmallVector<SDValue, 8> MemOpChains2;
2391     SDValue FIN;
2392     int FI = 0;
2393     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2394       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2395         CCValAssign &VA = ArgLocs[i];
2396         if (VA.isRegLoc())
2397           continue;
2398         assert(VA.isMemLoc());
2399         SDValue Arg = OutVals[i];
2400         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2401         // Create frame index.
2402         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2403         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2404         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2405         FIN = DAG.getFrameIndex(FI, getPointerTy());
2406
2407         if (Flags.isByVal()) {
2408           // Copy relative to framepointer.
2409           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2410           if (StackPtr.getNode() == 0)
2411             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2412                                           getPointerTy());
2413           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2414
2415           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2416                                                            ArgChain,
2417                                                            Flags, DAG, dl));
2418         } else {
2419           // Store relative to framepointer.
2420           MemOpChains2.push_back(
2421             DAG.getStore(ArgChain, dl, Arg, FIN,
2422                          MachinePointerInfo::getFixedStack(FI),
2423                          false, false, 0));
2424         }
2425       }
2426     }
2427
2428     if (!MemOpChains2.empty())
2429       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430                           &MemOpChains2[0], MemOpChains2.size());
2431
2432     // Store the return address to the appropriate stack slot.
2433     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2434                                      FPDiff, dl);
2435   }
2436
2437   // Build a sequence of copy-to-reg nodes chained together with token chain
2438   // and flag operands which copy the outgoing args into registers.
2439   SDValue InFlag;
2440   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2441     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2442                              RegsToPass[i].second, InFlag);
2443     InFlag = Chain.getValue(1);
2444   }
2445
2446   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2447     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2448     // In the 64-bit large code model, we have to make all calls
2449     // through a register, since the call instruction's 32-bit
2450     // pc-relative offset may not be large enough to hold the whole
2451     // address.
2452   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2453     // If the callee is a GlobalAddress node (quite common, every direct call
2454     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2455     // it.
2456
2457     // We should use extra load for direct calls to dllimported functions in
2458     // non-JIT mode.
2459     const GlobalValue *GV = G->getGlobal();
2460     if (!GV->hasDLLImportLinkage()) {
2461       unsigned char OpFlags = 0;
2462       bool ExtraLoad = false;
2463       unsigned WrapperKind = ISD::DELETED_NODE;
2464
2465       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2466       // external symbols most go through the PLT in PIC mode.  If the symbol
2467       // has hidden or protected visibility, or if it is static or local, then
2468       // we don't need to use the PLT - we can directly call it.
2469       if (Subtarget->isTargetELF() &&
2470           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2471           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2472         OpFlags = X86II::MO_PLT;
2473       } else if (Subtarget->isPICStyleStubAny() &&
2474                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2475                  (!Subtarget->getTargetTriple().isMacOSX() ||
2476                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2477         // PC-relative references to external symbols should go through $stub,
2478         // unless we're building with the leopard linker or later, which
2479         // automatically synthesizes these stubs.
2480         OpFlags = X86II::MO_DARWIN_STUB;
2481       } else if (Subtarget->isPICStyleRIPRel() &&
2482                  isa<Function>(GV) &&
2483                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2484         // If the function is marked as non-lazy, generate an indirect call
2485         // which loads from the GOT directly. This avoids runtime overhead
2486         // at the cost of eager binding (and one extra byte of encoding).
2487         OpFlags = X86II::MO_GOTPCREL;
2488         WrapperKind = X86ISD::WrapperRIP;
2489         ExtraLoad = true;
2490       }
2491
2492       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2493                                           G->getOffset(), OpFlags);
2494
2495       // Add a wrapper if needed.
2496       if (WrapperKind != ISD::DELETED_NODE)
2497         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2498       // Add extra indirection if needed.
2499       if (ExtraLoad)
2500         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2501                              MachinePointerInfo::getGOT(),
2502                              false, false, false, 0);
2503     }
2504   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2505     unsigned char OpFlags = 0;
2506
2507     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2508     // external symbols should go through the PLT.
2509     if (Subtarget->isTargetELF() &&
2510         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2511       OpFlags = X86II::MO_PLT;
2512     } else if (Subtarget->isPICStyleStubAny() &&
2513                (!Subtarget->getTargetTriple().isMacOSX() ||
2514                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2515       // PC-relative references to external symbols should go through $stub,
2516       // unless we're building with the leopard linker or later, which
2517       // automatically synthesizes these stubs.
2518       OpFlags = X86II::MO_DARWIN_STUB;
2519     }
2520
2521     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2522                                          OpFlags);
2523   }
2524
2525   // Returns a chain & a flag for retval copy to use.
2526   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2527   SmallVector<SDValue, 8> Ops;
2528
2529   if (!IsSibcall && isTailCall) {
2530     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2531                            DAG.getIntPtrConstant(0, true), InFlag);
2532     InFlag = Chain.getValue(1);
2533   }
2534
2535   Ops.push_back(Chain);
2536   Ops.push_back(Callee);
2537
2538   if (isTailCall)
2539     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2540
2541   // Add argument registers to the end of the list so that they are known live
2542   // into the call.
2543   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2544     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2545                                   RegsToPass[i].second.getValueType()));
2546
2547   // Add a register mask operand representing the call-preserved registers.
2548   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2549   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2550   assert(Mask && "Missing call preserved mask for calling convention");
2551   Ops.push_back(DAG.getRegisterMask(Mask));
2552
2553   if (InFlag.getNode())
2554     Ops.push_back(InFlag);
2555
2556   if (isTailCall) {
2557     // We used to do:
2558     //// If this is the first return lowered for this function, add the regs
2559     //// to the liveout set for the function.
2560     // This isn't right, although it's probably harmless on x86; liveouts
2561     // should be computed from returns not tail calls.  Consider a void
2562     // function making a tail call to a function returning int.
2563     return DAG.getNode(X86ISD::TC_RETURN, dl,
2564                        NodeTys, &Ops[0], Ops.size());
2565   }
2566
2567   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2568   InFlag = Chain.getValue(1);
2569
2570   // Create the CALLSEQ_END node.
2571   unsigned NumBytesForCalleeToPush;
2572   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2573                        getTargetMachine().Options.GuaranteedTailCallOpt))
2574     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2575   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2576            SR == StackStructReturn)
2577     // If this is a call to a struct-return function, the callee
2578     // pops the hidden struct pointer, so we have to push it back.
2579     // This is common for Darwin/X86, Linux & Mingw32 targets.
2580     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2581     NumBytesForCalleeToPush = 4;
2582   else
2583     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2584
2585   // Returns a flag for retval copy to use.
2586   if (!IsSibcall) {
2587     Chain = DAG.getCALLSEQ_END(Chain,
2588                                DAG.getIntPtrConstant(NumBytes, true),
2589                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2590                                                      true),
2591                                InFlag);
2592     InFlag = Chain.getValue(1);
2593   }
2594
2595   // Handle result values, copying them out of physregs into vregs that we
2596   // return.
2597   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2598                          Ins, dl, DAG, InVals);
2599 }
2600
2601
2602 //===----------------------------------------------------------------------===//
2603 //                Fast Calling Convention (tail call) implementation
2604 //===----------------------------------------------------------------------===//
2605
2606 //  Like std call, callee cleans arguments, convention except that ECX is
2607 //  reserved for storing the tail called function address. Only 2 registers are
2608 //  free for argument passing (inreg). Tail call optimization is performed
2609 //  provided:
2610 //                * tailcallopt is enabled
2611 //                * caller/callee are fastcc
2612 //  On X86_64 architecture with GOT-style position independent code only local
2613 //  (within module) calls are supported at the moment.
2614 //  To keep the stack aligned according to platform abi the function
2615 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2616 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2617 //  If a tail called function callee has more arguments than the caller the
2618 //  caller needs to make sure that there is room to move the RETADDR to. This is
2619 //  achieved by reserving an area the size of the argument delta right after the
2620 //  original REtADDR, but before the saved framepointer or the spilled registers
2621 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2622 //  stack layout:
2623 //    arg1
2624 //    arg2
2625 //    RETADDR
2626 //    [ new RETADDR
2627 //      move area ]
2628 //    (possible EBP)
2629 //    ESI
2630 //    EDI
2631 //    local1 ..
2632
2633 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2634 /// for a 16 byte align requirement.
2635 unsigned
2636 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2637                                                SelectionDAG& DAG) const {
2638   MachineFunction &MF = DAG.getMachineFunction();
2639   const TargetMachine &TM = MF.getTarget();
2640   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2641   unsigned StackAlignment = TFI.getStackAlignment();
2642   uint64_t AlignMask = StackAlignment - 1;
2643   int64_t Offset = StackSize;
2644   uint64_t SlotSize = TD->getPointerSize();
2645   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2646     // Number smaller than 12 so just add the difference.
2647     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2648   } else {
2649     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2650     Offset = ((~AlignMask) & Offset) + StackAlignment +
2651       (StackAlignment-SlotSize);
2652   }
2653   return Offset;
2654 }
2655
2656 /// MatchingStackOffset - Return true if the given stack call argument is
2657 /// already available in the same position (relatively) of the caller's
2658 /// incoming argument stack.
2659 static
2660 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2661                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2662                          const X86InstrInfo *TII) {
2663   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2664   int FI = INT_MAX;
2665   if (Arg.getOpcode() == ISD::CopyFromReg) {
2666     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2667     if (!TargetRegisterInfo::isVirtualRegister(VR))
2668       return false;
2669     MachineInstr *Def = MRI->getVRegDef(VR);
2670     if (!Def)
2671       return false;
2672     if (!Flags.isByVal()) {
2673       if (!TII->isLoadFromStackSlot(Def, FI))
2674         return false;
2675     } else {
2676       unsigned Opcode = Def->getOpcode();
2677       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2678           Def->getOperand(1).isFI()) {
2679         FI = Def->getOperand(1).getIndex();
2680         Bytes = Flags.getByValSize();
2681       } else
2682         return false;
2683     }
2684   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2685     if (Flags.isByVal())
2686       // ByVal argument is passed in as a pointer but it's now being
2687       // dereferenced. e.g.
2688       // define @foo(%struct.X* %A) {
2689       //   tail call @bar(%struct.X* byval %A)
2690       // }
2691       return false;
2692     SDValue Ptr = Ld->getBasePtr();
2693     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2694     if (!FINode)
2695       return false;
2696     FI = FINode->getIndex();
2697   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2698     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2699     FI = FINode->getIndex();
2700     Bytes = Flags.getByValSize();
2701   } else
2702     return false;
2703
2704   assert(FI != INT_MAX);
2705   if (!MFI->isFixedObjectIndex(FI))
2706     return false;
2707   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2708 }
2709
2710 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2711 /// for tail call optimization. Targets which want to do tail call
2712 /// optimization should implement this function.
2713 bool
2714 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2715                                                      CallingConv::ID CalleeCC,
2716                                                      bool isVarArg,
2717                                                      bool isCalleeStructRet,
2718                                                      bool isCallerStructRet,
2719                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2720                                     const SmallVectorImpl<SDValue> &OutVals,
2721                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2722                                                      SelectionDAG& DAG) const {
2723   if (!IsTailCallConvention(CalleeCC) &&
2724       CalleeCC != CallingConv::C)
2725     return false;
2726
2727   // If -tailcallopt is specified, make fastcc functions tail-callable.
2728   const MachineFunction &MF = DAG.getMachineFunction();
2729   const Function *CallerF = DAG.getMachineFunction().getFunction();
2730   CallingConv::ID CallerCC = CallerF->getCallingConv();
2731   bool CCMatch = CallerCC == CalleeCC;
2732
2733   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2734     if (IsTailCallConvention(CalleeCC) && CCMatch)
2735       return true;
2736     return false;
2737   }
2738
2739   // Look for obvious safe cases to perform tail call optimization that do not
2740   // require ABI changes. This is what gcc calls sibcall.
2741
2742   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2743   // emit a special epilogue.
2744   if (RegInfo->needsStackRealignment(MF))
2745     return false;
2746
2747   // Also avoid sibcall optimization if either caller or callee uses struct
2748   // return semantics.
2749   if (isCalleeStructRet || isCallerStructRet)
2750     return false;
2751
2752   // An stdcall caller is expected to clean up its arguments; the callee
2753   // isn't going to do that.
2754   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2755     return false;
2756
2757   // Do not sibcall optimize vararg calls unless all arguments are passed via
2758   // registers.
2759   if (isVarArg && !Outs.empty()) {
2760
2761     // Optimizing for varargs on Win64 is unlikely to be safe without
2762     // additional testing.
2763     if (Subtarget->isTargetWin64())
2764       return false;
2765
2766     SmallVector<CCValAssign, 16> ArgLocs;
2767     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2768                    getTargetMachine(), ArgLocs, *DAG.getContext());
2769
2770     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2771     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2772       if (!ArgLocs[i].isRegLoc())
2773         return false;
2774   }
2775
2776   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2777   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2778   // this into a sibcall.
2779   bool Unused = false;
2780   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2781     if (!Ins[i].Used) {
2782       Unused = true;
2783       break;
2784     }
2785   }
2786   if (Unused) {
2787     SmallVector<CCValAssign, 16> RVLocs;
2788     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2789                    getTargetMachine(), RVLocs, *DAG.getContext());
2790     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2791     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2792       CCValAssign &VA = RVLocs[i];
2793       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2794         return false;
2795     }
2796   }
2797
2798   // If the calling conventions do not match, then we'd better make sure the
2799   // results are returned in the same way as what the caller expects.
2800   if (!CCMatch) {
2801     SmallVector<CCValAssign, 16> RVLocs1;
2802     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2803                     getTargetMachine(), RVLocs1, *DAG.getContext());
2804     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2805
2806     SmallVector<CCValAssign, 16> RVLocs2;
2807     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2808                     getTargetMachine(), RVLocs2, *DAG.getContext());
2809     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2810
2811     if (RVLocs1.size() != RVLocs2.size())
2812       return false;
2813     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2814       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2815         return false;
2816       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2817         return false;
2818       if (RVLocs1[i].isRegLoc()) {
2819         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2820           return false;
2821       } else {
2822         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2823           return false;
2824       }
2825     }
2826   }
2827
2828   // If the callee takes no arguments then go on to check the results of the
2829   // call.
2830   if (!Outs.empty()) {
2831     // Check if stack adjustment is needed. For now, do not do this if any
2832     // argument is passed on the stack.
2833     SmallVector<CCValAssign, 16> ArgLocs;
2834     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2835                    getTargetMachine(), ArgLocs, *DAG.getContext());
2836
2837     // Allocate shadow area for Win64
2838     if (Subtarget->isTargetWin64()) {
2839       CCInfo.AllocateStack(32, 8);
2840     }
2841
2842     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2843     if (CCInfo.getNextStackOffset()) {
2844       MachineFunction &MF = DAG.getMachineFunction();
2845       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2846         return false;
2847
2848       // Check if the arguments are already laid out in the right way as
2849       // the caller's fixed stack objects.
2850       MachineFrameInfo *MFI = MF.getFrameInfo();
2851       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2852       const X86InstrInfo *TII =
2853         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2854       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855         CCValAssign &VA = ArgLocs[i];
2856         SDValue Arg = OutVals[i];
2857         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2858         if (VA.getLocInfo() == CCValAssign::Indirect)
2859           return false;
2860         if (!VA.isRegLoc()) {
2861           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2862                                    MFI, MRI, TII))
2863             return false;
2864         }
2865       }
2866     }
2867
2868     // If the tailcall address may be in a register, then make sure it's
2869     // possible to register allocate for it. In 32-bit, the call address can
2870     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2871     // callee-saved registers are restored. These happen to be the same
2872     // registers used to pass 'inreg' arguments so watch out for those.
2873     if (!Subtarget->is64Bit() &&
2874         !isa<GlobalAddressSDNode>(Callee) &&
2875         !isa<ExternalSymbolSDNode>(Callee)) {
2876       unsigned NumInRegs = 0;
2877       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2878         CCValAssign &VA = ArgLocs[i];
2879         if (!VA.isRegLoc())
2880           continue;
2881         unsigned Reg = VA.getLocReg();
2882         switch (Reg) {
2883         default: break;
2884         case X86::EAX: case X86::EDX: case X86::ECX:
2885           if (++NumInRegs == 3)
2886             return false;
2887           break;
2888         }
2889       }
2890     }
2891   }
2892
2893   return true;
2894 }
2895
2896 FastISel *
2897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2898                                   const TargetLibraryInfo *libInfo) const {
2899   return X86::createFastISel(funcInfo, libInfo);
2900 }
2901
2902
2903 //===----------------------------------------------------------------------===//
2904 //                           Other Lowering Hooks
2905 //===----------------------------------------------------------------------===//
2906
2907 static bool MayFoldLoad(SDValue Op) {
2908   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2909 }
2910
2911 static bool MayFoldIntoStore(SDValue Op) {
2912   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2913 }
2914
2915 static bool isTargetShuffle(unsigned Opcode) {
2916   switch(Opcode) {
2917   default: return false;
2918   case X86ISD::PSHUFD:
2919   case X86ISD::PSHUFHW:
2920   case X86ISD::PSHUFLW:
2921   case X86ISD::SHUFP:
2922   case X86ISD::PALIGN:
2923   case X86ISD::MOVLHPS:
2924   case X86ISD::MOVLHPD:
2925   case X86ISD::MOVHLPS:
2926   case X86ISD::MOVLPS:
2927   case X86ISD::MOVLPD:
2928   case X86ISD::MOVSHDUP:
2929   case X86ISD::MOVSLDUP:
2930   case X86ISD::MOVDDUP:
2931   case X86ISD::MOVSS:
2932   case X86ISD::MOVSD:
2933   case X86ISD::UNPCKL:
2934   case X86ISD::UNPCKH:
2935   case X86ISD::VPERMILP:
2936   case X86ISD::VPERM2X128:
2937   case X86ISD::VPERMI:
2938     return true;
2939   }
2940 }
2941
2942 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2943                                     SDValue V1, SelectionDAG &DAG) {
2944   switch(Opc) {
2945   default: llvm_unreachable("Unknown x86 shuffle node");
2946   case X86ISD::MOVSHDUP:
2947   case X86ISD::MOVSLDUP:
2948   case X86ISD::MOVDDUP:
2949     return DAG.getNode(Opc, dl, VT, V1);
2950   }
2951 }
2952
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954                                     SDValue V1, unsigned TargetMask,
2955                                     SelectionDAG &DAG) {
2956   switch(Opc) {
2957   default: llvm_unreachable("Unknown x86 shuffle node");
2958   case X86ISD::PSHUFD:
2959   case X86ISD::PSHUFHW:
2960   case X86ISD::PSHUFLW:
2961   case X86ISD::VPERMILP:
2962   case X86ISD::VPERMI:
2963     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2964   }
2965 }
2966
2967 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2968                                     SDValue V1, SDValue V2, unsigned TargetMask,
2969                                     SelectionDAG &DAG) {
2970   switch(Opc) {
2971   default: llvm_unreachable("Unknown x86 shuffle node");
2972   case X86ISD::PALIGN:
2973   case X86ISD::SHUFP:
2974   case X86ISD::VPERM2X128:
2975     return DAG.getNode(Opc, dl, VT, V1, V2,
2976                        DAG.getConstant(TargetMask, MVT::i8));
2977   }
2978 }
2979
2980 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2981                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2982   switch(Opc) {
2983   default: llvm_unreachable("Unknown x86 shuffle node");
2984   case X86ISD::MOVLHPS:
2985   case X86ISD::MOVLHPD:
2986   case X86ISD::MOVHLPS:
2987   case X86ISD::MOVLPS:
2988   case X86ISD::MOVLPD:
2989   case X86ISD::MOVSS:
2990   case X86ISD::MOVSD:
2991   case X86ISD::UNPCKL:
2992   case X86ISD::UNPCKH:
2993     return DAG.getNode(Opc, dl, VT, V1, V2);
2994   }
2995 }
2996
2997 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2998   MachineFunction &MF = DAG.getMachineFunction();
2999   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3000   int ReturnAddrIndex = FuncInfo->getRAIndex();
3001
3002   if (ReturnAddrIndex == 0) {
3003     // Set up a frame object for the return address.
3004     uint64_t SlotSize = TD->getPointerSize();
3005     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3006                                                            false);
3007     FuncInfo->setRAIndex(ReturnAddrIndex);
3008   }
3009
3010   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3011 }
3012
3013
3014 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3015                                        bool hasSymbolicDisplacement) {
3016   // Offset should fit into 32 bit immediate field.
3017   if (!isInt<32>(Offset))
3018     return false;
3019
3020   // If we don't have a symbolic displacement - we don't have any extra
3021   // restrictions.
3022   if (!hasSymbolicDisplacement)
3023     return true;
3024
3025   // FIXME: Some tweaks might be needed for medium code model.
3026   if (M != CodeModel::Small && M != CodeModel::Kernel)
3027     return false;
3028
3029   // For small code model we assume that latest object is 16MB before end of 31
3030   // bits boundary. We may also accept pretty large negative constants knowing
3031   // that all objects are in the positive half of address space.
3032   if (M == CodeModel::Small && Offset < 16*1024*1024)
3033     return true;
3034
3035   // For kernel code model we know that all object resist in the negative half
3036   // of 32bits address space. We may not accept negative offsets, since they may
3037   // be just off and we may accept pretty large positive ones.
3038   if (M == CodeModel::Kernel && Offset > 0)
3039     return true;
3040
3041   return false;
3042 }
3043
3044 /// isCalleePop - Determines whether the callee is required to pop its
3045 /// own arguments. Callee pop is necessary to support tail calls.
3046 bool X86::isCalleePop(CallingConv::ID CallingConv,
3047                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3048   if (IsVarArg)
3049     return false;
3050
3051   switch (CallingConv) {
3052   default:
3053     return false;
3054   case CallingConv::X86_StdCall:
3055     return !is64Bit;
3056   case CallingConv::X86_FastCall:
3057     return !is64Bit;
3058   case CallingConv::X86_ThisCall:
3059     return !is64Bit;
3060   case CallingConv::Fast:
3061     return TailCallOpt;
3062   case CallingConv::GHC:
3063     return TailCallOpt;
3064   }
3065 }
3066
3067 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3068 /// specific condition code, returning the condition code and the LHS/RHS of the
3069 /// comparison to make.
3070 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3071                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3072   if (!isFP) {
3073     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3074       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3075         // X > -1   -> X == 0, jump !sign.
3076         RHS = DAG.getConstant(0, RHS.getValueType());
3077         return X86::COND_NS;
3078       }
3079       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3080         // X < 0   -> X == 0, jump on sign.
3081         return X86::COND_S;
3082       }
3083       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3084         // X < 1   -> X <= 0
3085         RHS = DAG.getConstant(0, RHS.getValueType());
3086         return X86::COND_LE;
3087       }
3088     }
3089
3090     switch (SetCCOpcode) {
3091     default: llvm_unreachable("Invalid integer condition!");
3092     case ISD::SETEQ:  return X86::COND_E;
3093     case ISD::SETGT:  return X86::COND_G;
3094     case ISD::SETGE:  return X86::COND_GE;
3095     case ISD::SETLT:  return X86::COND_L;
3096     case ISD::SETLE:  return X86::COND_LE;
3097     case ISD::SETNE:  return X86::COND_NE;
3098     case ISD::SETULT: return X86::COND_B;
3099     case ISD::SETUGT: return X86::COND_A;
3100     case ISD::SETULE: return X86::COND_BE;
3101     case ISD::SETUGE: return X86::COND_AE;
3102     }
3103   }
3104
3105   // First determine if it is required or is profitable to flip the operands.
3106
3107   // If LHS is a foldable load, but RHS is not, flip the condition.
3108   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3109       !ISD::isNON_EXTLoad(RHS.getNode())) {
3110     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3111     std::swap(LHS, RHS);
3112   }
3113
3114   switch (SetCCOpcode) {
3115   default: break;
3116   case ISD::SETOLT:
3117   case ISD::SETOLE:
3118   case ISD::SETUGT:
3119   case ISD::SETUGE:
3120     std::swap(LHS, RHS);
3121     break;
3122   }
3123
3124   // On a floating point condition, the flags are set as follows:
3125   // ZF  PF  CF   op
3126   //  0 | 0 | 0 | X > Y
3127   //  0 | 0 | 1 | X < Y
3128   //  1 | 0 | 0 | X == Y
3129   //  1 | 1 | 1 | unordered
3130   switch (SetCCOpcode) {
3131   default: llvm_unreachable("Condcode should be pre-legalized away");
3132   case ISD::SETUEQ:
3133   case ISD::SETEQ:   return X86::COND_E;
3134   case ISD::SETOLT:              // flipped
3135   case ISD::SETOGT:
3136   case ISD::SETGT:   return X86::COND_A;
3137   case ISD::SETOLE:              // flipped
3138   case ISD::SETOGE:
3139   case ISD::SETGE:   return X86::COND_AE;
3140   case ISD::SETUGT:              // flipped
3141   case ISD::SETULT:
3142   case ISD::SETLT:   return X86::COND_B;
3143   case ISD::SETUGE:              // flipped
3144   case ISD::SETULE:
3145   case ISD::SETLE:   return X86::COND_BE;
3146   case ISD::SETONE:
3147   case ISD::SETNE:   return X86::COND_NE;
3148   case ISD::SETUO:   return X86::COND_P;
3149   case ISD::SETO:    return X86::COND_NP;
3150   case ISD::SETOEQ:
3151   case ISD::SETUNE:  return X86::COND_INVALID;
3152   }
3153 }
3154
3155 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3156 /// code. Current x86 isa includes the following FP cmov instructions:
3157 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3158 static bool hasFPCMov(unsigned X86CC) {
3159   switch (X86CC) {
3160   default:
3161     return false;
3162   case X86::COND_B:
3163   case X86::COND_BE:
3164   case X86::COND_E:
3165   case X86::COND_P:
3166   case X86::COND_A:
3167   case X86::COND_AE:
3168   case X86::COND_NE:
3169   case X86::COND_NP:
3170     return true;
3171   }
3172 }
3173
3174 /// isFPImmLegal - Returns true if the target can instruction select the
3175 /// specified FP immediate natively. If false, the legalizer will
3176 /// materialize the FP immediate as a load from a constant pool.
3177 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3178   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3179     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3180       return true;
3181   }
3182   return false;
3183 }
3184
3185 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3186 /// the specified range (L, H].
3187 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3188   return (Val < 0) || (Val >= Low && Val < Hi);
3189 }
3190
3191 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3192 /// specified value.
3193 static bool isUndefOrEqual(int Val, int CmpVal) {
3194   if (Val < 0 || Val == CmpVal)
3195     return true;
3196   return false;
3197 }
3198
3199 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3200 /// from position Pos and ending in Pos+Size, falls within the specified
3201 /// sequential range (L, L+Pos]. or is undef.
3202 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3203                                        unsigned Pos, unsigned Size, int Low) {
3204   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3205     if (!isUndefOrEqual(Mask[i], Low))
3206       return false;
3207   return true;
3208 }
3209
3210 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3211 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3212 /// the second operand.
3213 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3214   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3215     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3216   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3217     return (Mask[0] < 2 && Mask[1] < 2);
3218   return false;
3219 }
3220
3221 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3222 /// is suitable for input to PSHUFHW.
3223 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3224   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3225     return false;
3226
3227   // Lower quadword copied in order or undef.
3228   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3229     return false;
3230
3231   // Upper quadword shuffled.
3232   for (unsigned i = 4; i != 8; ++i)
3233     if (!isUndefOrInRange(Mask[i], 4, 8))
3234       return false;
3235
3236   if (VT == MVT::v16i16) {
3237     // Lower quadword copied in order or undef.
3238     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3239       return false;
3240
3241     // Upper quadword shuffled.
3242     for (unsigned i = 12; i != 16; ++i)
3243       if (!isUndefOrInRange(Mask[i], 12, 16))
3244         return false;
3245   }
3246
3247   return true;
3248 }
3249
3250 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3251 /// is suitable for input to PSHUFLW.
3252 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3253   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3254     return false;
3255
3256   // Upper quadword copied in order.
3257   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3258     return false;
3259
3260   // Lower quadword shuffled.
3261   for (unsigned i = 0; i != 4; ++i)
3262     if (!isUndefOrInRange(Mask[i], 0, 4))
3263       return false;
3264
3265   if (VT == MVT::v16i16) {
3266     // Upper quadword copied in order.
3267     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3268       return false;
3269
3270     // Lower quadword shuffled.
3271     for (unsigned i = 8; i != 12; ++i)
3272       if (!isUndefOrInRange(Mask[i], 8, 12))
3273         return false;
3274   }
3275
3276   return true;
3277 }
3278
3279 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3280 /// is suitable for input to PALIGNR.
3281 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3282                           const X86Subtarget *Subtarget) {
3283   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3284       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3285     return false;
3286
3287   unsigned NumElts = VT.getVectorNumElements();
3288   unsigned NumLanes = VT.getSizeInBits()/128;
3289   unsigned NumLaneElts = NumElts/NumLanes;
3290
3291   // Do not handle 64-bit element shuffles with palignr.
3292   if (NumLaneElts == 2)
3293     return false;
3294
3295   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3296     unsigned i;
3297     for (i = 0; i != NumLaneElts; ++i) {
3298       if (Mask[i+l] >= 0)
3299         break;
3300     }
3301
3302     // Lane is all undef, go to next lane
3303     if (i == NumLaneElts)
3304       continue;
3305
3306     int Start = Mask[i+l];
3307
3308     // Make sure its in this lane in one of the sources
3309     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3310         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3311       return false;
3312
3313     // If not lane 0, then we must match lane 0
3314     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3315       return false;
3316
3317     // Correct second source to be contiguous with first source
3318     if (Start >= (int)NumElts)
3319       Start -= NumElts - NumLaneElts;
3320
3321     // Make sure we're shifting in the right direction.
3322     if (Start <= (int)(i+l))
3323       return false;
3324
3325     Start -= i;
3326
3327     // Check the rest of the elements to see if they are consecutive.
3328     for (++i; i != NumLaneElts; ++i) {
3329       int Idx = Mask[i+l];
3330
3331       // Make sure its in this lane
3332       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3333           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3334         return false;
3335
3336       // If not lane 0, then we must match lane 0
3337       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3338         return false;
3339
3340       if (Idx >= (int)NumElts)
3341         Idx -= NumElts - NumLaneElts;
3342
3343       if (!isUndefOrEqual(Idx, Start+i))
3344         return false;
3345
3346     }
3347   }
3348
3349   return true;
3350 }
3351
3352 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3353 /// the two vector operands have swapped position.
3354 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3355                                      unsigned NumElems) {
3356   for (unsigned i = 0; i != NumElems; ++i) {
3357     int idx = Mask[i];
3358     if (idx < 0)
3359       continue;
3360     else if (idx < (int)NumElems)
3361       Mask[i] = idx + NumElems;
3362     else
3363       Mask[i] = idx - NumElems;
3364   }
3365 }
3366
3367 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3368 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3369 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3370 /// reverse of what x86 shuffles want.
3371 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3372                         bool Commuted = false) {
3373   if (!HasAVX && VT.getSizeInBits() == 256)
3374     return false;
3375
3376   unsigned NumElems = VT.getVectorNumElements();
3377   unsigned NumLanes = VT.getSizeInBits()/128;
3378   unsigned NumLaneElems = NumElems/NumLanes;
3379
3380   if (NumLaneElems != 2 && NumLaneElems != 4)
3381     return false;
3382
3383   // VSHUFPSY divides the resulting vector into 4 chunks.
3384   // The sources are also splitted into 4 chunks, and each destination
3385   // chunk must come from a different source chunk.
3386   //
3387   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3388   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3389   //
3390   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3391   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3392   //
3393   // VSHUFPDY divides the resulting vector into 4 chunks.
3394   // The sources are also splitted into 4 chunks, and each destination
3395   // chunk must come from a different source chunk.
3396   //
3397   //  SRC1 =>      X3       X2       X1       X0
3398   //  SRC2 =>      Y3       Y2       Y1       Y0
3399   //
3400   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3401   //
3402   unsigned HalfLaneElems = NumLaneElems/2;
3403   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3404     for (unsigned i = 0; i != NumLaneElems; ++i) {
3405       int Idx = Mask[i+l];
3406       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3407       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3408         return false;
3409       // For VSHUFPSY, the mask of the second half must be the same as the
3410       // first but with the appropriate offsets. This works in the same way as
3411       // VPERMILPS works with masks.
3412       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3413         continue;
3414       if (!isUndefOrEqual(Idx, Mask[i]+l))
3415         return false;
3416     }
3417   }
3418
3419   return true;
3420 }
3421
3422 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3423 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3424 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3425   if (!VT.is128BitVector())
3426     return false;
3427
3428   unsigned NumElems = VT.getVectorNumElements();
3429
3430   if (NumElems != 4)
3431     return false;
3432
3433   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3434   return isUndefOrEqual(Mask[0], 6) &&
3435          isUndefOrEqual(Mask[1], 7) &&
3436          isUndefOrEqual(Mask[2], 2) &&
3437          isUndefOrEqual(Mask[3], 3);
3438 }
3439
3440 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3441 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3442 /// <2, 3, 2, 3>
3443 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3444   if (!VT.is128BitVector())
3445     return false;
3446
3447   unsigned NumElems = VT.getVectorNumElements();
3448
3449   if (NumElems != 4)
3450     return false;
3451
3452   return isUndefOrEqual(Mask[0], 2) &&
3453          isUndefOrEqual(Mask[1], 3) &&
3454          isUndefOrEqual(Mask[2], 2) &&
3455          isUndefOrEqual(Mask[3], 3);
3456 }
3457
3458 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3459 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3460 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3461   if (!VT.is128BitVector())
3462     return false;
3463
3464   unsigned NumElems = VT.getVectorNumElements();
3465
3466   if (NumElems != 2 && NumElems != 4)
3467     return false;
3468
3469   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3470     if (!isUndefOrEqual(Mask[i], i + NumElems))
3471       return false;
3472
3473   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3474     if (!isUndefOrEqual(Mask[i], i))
3475       return false;
3476
3477   return true;
3478 }
3479
3480 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3481 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3482 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3483   if (!VT.is128BitVector())
3484     return false;
3485
3486   unsigned NumElems = VT.getVectorNumElements();
3487
3488   if (NumElems != 2 && NumElems != 4)
3489     return false;
3490
3491   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492     if (!isUndefOrEqual(Mask[i], i))
3493       return false;
3494
3495   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3496     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3497       return false;
3498
3499   return true;
3500 }
3501
3502 //
3503 // Some special combinations that can be optimized.
3504 //
3505 static
3506 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3507                                SelectionDAG &DAG) {
3508   EVT VT = SVOp->getValueType(0);
3509   DebugLoc dl = SVOp->getDebugLoc();
3510
3511   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3512     return SDValue();
3513
3514   ArrayRef<int> Mask = SVOp->getMask();
3515
3516   // These are the special masks that may be optimized.
3517   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3518   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3519   bool MatchEvenMask = true;
3520   bool MatchOddMask  = true;
3521   for (int i=0; i<8; ++i) {
3522     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3523       MatchEvenMask = false;
3524     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3525       MatchOddMask = false;
3526   }
3527
3528   if (!MatchEvenMask && !MatchOddMask)
3529     return SDValue();
3530   
3531   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3532
3533   SDValue Op0 = SVOp->getOperand(0);
3534   SDValue Op1 = SVOp->getOperand(1);
3535
3536   if (MatchEvenMask) {
3537     // Shift the second operand right to 32 bits.
3538     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3539     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3540   } else {
3541     // Shift the first operand left to 32 bits.
3542     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3543     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3544   }
3545   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3546   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
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.is128BitVector())
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.is256BitVector())
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   if (!VT.is128BitVector())
3821     return false;
3822
3823   unsigned NumOps = VT.getVectorNumElements();
3824   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3825     return false;
3826
3827   if (!isUndefOrEqual(Mask[0], 0))
3828     return false;
3829
3830   for (unsigned i = 1; i != NumOps; ++i)
3831     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3832           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3833           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3834       return false;
3835
3836   return true;
3837 }
3838
3839 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3840 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3841 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3842 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3843                            const X86Subtarget *Subtarget) {
3844   if (!Subtarget->hasSSE3())
3845     return false;
3846
3847   unsigned NumElems = VT.getVectorNumElements();
3848
3849   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3850       (VT.getSizeInBits() == 256 && NumElems != 8))
3851     return false;
3852
3853   // "i+1" is the value the indexed mask element must have
3854   for (unsigned i = 0; i != NumElems; i += 2)
3855     if (!isUndefOrEqual(Mask[i], i+1) ||
3856         !isUndefOrEqual(Mask[i+1], i+1))
3857       return false;
3858
3859   return true;
3860 }
3861
3862 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3863 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3864 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3865 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3866                            const X86Subtarget *Subtarget) {
3867   if (!Subtarget->hasSSE3())
3868     return false;
3869
3870   unsigned NumElems = VT.getVectorNumElements();
3871
3872   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3873       (VT.getSizeInBits() == 256 && NumElems != 8))
3874     return false;
3875
3876   // "i" is the value the indexed mask element must have
3877   for (unsigned i = 0; i != NumElems; i += 2)
3878     if (!isUndefOrEqual(Mask[i], i) ||
3879         !isUndefOrEqual(Mask[i+1], i))
3880       return false;
3881
3882   return true;
3883 }
3884
3885 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3886 /// specifies a shuffle of elements that is suitable for input to 256-bit
3887 /// version of MOVDDUP.
3888 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3889   if (!HasAVX || !VT.is256BitVector())
3890     return false;
3891
3892   unsigned NumElts = VT.getVectorNumElements();
3893   if (NumElts != 4)
3894     return false;
3895
3896   for (unsigned i = 0; i != NumElts/2; ++i)
3897     if (!isUndefOrEqual(Mask[i], 0))
3898       return false;
3899   for (unsigned i = NumElts/2; i != NumElts; ++i)
3900     if (!isUndefOrEqual(Mask[i], NumElts/2))
3901       return false;
3902   return true;
3903 }
3904
3905 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to 128-bit
3907 /// version of MOVDDUP.
3908 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3909   if (!VT.is128BitVector())
3910     return false;
3911
3912   unsigned e = VT.getVectorNumElements() / 2;
3913   for (unsigned i = 0; i != e; ++i)
3914     if (!isUndefOrEqual(Mask[i], i))
3915       return false;
3916   for (unsigned i = 0; i != e; ++i)
3917     if (!isUndefOrEqual(Mask[e+i], i))
3918       return false;
3919   return true;
3920 }
3921
3922 /// isVEXTRACTF128Index - Return true if the specified
3923 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3924 /// suitable for input to VEXTRACTF128.
3925 bool X86::isVEXTRACTF128Index(SDNode *N) {
3926   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3927     return false;
3928
3929   // The index should be aligned on a 128-bit boundary.
3930   uint64_t Index =
3931     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3932
3933   unsigned VL = N->getValueType(0).getVectorNumElements();
3934   unsigned VBits = N->getValueType(0).getSizeInBits();
3935   unsigned ElSize = VBits / VL;
3936   bool Result = (Index * ElSize) % 128 == 0;
3937
3938   return Result;
3939 }
3940
3941 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3942 /// operand specifies a subvector insert that is suitable for input to
3943 /// VINSERTF128.
3944 bool X86::isVINSERTF128Index(SDNode *N) {
3945   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946     return false;
3947
3948   // The index should be aligned on a 128-bit boundary.
3949   uint64_t Index =
3950     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3951
3952   unsigned VL = N->getValueType(0).getVectorNumElements();
3953   unsigned VBits = N->getValueType(0).getSizeInBits();
3954   unsigned ElSize = VBits / VL;
3955   bool Result = (Index * ElSize) % 128 == 0;
3956
3957   return Result;
3958 }
3959
3960 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3961 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3962 /// Handles 128-bit and 256-bit.
3963 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3964   EVT VT = N->getValueType(0);
3965
3966   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3967          "Unsupported vector type for PSHUF/SHUFP");
3968
3969   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3970   // independently on 128-bit lanes.
3971   unsigned NumElts = VT.getVectorNumElements();
3972   unsigned NumLanes = VT.getSizeInBits()/128;
3973   unsigned NumLaneElts = NumElts/NumLanes;
3974
3975   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3976          "Only supports 2 or 4 elements per lane");
3977
3978   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3979   unsigned Mask = 0;
3980   for (unsigned i = 0; i != NumElts; ++i) {
3981     int Elt = N->getMaskElt(i);
3982     if (Elt < 0) continue;
3983     Elt &= NumLaneElts - 1;
3984     unsigned ShAmt = (i << Shift) % 8;
3985     Mask |= Elt << ShAmt;
3986   }
3987
3988   return Mask;
3989 }
3990
3991 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3992 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3993 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3994   EVT VT = N->getValueType(0);
3995
3996   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3997          "Unsupported vector type for PSHUFHW");
3998
3999   unsigned NumElts = VT.getVectorNumElements();
4000
4001   unsigned Mask = 0;
4002   for (unsigned l = 0; l != NumElts; l += 8) {
4003     // 8 nodes per lane, but we only care about the last 4.
4004     for (unsigned i = 0; i < 4; ++i) {
4005       int Elt = N->getMaskElt(l+i+4);
4006       if (Elt < 0) continue;
4007       Elt &= 0x3; // only 2-bits.
4008       Mask |= Elt << (i * 2);
4009     }
4010   }
4011
4012   return Mask;
4013 }
4014
4015 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4016 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4017 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4018   EVT VT = N->getValueType(0);
4019
4020   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4021          "Unsupported vector type for PSHUFHW");
4022
4023   unsigned NumElts = VT.getVectorNumElements();
4024
4025   unsigned Mask = 0;
4026   for (unsigned l = 0; l != NumElts; l += 8) {
4027     // 8 nodes per lane, but we only care about the first 4.
4028     for (unsigned i = 0; i < 4; ++i) {
4029       int Elt = N->getMaskElt(l+i);
4030       if (Elt < 0) continue;
4031       Elt &= 0x3; // only 2-bits
4032       Mask |= Elt << (i * 2);
4033     }
4034   }
4035
4036   return Mask;
4037 }
4038
4039 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4040 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4041 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4042   EVT VT = SVOp->getValueType(0);
4043   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4044
4045   unsigned NumElts = VT.getVectorNumElements();
4046   unsigned NumLanes = VT.getSizeInBits()/128;
4047   unsigned NumLaneElts = NumElts/NumLanes;
4048
4049   int Val = 0;
4050   unsigned i;
4051   for (i = 0; i != NumElts; ++i) {
4052     Val = SVOp->getMaskElt(i);
4053     if (Val >= 0)
4054       break;
4055   }
4056   if (Val >= (int)NumElts)
4057     Val -= NumElts - NumLaneElts;
4058
4059   assert(Val - i > 0 && "PALIGNR imm should be positive");
4060   return (Val - i) * EltSize;
4061 }
4062
4063 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4064 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4065 /// instructions.
4066 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4067   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4068     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4069
4070   uint64_t Index =
4071     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4072
4073   EVT VecVT = N->getOperand(0).getValueType();
4074   EVT ElVT = VecVT.getVectorElementType();
4075
4076   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4077   return Index / NumElemsPerChunk;
4078 }
4079
4080 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4081 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4082 /// instructions.
4083 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4084   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4085     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4086
4087   uint64_t Index =
4088     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4089
4090   EVT VecVT = N->getValueType(0);
4091   EVT ElVT = VecVT.getVectorElementType();
4092
4093   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4094   return Index / NumElemsPerChunk;
4095 }
4096
4097 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4098 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4099 /// Handles 256-bit.
4100 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4101   EVT VT = N->getValueType(0);
4102
4103   unsigned NumElts = VT.getVectorNumElements();
4104
4105   assert((VT.is256BitVector() && NumElts == 4) &&
4106          "Unsupported vector type for VPERMQ/VPERMPD");
4107
4108   unsigned Mask = 0;
4109   for (unsigned i = 0; i != NumElts; ++i) {
4110     int Elt = N->getMaskElt(i);
4111     if (Elt < 0)
4112       continue;
4113     Mask |= Elt << (i*2);
4114   }
4115
4116   return Mask;
4117 }
4118 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4119 /// constant +0.0.
4120 bool X86::isZeroNode(SDValue Elt) {
4121   return ((isa<ConstantSDNode>(Elt) &&
4122            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4123           (isa<ConstantFPSDNode>(Elt) &&
4124            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4125 }
4126
4127 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4128 /// their permute mask.
4129 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4130                                     SelectionDAG &DAG) {
4131   EVT VT = SVOp->getValueType(0);
4132   unsigned NumElems = VT.getVectorNumElements();
4133   SmallVector<int, 8> MaskVec;
4134
4135   for (unsigned i = 0; i != NumElems; ++i) {
4136     int Idx = SVOp->getMaskElt(i);
4137     if (Idx >= 0) {
4138       if (Idx < (int)NumElems)
4139         Idx += NumElems;
4140       else
4141         Idx -= NumElems;
4142     }
4143     MaskVec.push_back(Idx);
4144   }
4145   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4146                               SVOp->getOperand(0), &MaskVec[0]);
4147 }
4148
4149 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4150 /// match movhlps. The lower half elements should come from upper half of
4151 /// V1 (and in order), and the upper half elements should come from the upper
4152 /// half of V2 (and in order).
4153 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4154   if (!VT.is128BitVector())
4155     return false;
4156   if (VT.getVectorNumElements() != 4)
4157     return false;
4158   for (unsigned i = 0, e = 2; i != e; ++i)
4159     if (!isUndefOrEqual(Mask[i], i+2))
4160       return false;
4161   for (unsigned i = 2; i != 4; ++i)
4162     if (!isUndefOrEqual(Mask[i], i+4))
4163       return false;
4164   return true;
4165 }
4166
4167 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4168 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4169 /// required.
4170 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4171   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4172     return false;
4173   N = N->getOperand(0).getNode();
4174   if (!ISD::isNON_EXTLoad(N))
4175     return false;
4176   if (LD)
4177     *LD = cast<LoadSDNode>(N);
4178   return true;
4179 }
4180
4181 // Test whether the given value is a vector value which will be legalized
4182 // into a load.
4183 static bool WillBeConstantPoolLoad(SDNode *N) {
4184   if (N->getOpcode() != ISD::BUILD_VECTOR)
4185     return false;
4186
4187   // Check for any non-constant elements.
4188   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4189     switch (N->getOperand(i).getNode()->getOpcode()) {
4190     case ISD::UNDEF:
4191     case ISD::ConstantFP:
4192     case ISD::Constant:
4193       break;
4194     default:
4195       return false;
4196     }
4197
4198   // Vectors of all-zeros and all-ones are materialized with special
4199   // instructions rather than being loaded.
4200   return !ISD::isBuildVectorAllZeros(N) &&
4201          !ISD::isBuildVectorAllOnes(N);
4202 }
4203
4204 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4205 /// match movlp{s|d}. The lower half elements should come from lower half of
4206 /// V1 (and in order), and the upper half elements should come from the upper
4207 /// half of V2 (and in order). And since V1 will become the source of the
4208 /// MOVLP, it must be either a vector load or a scalar load to vector.
4209 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4210                                ArrayRef<int> Mask, EVT VT) {
4211   if (!VT.is128BitVector())
4212     return false;
4213
4214   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4215     return false;
4216   // Is V2 is a vector load, don't do this transformation. We will try to use
4217   // load folding shufps op.
4218   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4219     return false;
4220
4221   unsigned NumElems = VT.getVectorNumElements();
4222
4223   if (NumElems != 2 && NumElems != 4)
4224     return false;
4225   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4226     if (!isUndefOrEqual(Mask[i], i))
4227       return false;
4228   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4229     if (!isUndefOrEqual(Mask[i], i+NumElems))
4230       return false;
4231   return true;
4232 }
4233
4234 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4235 /// all the same.
4236 static bool isSplatVector(SDNode *N) {
4237   if (N->getOpcode() != ISD::BUILD_VECTOR)
4238     return false;
4239
4240   SDValue SplatValue = N->getOperand(0);
4241   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4242     if (N->getOperand(i) != SplatValue)
4243       return false;
4244   return true;
4245 }
4246
4247 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4248 /// to an zero vector.
4249 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4250 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4251   SDValue V1 = N->getOperand(0);
4252   SDValue V2 = N->getOperand(1);
4253   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4254   for (unsigned i = 0; i != NumElems; ++i) {
4255     int Idx = N->getMaskElt(i);
4256     if (Idx >= (int)NumElems) {
4257       unsigned Opc = V2.getOpcode();
4258       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4259         continue;
4260       if (Opc != ISD::BUILD_VECTOR ||
4261           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4262         return false;
4263     } else if (Idx >= 0) {
4264       unsigned Opc = V1.getOpcode();
4265       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4266         continue;
4267       if (Opc != ISD::BUILD_VECTOR ||
4268           !X86::isZeroNode(V1.getOperand(Idx)))
4269         return false;
4270     }
4271   }
4272   return true;
4273 }
4274
4275 /// getZeroVector - Returns a vector of specified type with all zero elements.
4276 ///
4277 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4278                              SelectionDAG &DAG, DebugLoc dl) {
4279   assert(VT.isVector() && "Expected a vector type");
4280   unsigned Size = VT.getSizeInBits();
4281
4282   // Always build SSE zero vectors as <4 x i32> bitcasted
4283   // to their dest type. This ensures they get CSE'd.
4284   SDValue Vec;
4285   if (Size == 128) {  // SSE
4286     if (Subtarget->hasSSE2()) {  // SSE2
4287       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4288       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4289     } else { // SSE1
4290       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4291       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4292     }
4293   } else if (Size == 256) { // AVX
4294     if (Subtarget->hasAVX2()) { // AVX2
4295       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4296       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4297       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4298     } else {
4299       // 256-bit logic and arithmetic instructions in AVX are all
4300       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4301       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4302       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4303       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4304     }
4305   } else
4306     llvm_unreachable("Unexpected vector type");
4307
4308   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4309 }
4310
4311 /// getOnesVector - Returns a vector of specified type with all bits set.
4312 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4313 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4314 /// Then bitcast to their original type, ensuring they get CSE'd.
4315 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4316                              DebugLoc dl) {
4317   assert(VT.isVector() && "Expected a vector type");
4318   unsigned Size = VT.getSizeInBits();
4319
4320   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4321   SDValue Vec;
4322   if (Size == 256) {
4323     if (HasAVX2) { // AVX2
4324       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4325       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4326     } else { // AVX
4327       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4328       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4329     }
4330   } else if (Size == 128) {
4331     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4332   } else
4333     llvm_unreachable("Unexpected vector type");
4334
4335   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4336 }
4337
4338 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4339 /// that point to V2 points to its first element.
4340 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4341   for (unsigned i = 0; i != NumElems; ++i) {
4342     if (Mask[i] > (int)NumElems) {
4343       Mask[i] = NumElems;
4344     }
4345   }
4346 }
4347
4348 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4349 /// operation of specified width.
4350 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4351                        SDValue V2) {
4352   unsigned NumElems = VT.getVectorNumElements();
4353   SmallVector<int, 8> Mask;
4354   Mask.push_back(NumElems);
4355   for (unsigned i = 1; i != NumElems; ++i)
4356     Mask.push_back(i);
4357   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4358 }
4359
4360 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4361 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4362                           SDValue V2) {
4363   unsigned NumElems = VT.getVectorNumElements();
4364   SmallVector<int, 8> Mask;
4365   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4366     Mask.push_back(i);
4367     Mask.push_back(i + NumElems);
4368   }
4369   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4370 }
4371
4372 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4373 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4374                           SDValue V2) {
4375   unsigned NumElems = VT.getVectorNumElements();
4376   SmallVector<int, 8> Mask;
4377   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4378     Mask.push_back(i + Half);
4379     Mask.push_back(i + NumElems + Half);
4380   }
4381   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4382 }
4383
4384 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4385 // a generic shuffle instruction because the target has no such instructions.
4386 // Generate shuffles which repeat i16 and i8 several times until they can be
4387 // represented by v4f32 and then be manipulated by target suported shuffles.
4388 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4389   EVT VT = V.getValueType();
4390   int NumElems = VT.getVectorNumElements();
4391   DebugLoc dl = V.getDebugLoc();
4392
4393   while (NumElems > 4) {
4394     if (EltNo < NumElems/2) {
4395       V = getUnpackl(DAG, dl, VT, V, V);
4396     } else {
4397       V = getUnpackh(DAG, dl, VT, V, V);
4398       EltNo -= NumElems/2;
4399     }
4400     NumElems >>= 1;
4401   }
4402   return V;
4403 }
4404
4405 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4406 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4407   EVT VT = V.getValueType();
4408   DebugLoc dl = V.getDebugLoc();
4409   unsigned Size = VT.getSizeInBits();
4410
4411   if (Size == 128) {
4412     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4413     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4414     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4415                              &SplatMask[0]);
4416   } else if (Size == 256) {
4417     // To use VPERMILPS to splat scalars, the second half of indicies must
4418     // refer to the higher part, which is a duplication of the lower one,
4419     // because VPERMILPS can only handle in-lane permutations.
4420     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4421                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4422
4423     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4424     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4425                              &SplatMask[0]);
4426   } else
4427     llvm_unreachable("Vector size not supported");
4428
4429   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4430 }
4431
4432 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4433 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4434   EVT SrcVT = SV->getValueType(0);
4435   SDValue V1 = SV->getOperand(0);
4436   DebugLoc dl = SV->getDebugLoc();
4437
4438   int EltNo = SV->getSplatIndex();
4439   int NumElems = SrcVT.getVectorNumElements();
4440   unsigned Size = SrcVT.getSizeInBits();
4441
4442   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4443           "Unknown how to promote splat for type");
4444
4445   // Extract the 128-bit part containing the splat element and update
4446   // the splat element index when it refers to the higher register.
4447   if (Size == 256) {
4448     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4449     if (EltNo >= NumElems/2)
4450       EltNo -= NumElems/2;
4451   }
4452
4453   // All i16 and i8 vector types can't be used directly by a generic shuffle
4454   // instruction because the target has no such instruction. Generate shuffles
4455   // which repeat i16 and i8 several times until they fit in i32, and then can
4456   // be manipulated by target suported shuffles.
4457   EVT EltVT = SrcVT.getVectorElementType();
4458   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4459     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4460
4461   // Recreate the 256-bit vector and place the same 128-bit vector
4462   // into the low and high part. This is necessary because we want
4463   // to use VPERM* to shuffle the vectors
4464   if (Size == 256) {
4465     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4466   }
4467
4468   return getLegalSplat(DAG, V1, EltNo);
4469 }
4470
4471 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4472 /// vector of zero or undef vector.  This produces a shuffle where the low
4473 /// element of V2 is swizzled into the zero/undef vector, landing at element
4474 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4475 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4476                                            bool IsZero,
4477                                            const X86Subtarget *Subtarget,
4478                                            SelectionDAG &DAG) {
4479   EVT VT = V2.getValueType();
4480   SDValue V1 = IsZero
4481     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4482   unsigned NumElems = VT.getVectorNumElements();
4483   SmallVector<int, 16> MaskVec;
4484   for (unsigned i = 0; i != NumElems; ++i)
4485     // If this is the insertion idx, put the low elt of V2 here.
4486     MaskVec.push_back(i == Idx ? NumElems : i);
4487   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4488 }
4489
4490 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4491 /// target specific opcode. Returns true if the Mask could be calculated.
4492 /// Sets IsUnary to true if only uses one source.
4493 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4494                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4495   unsigned NumElems = VT.getVectorNumElements();
4496   SDValue ImmN;
4497
4498   IsUnary = false;
4499   switch(N->getOpcode()) {
4500   case X86ISD::SHUFP:
4501     ImmN = N->getOperand(N->getNumOperands()-1);
4502     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4503     break;
4504   case X86ISD::UNPCKH:
4505     DecodeUNPCKHMask(VT, Mask);
4506     break;
4507   case X86ISD::UNPCKL:
4508     DecodeUNPCKLMask(VT, Mask);
4509     break;
4510   case X86ISD::MOVHLPS:
4511     DecodeMOVHLPSMask(NumElems, Mask);
4512     break;
4513   case X86ISD::MOVLHPS:
4514     DecodeMOVLHPSMask(NumElems, Mask);
4515     break;
4516   case X86ISD::PSHUFD:
4517   case X86ISD::VPERMILP:
4518     ImmN = N->getOperand(N->getNumOperands()-1);
4519     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4520     IsUnary = true;
4521     break;
4522   case X86ISD::PSHUFHW:
4523     ImmN = N->getOperand(N->getNumOperands()-1);
4524     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4525     IsUnary = true;
4526     break;
4527   case X86ISD::PSHUFLW:
4528     ImmN = N->getOperand(N->getNumOperands()-1);
4529     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4530     IsUnary = true;
4531     break;
4532   case X86ISD::VPERMI:
4533     ImmN = N->getOperand(N->getNumOperands()-1);
4534     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4535     IsUnary = true;
4536     break;
4537   case X86ISD::MOVSS:
4538   case X86ISD::MOVSD: {
4539     // The index 0 always comes from the first element of the second source,
4540     // this is why MOVSS and MOVSD are used in the first place. The other
4541     // elements come from the other positions of the first source vector
4542     Mask.push_back(NumElems);
4543     for (unsigned i = 1; i != NumElems; ++i) {
4544       Mask.push_back(i);
4545     }
4546     break;
4547   }
4548   case X86ISD::VPERM2X128:
4549     ImmN = N->getOperand(N->getNumOperands()-1);
4550     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551     if (Mask.empty()) return false;
4552     break;
4553   case X86ISD::MOVDDUP:
4554   case X86ISD::MOVLHPD:
4555   case X86ISD::MOVLPD:
4556   case X86ISD::MOVLPS:
4557   case X86ISD::MOVSHDUP:
4558   case X86ISD::MOVSLDUP:
4559   case X86ISD::PALIGN:
4560     // Not yet implemented
4561     return false;
4562   default: llvm_unreachable("unknown target shuffle node");
4563   }
4564
4565   return true;
4566 }
4567
4568 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4569 /// element of the result of the vector shuffle.
4570 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4571                                    unsigned Depth) {
4572   if (Depth == 6)
4573     return SDValue();  // Limit search depth.
4574
4575   SDValue V = SDValue(N, 0);
4576   EVT VT = V.getValueType();
4577   unsigned Opcode = V.getOpcode();
4578
4579   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4580   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4581     int Elt = SV->getMaskElt(Index);
4582
4583     if (Elt < 0)
4584       return DAG.getUNDEF(VT.getVectorElementType());
4585
4586     unsigned NumElems = VT.getVectorNumElements();
4587     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4588                                          : SV->getOperand(1);
4589     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4590   }
4591
4592   // Recurse into target specific vector shuffles to find scalars.
4593   if (isTargetShuffle(Opcode)) {
4594     MVT ShufVT = V.getValueType().getSimpleVT();
4595     unsigned NumElems = ShufVT.getVectorNumElements();
4596     SmallVector<int, 16> ShuffleMask;
4597     SDValue ImmN;
4598     bool IsUnary;
4599
4600     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4601       return SDValue();
4602
4603     int Elt = ShuffleMask[Index];
4604     if (Elt < 0)
4605       return DAG.getUNDEF(ShufVT.getVectorElementType());
4606
4607     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4608                                          : N->getOperand(1);
4609     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4610                                Depth+1);
4611   }
4612
4613   // Actual nodes that may contain scalar elements
4614   if (Opcode == ISD::BITCAST) {
4615     V = V.getOperand(0);
4616     EVT SrcVT = V.getValueType();
4617     unsigned NumElems = VT.getVectorNumElements();
4618
4619     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4620       return SDValue();
4621   }
4622
4623   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4624     return (Index == 0) ? V.getOperand(0)
4625                         : DAG.getUNDEF(VT.getVectorElementType());
4626
4627   if (V.getOpcode() == ISD::BUILD_VECTOR)
4628     return V.getOperand(Index);
4629
4630   return SDValue();
4631 }
4632
4633 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4634 /// shuffle operation which come from a consecutively from a zero. The
4635 /// search can start in two different directions, from left or right.
4636 static
4637 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4638                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4639   unsigned i;
4640   for (i = 0; i != NumElems; ++i) {
4641     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4642     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4643     if (!(Elt.getNode() &&
4644          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4645       break;
4646   }
4647
4648   return i;
4649 }
4650
4651 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4652 /// correspond consecutively to elements from one of the vector operands,
4653 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4654 static
4655 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4656                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4657                               unsigned NumElems, unsigned &OpNum) {
4658   bool SeenV1 = false;
4659   bool SeenV2 = false;
4660
4661   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4662     int Idx = SVOp->getMaskElt(i);
4663     // Ignore undef indicies
4664     if (Idx < 0)
4665       continue;
4666
4667     if (Idx < (int)NumElems)
4668       SeenV1 = true;
4669     else
4670       SeenV2 = true;
4671
4672     // Only accept consecutive elements from the same vector
4673     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4674       return false;
4675   }
4676
4677   OpNum = SeenV1 ? 0 : 1;
4678   return true;
4679 }
4680
4681 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4682 /// logical left shift of a vector.
4683 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4684                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4685   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4686   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4687               false /* check zeros from right */, DAG);
4688   unsigned OpSrc;
4689
4690   if (!NumZeros)
4691     return false;
4692
4693   // Considering the elements in the mask that are not consecutive zeros,
4694   // check if they consecutively come from only one of the source vectors.
4695   //
4696   //               V1 = {X, A, B, C}     0
4697   //                         \  \  \    /
4698   //   vector_shuffle V1, V2 <1, 2, 3, X>
4699   //
4700   if (!isShuffleMaskConsecutive(SVOp,
4701             0,                   // Mask Start Index
4702             NumElems-NumZeros,   // Mask End Index(exclusive)
4703             NumZeros,            // Where to start looking in the src vector
4704             NumElems,            // Number of elements in vector
4705             OpSrc))              // Which source operand ?
4706     return false;
4707
4708   isLeft = false;
4709   ShAmt = NumZeros;
4710   ShVal = SVOp->getOperand(OpSrc);
4711   return true;
4712 }
4713
4714 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4715 /// logical left shift of a vector.
4716 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4717                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4718   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4719   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4720               true /* check zeros from left */, DAG);
4721   unsigned OpSrc;
4722
4723   if (!NumZeros)
4724     return false;
4725
4726   // Considering the elements in the mask that are not consecutive zeros,
4727   // check if they consecutively come from only one of the source vectors.
4728   //
4729   //                           0    { A, B, X, X } = V2
4730   //                          / \    /  /
4731   //   vector_shuffle V1, V2 <X, X, 4, 5>
4732   //
4733   if (!isShuffleMaskConsecutive(SVOp,
4734             NumZeros,     // Mask Start Index
4735             NumElems,     // Mask End Index(exclusive)
4736             0,            // Where to start looking in the src vector
4737             NumElems,     // Number of elements in vector
4738             OpSrc))       // Which source operand ?
4739     return false;
4740
4741   isLeft = true;
4742   ShAmt = NumZeros;
4743   ShVal = SVOp->getOperand(OpSrc);
4744   return true;
4745 }
4746
4747 /// isVectorShift - Returns true if the shuffle can be implemented as a
4748 /// logical left or right shift of a vector.
4749 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4750                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4751   // Although the logic below support any bitwidth size, there are no
4752   // shift instructions which handle more than 128-bit vectors.
4753   if (!SVOp->getValueType(0).is128BitVector())
4754     return false;
4755
4756   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4757       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4758     return true;
4759
4760   return false;
4761 }
4762
4763 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4764 ///
4765 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4766                                        unsigned NumNonZero, unsigned NumZero,
4767                                        SelectionDAG &DAG,
4768                                        const X86Subtarget* Subtarget,
4769                                        const TargetLowering &TLI) {
4770   if (NumNonZero > 8)
4771     return SDValue();
4772
4773   DebugLoc dl = Op.getDebugLoc();
4774   SDValue V(0, 0);
4775   bool First = true;
4776   for (unsigned i = 0; i < 16; ++i) {
4777     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4778     if (ThisIsNonZero && First) {
4779       if (NumZero)
4780         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4781       else
4782         V = DAG.getUNDEF(MVT::v8i16);
4783       First = false;
4784     }
4785
4786     if ((i & 1) != 0) {
4787       SDValue ThisElt(0, 0), LastElt(0, 0);
4788       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4789       if (LastIsNonZero) {
4790         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4791                               MVT::i16, Op.getOperand(i-1));
4792       }
4793       if (ThisIsNonZero) {
4794         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4795         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4796                               ThisElt, DAG.getConstant(8, MVT::i8));
4797         if (LastIsNonZero)
4798           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4799       } else
4800         ThisElt = LastElt;
4801
4802       if (ThisElt.getNode())
4803         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4804                         DAG.getIntPtrConstant(i/2));
4805     }
4806   }
4807
4808   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4809 }
4810
4811 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4812 ///
4813 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4814                                      unsigned NumNonZero, unsigned NumZero,
4815                                      SelectionDAG &DAG,
4816                                      const X86Subtarget* Subtarget,
4817                                      const TargetLowering &TLI) {
4818   if (NumNonZero > 4)
4819     return SDValue();
4820
4821   DebugLoc dl = Op.getDebugLoc();
4822   SDValue V(0, 0);
4823   bool First = true;
4824   for (unsigned i = 0; i < 8; ++i) {
4825     bool isNonZero = (NonZeros & (1 << i)) != 0;
4826     if (isNonZero) {
4827       if (First) {
4828         if (NumZero)
4829           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4830         else
4831           V = DAG.getUNDEF(MVT::v8i16);
4832         First = false;
4833       }
4834       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4835                       MVT::v8i16, V, Op.getOperand(i),
4836                       DAG.getIntPtrConstant(i));
4837     }
4838   }
4839
4840   return V;
4841 }
4842
4843 /// getVShift - Return a vector logical shift node.
4844 ///
4845 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4846                          unsigned NumBits, SelectionDAG &DAG,
4847                          const TargetLowering &TLI, DebugLoc dl) {
4848   assert(VT.is128BitVector() && "Unknown type for VShift");
4849   EVT ShVT = MVT::v2i64;
4850   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4851   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4852   return DAG.getNode(ISD::BITCAST, dl, VT,
4853                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4854                              DAG.getConstant(NumBits,
4855                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4856 }
4857
4858 SDValue
4859 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4860                                           SelectionDAG &DAG) const {
4861
4862   // Check if the scalar load can be widened into a vector load. And if
4863   // the address is "base + cst" see if the cst can be "absorbed" into
4864   // the shuffle mask.
4865   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4866     SDValue Ptr = LD->getBasePtr();
4867     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4868       return SDValue();
4869     EVT PVT = LD->getValueType(0);
4870     if (PVT != MVT::i32 && PVT != MVT::f32)
4871       return SDValue();
4872
4873     int FI = -1;
4874     int64_t Offset = 0;
4875     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4876       FI = FINode->getIndex();
4877       Offset = 0;
4878     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4879                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4880       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4881       Offset = Ptr.getConstantOperandVal(1);
4882       Ptr = Ptr.getOperand(0);
4883     } else {
4884       return SDValue();
4885     }
4886
4887     // FIXME: 256-bit vector instructions don't require a strict alignment,
4888     // improve this code to support it better.
4889     unsigned RequiredAlign = VT.getSizeInBits()/8;
4890     SDValue Chain = LD->getChain();
4891     // Make sure the stack object alignment is at least 16 or 32.
4892     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4893     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4894       if (MFI->isFixedObjectIndex(FI)) {
4895         // Can't change the alignment. FIXME: It's possible to compute
4896         // the exact stack offset and reference FI + adjust offset instead.
4897         // If someone *really* cares about this. That's the way to implement it.
4898         return SDValue();
4899       } else {
4900         MFI->setObjectAlignment(FI, RequiredAlign);
4901       }
4902     }
4903
4904     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4905     // Ptr + (Offset & ~15).
4906     if (Offset < 0)
4907       return SDValue();
4908     if ((Offset % RequiredAlign) & 3)
4909       return SDValue();
4910     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4911     if (StartOffset)
4912       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4913                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4914
4915     int EltNo = (Offset - StartOffset) >> 2;
4916     unsigned NumElems = VT.getVectorNumElements();
4917
4918     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4919     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4920                              LD->getPointerInfo().getWithOffset(StartOffset),
4921                              false, false, false, 0);
4922
4923     SmallVector<int, 8> Mask;
4924     for (unsigned i = 0; i != NumElems; ++i)
4925       Mask.push_back(EltNo);
4926
4927     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4928   }
4929
4930   return SDValue();
4931 }
4932
4933 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4934 /// vector of type 'VT', see if the elements can be replaced by a single large
4935 /// load which has the same value as a build_vector whose operands are 'elts'.
4936 ///
4937 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4938 ///
4939 /// FIXME: we'd also like to handle the case where the last elements are zero
4940 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4941 /// There's even a handy isZeroNode for that purpose.
4942 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4943                                         DebugLoc &DL, SelectionDAG &DAG) {
4944   EVT EltVT = VT.getVectorElementType();
4945   unsigned NumElems = Elts.size();
4946
4947   LoadSDNode *LDBase = NULL;
4948   unsigned LastLoadedElt = -1U;
4949
4950   // For each element in the initializer, see if we've found a load or an undef.
4951   // If we don't find an initial load element, or later load elements are
4952   // non-consecutive, bail out.
4953   for (unsigned i = 0; i < NumElems; ++i) {
4954     SDValue Elt = Elts[i];
4955
4956     if (!Elt.getNode() ||
4957         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4958       return SDValue();
4959     if (!LDBase) {
4960       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4961         return SDValue();
4962       LDBase = cast<LoadSDNode>(Elt.getNode());
4963       LastLoadedElt = i;
4964       continue;
4965     }
4966     if (Elt.getOpcode() == ISD::UNDEF)
4967       continue;
4968
4969     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4970     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4971       return SDValue();
4972     LastLoadedElt = i;
4973   }
4974
4975   // If we have found an entire vector of loads and undefs, then return a large
4976   // load of the entire vector width starting at the base pointer.  If we found
4977   // consecutive loads for the low half, generate a vzext_load node.
4978   if (LastLoadedElt == NumElems - 1) {
4979     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4980       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4981                          LDBase->getPointerInfo(),
4982                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4983                          LDBase->isInvariant(), 0);
4984     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4985                        LDBase->getPointerInfo(),
4986                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4987                        LDBase->isInvariant(), LDBase->getAlignment());
4988   }
4989   if (NumElems == 4 && LastLoadedElt == 1 &&
4990       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4991     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4992     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4993     SDValue ResNode =
4994         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4995                                 LDBase->getPointerInfo(),
4996                                 LDBase->getAlignment(),
4997                                 false/*isVolatile*/, true/*ReadMem*/,
4998                                 false/*WriteMem*/);
4999
5000     // Make sure the newly-created LOAD is in the same position as LDBase in
5001     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5002     // update uses of LDBase's output chain to use the TokenFactor.
5003     if (LDBase->hasAnyUseOfValue(1)) {
5004       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5005                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5006       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5007       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5008                              SDValue(ResNode.getNode(), 1));
5009     }
5010
5011     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5012   }
5013   return SDValue();
5014 }
5015
5016 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5017 /// to generate a splat value for the following cases:
5018 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5019 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5020 /// a scalar load, or a constant.
5021 /// The VBROADCAST node is returned when a pattern is found,
5022 /// or SDValue() otherwise.
5023 SDValue
5024 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5025   if (!Subtarget->hasAVX())
5026     return SDValue();
5027
5028   EVT VT = Op.getValueType();
5029   DebugLoc dl = Op.getDebugLoc();
5030
5031   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5032          "Unsupported vector type for broadcast.");
5033
5034   SDValue Ld;
5035   bool ConstSplatVal;
5036
5037   switch (Op.getOpcode()) {
5038     default:
5039       // Unknown pattern found.
5040       return SDValue();
5041
5042     case ISD::BUILD_VECTOR: {
5043       // The BUILD_VECTOR node must be a splat.
5044       if (!isSplatVector(Op.getNode()))
5045         return SDValue();
5046
5047       Ld = Op.getOperand(0);
5048       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5049                      Ld.getOpcode() == ISD::ConstantFP);
5050
5051       // The suspected load node has several users. Make sure that all
5052       // of its users are from the BUILD_VECTOR node.
5053       // Constants may have multiple users.
5054       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5055         return SDValue();
5056       break;
5057     }
5058
5059     case ISD::VECTOR_SHUFFLE: {
5060       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5061
5062       // Shuffles must have a splat mask where the first element is
5063       // broadcasted.
5064       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5065         return SDValue();
5066
5067       SDValue Sc = Op.getOperand(0);
5068       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5069           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5070
5071         if (!Subtarget->hasAVX2())
5072           return SDValue();
5073
5074         // Use the register form of the broadcast instruction available on AVX2.
5075         if (VT.is256BitVector())
5076           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5077         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5078       }
5079
5080       Ld = Sc.getOperand(0);
5081       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5082                        Ld.getOpcode() == ISD::ConstantFP);
5083
5084       // The scalar_to_vector node and the suspected
5085       // load node must have exactly one user.
5086       // Constants may have multiple users.
5087       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5088         return SDValue();
5089       break;
5090     }
5091   }
5092
5093   bool Is256 = VT.is256BitVector();
5094
5095   // Handle the broadcasting a single constant scalar from the constant pool
5096   // into a vector. On Sandybridge it is still better to load a constant vector
5097   // from the constant pool and not to broadcast it from a scalar.
5098   if (ConstSplatVal && Subtarget->hasAVX2()) {
5099     EVT CVT = Ld.getValueType();
5100     assert(!CVT.isVector() && "Must not broadcast a vector type");
5101     unsigned ScalarSize = CVT.getSizeInBits();
5102
5103     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5104       const Constant *C = 0;
5105       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5106         C = CI->getConstantIntValue();
5107       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5108         C = CF->getConstantFPValue();
5109
5110       assert(C && "Invalid constant type");
5111
5112       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5113       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5114       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5115                        MachinePointerInfo::getConstantPool(),
5116                        false, false, false, Alignment);
5117
5118       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5119     }
5120   }
5121
5122   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5123   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5124
5125   // Handle AVX2 in-register broadcasts.
5126   if (!IsLoad && Subtarget->hasAVX2() &&
5127       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5128     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5129
5130   // The scalar source must be a normal load.
5131   if (!IsLoad)
5132     return SDValue();
5133
5134   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5135     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5136
5137   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5138   // double since there is no vbroadcastsd xmm
5139   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5140     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5141       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5142   }
5143
5144   // Unsupported broadcast.
5145   return SDValue();
5146 }
5147
5148 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5149 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5150 // constraint of matching input/output vector elements.
5151 SDValue
5152 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5153   DebugLoc DL = Op.getDebugLoc();
5154   SDNode *N = Op.getNode();
5155   EVT VT = Op.getValueType();
5156   unsigned NumElts = Op.getNumOperands();
5157
5158   // Check supported types and sub-targets.
5159   //
5160   // Only v2f32 -> v2f64 needs special handling.
5161   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5162     return SDValue();
5163
5164   SDValue VecIn;
5165   EVT VecInVT;
5166   SmallVector<int, 8> Mask;
5167   EVT SrcVT = MVT::Other;
5168
5169   // Check the patterns could be translated into X86vfpext.
5170   for (unsigned i = 0; i < NumElts; ++i) {
5171     SDValue In = N->getOperand(i);
5172     unsigned Opcode = In.getOpcode();
5173
5174     // Skip if the element is undefined.
5175     if (Opcode == ISD::UNDEF) {
5176       Mask.push_back(-1);
5177       continue;
5178     }
5179
5180     // Quit if one of the elements is not defined from 'fpext'.
5181     if (Opcode != ISD::FP_EXTEND)
5182       return SDValue();
5183
5184     // Check how the source of 'fpext' is defined.
5185     SDValue L2In = In.getOperand(0);
5186     EVT L2InVT = L2In.getValueType();
5187
5188     // Check the original type
5189     if (SrcVT == MVT::Other)
5190       SrcVT = L2InVT;
5191     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5192       return SDValue();
5193
5194     // Check whether the value being 'fpext'ed is extracted from the same
5195     // source.
5196     Opcode = L2In.getOpcode();
5197
5198     // Quit if it's not extracted with a constant index.
5199     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5200         !isa<ConstantSDNode>(L2In.getOperand(1)))
5201       return SDValue();
5202
5203     SDValue ExtractedFromVec = L2In.getOperand(0);
5204
5205     if (VecIn.getNode() == 0) {
5206       VecIn = ExtractedFromVec;
5207       VecInVT = ExtractedFromVec.getValueType();
5208     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5209       return SDValue();
5210
5211     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5212   }
5213
5214   // Quit if all operands of BUILD_VECTOR are undefined.
5215   if (!VecIn.getNode())
5216     return SDValue();
5217
5218   // Fill the remaining mask as undef.
5219   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5220     Mask.push_back(-1);
5221
5222   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5223                      DAG.getVectorShuffle(VecInVT, DL,
5224                                           VecIn, DAG.getUNDEF(VecInVT),
5225                                           &Mask[0]));
5226 }
5227
5228 SDValue
5229 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5230   DebugLoc dl = Op.getDebugLoc();
5231
5232   EVT VT = Op.getValueType();
5233   EVT ExtVT = VT.getVectorElementType();
5234   unsigned NumElems = Op.getNumOperands();
5235
5236   // Vectors containing all zeros can be matched by pxor and xorps later
5237   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5238     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5239     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5240     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5241       return Op;
5242
5243     return getZeroVector(VT, Subtarget, DAG, dl);
5244   }
5245
5246   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5247   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5248   // vpcmpeqd on 256-bit vectors.
5249   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5250     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5251       return Op;
5252
5253     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5254   }
5255
5256   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5257   if (Broadcast.getNode())
5258     return Broadcast;
5259
5260   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5261   if (FpExt.getNode())
5262     return FpExt;
5263
5264   unsigned EVTBits = ExtVT.getSizeInBits();
5265
5266   unsigned NumZero  = 0;
5267   unsigned NumNonZero = 0;
5268   unsigned NonZeros = 0;
5269   bool IsAllConstants = true;
5270   SmallSet<SDValue, 8> Values;
5271   for (unsigned i = 0; i < NumElems; ++i) {
5272     SDValue Elt = Op.getOperand(i);
5273     if (Elt.getOpcode() == ISD::UNDEF)
5274       continue;
5275     Values.insert(Elt);
5276     if (Elt.getOpcode() != ISD::Constant &&
5277         Elt.getOpcode() != ISD::ConstantFP)
5278       IsAllConstants = false;
5279     if (X86::isZeroNode(Elt))
5280       NumZero++;
5281     else {
5282       NonZeros |= (1 << i);
5283       NumNonZero++;
5284     }
5285   }
5286
5287   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5288   if (NumNonZero == 0)
5289     return DAG.getUNDEF(VT);
5290
5291   // Special case for single non-zero, non-undef, element.
5292   if (NumNonZero == 1) {
5293     unsigned Idx = CountTrailingZeros_32(NonZeros);
5294     SDValue Item = Op.getOperand(Idx);
5295
5296     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5297     // the value are obviously zero, truncate the value to i32 and do the
5298     // insertion that way.  Only do this if the value is non-constant or if the
5299     // value is a constant being inserted into element 0.  It is cheaper to do
5300     // a constant pool load than it is to do a movd + shuffle.
5301     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5302         (!IsAllConstants || Idx == 0)) {
5303       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5304         // Handle SSE only.
5305         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5306         EVT VecVT = MVT::v4i32;
5307         unsigned VecElts = 4;
5308
5309         // Truncate the value (which may itself be a constant) to i32, and
5310         // convert it to a vector with movd (S2V+shuffle to zero extend).
5311         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5312         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5313         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5314
5315         // Now we have our 32-bit value zero extended in the low element of
5316         // a vector.  If Idx != 0, swizzle it into place.
5317         if (Idx != 0) {
5318           SmallVector<int, 4> Mask;
5319           Mask.push_back(Idx);
5320           for (unsigned i = 1; i != VecElts; ++i)
5321             Mask.push_back(i);
5322           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5323                                       &Mask[0]);
5324         }
5325         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5326       }
5327     }
5328
5329     // If we have a constant or non-constant insertion into the low element of
5330     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5331     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5332     // depending on what the source datatype is.
5333     if (Idx == 0) {
5334       if (NumZero == 0)
5335         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5336
5337       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5338           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5339         if (VT.is256BitVector()) {
5340           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5341           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5342                              Item, DAG.getIntPtrConstant(0));
5343         }
5344         assert(VT.is128BitVector() && "Expected an SSE value type!");
5345         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5346         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5347         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5348       }
5349
5350       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5351         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5352         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5353         if (VT.is256BitVector()) {
5354           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5355           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5356         } else {
5357           assert(VT.is128BitVector() && "Expected an SSE value type!");
5358           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5359         }
5360         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5361       }
5362     }
5363
5364     // Is it a vector logical left shift?
5365     if (NumElems == 2 && Idx == 1 &&
5366         X86::isZeroNode(Op.getOperand(0)) &&
5367         !X86::isZeroNode(Op.getOperand(1))) {
5368       unsigned NumBits = VT.getSizeInBits();
5369       return getVShift(true, VT,
5370                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5371                                    VT, Op.getOperand(1)),
5372                        NumBits/2, DAG, *this, dl);
5373     }
5374
5375     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5376       return SDValue();
5377
5378     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5379     // is a non-constant being inserted into an element other than the low one,
5380     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5381     // movd/movss) to move this into the low element, then shuffle it into
5382     // place.
5383     if (EVTBits == 32) {
5384       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5385
5386       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5387       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5388       SmallVector<int, 8> MaskVec;
5389       for (unsigned i = 0; i != NumElems; ++i)
5390         MaskVec.push_back(i == Idx ? 0 : 1);
5391       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5392     }
5393   }
5394
5395   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5396   if (Values.size() == 1) {
5397     if (EVTBits == 32) {
5398       // Instead of a shuffle like this:
5399       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5400       // Check if it's possible to issue this instead.
5401       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5402       unsigned Idx = CountTrailingZeros_32(NonZeros);
5403       SDValue Item = Op.getOperand(Idx);
5404       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5405         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5406     }
5407     return SDValue();
5408   }
5409
5410   // A vector full of immediates; various special cases are already
5411   // handled, so this is best done with a single constant-pool load.
5412   if (IsAllConstants)
5413     return SDValue();
5414
5415   // For AVX-length vectors, build the individual 128-bit pieces and use
5416   // shuffles to put them in place.
5417   if (VT.is256BitVector()) {
5418     SmallVector<SDValue, 32> V;
5419     for (unsigned i = 0; i != NumElems; ++i)
5420       V.push_back(Op.getOperand(i));
5421
5422     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5423
5424     // Build both the lower and upper subvector.
5425     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5426     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5427                                 NumElems/2);
5428
5429     // Recreate the wider vector with the lower and upper part.
5430     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5431   }
5432
5433   // Let legalizer expand 2-wide build_vectors.
5434   if (EVTBits == 64) {
5435     if (NumNonZero == 1) {
5436       // One half is zero or undef.
5437       unsigned Idx = CountTrailingZeros_32(NonZeros);
5438       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5439                                  Op.getOperand(Idx));
5440       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5441     }
5442     return SDValue();
5443   }
5444
5445   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5446   if (EVTBits == 8 && NumElems == 16) {
5447     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5448                                         Subtarget, *this);
5449     if (V.getNode()) return V;
5450   }
5451
5452   if (EVTBits == 16 && NumElems == 8) {
5453     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5454                                       Subtarget, *this);
5455     if (V.getNode()) return V;
5456   }
5457
5458   // If element VT is == 32 bits, turn it into a number of shuffles.
5459   SmallVector<SDValue, 8> V(NumElems);
5460   if (NumElems == 4 && NumZero > 0) {
5461     for (unsigned i = 0; i < 4; ++i) {
5462       bool isZero = !(NonZeros & (1 << i));
5463       if (isZero)
5464         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5465       else
5466         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5467     }
5468
5469     for (unsigned i = 0; i < 2; ++i) {
5470       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5471         default: break;
5472         case 0:
5473           V[i] = V[i*2];  // Must be a zero vector.
5474           break;
5475         case 1:
5476           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5477           break;
5478         case 2:
5479           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5480           break;
5481         case 3:
5482           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5483           break;
5484       }
5485     }
5486
5487     bool Reverse1 = (NonZeros & 0x3) == 2;
5488     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5489     int MaskVec[] = {
5490       Reverse1 ? 1 : 0,
5491       Reverse1 ? 0 : 1,
5492       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5493       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5494     };
5495     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5496   }
5497
5498   if (Values.size() > 1 && VT.is128BitVector()) {
5499     // Check for a build vector of consecutive loads.
5500     for (unsigned i = 0; i < NumElems; ++i)
5501       V[i] = Op.getOperand(i);
5502
5503     // Check for elements which are consecutive loads.
5504     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5505     if (LD.getNode())
5506       return LD;
5507
5508     // For SSE 4.1, use insertps to put the high elements into the low element.
5509     if (getSubtarget()->hasSSE41()) {
5510       SDValue Result;
5511       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5512         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5513       else
5514         Result = DAG.getUNDEF(VT);
5515
5516       for (unsigned i = 1; i < NumElems; ++i) {
5517         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5518         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5519                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5520       }
5521       return Result;
5522     }
5523
5524     // Otherwise, expand into a number of unpckl*, start by extending each of
5525     // our (non-undef) elements to the full vector width with the element in the
5526     // bottom slot of the vector (which generates no code for SSE).
5527     for (unsigned i = 0; i < NumElems; ++i) {
5528       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5529         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5530       else
5531         V[i] = DAG.getUNDEF(VT);
5532     }
5533
5534     // Next, we iteratively mix elements, e.g. for v4f32:
5535     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5536     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5537     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5538     unsigned EltStride = NumElems >> 1;
5539     while (EltStride != 0) {
5540       for (unsigned i = 0; i < EltStride; ++i) {
5541         // If V[i+EltStride] is undef and this is the first round of mixing,
5542         // then it is safe to just drop this shuffle: V[i] is already in the
5543         // right place, the one element (since it's the first round) being
5544         // inserted as undef can be dropped.  This isn't safe for successive
5545         // rounds because they will permute elements within both vectors.
5546         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5547             EltStride == NumElems/2)
5548           continue;
5549
5550         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5551       }
5552       EltStride >>= 1;
5553     }
5554     return V[0];
5555   }
5556   return SDValue();
5557 }
5558
5559 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5560 // to create 256-bit vectors from two other 128-bit ones.
5561 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5562   DebugLoc dl = Op.getDebugLoc();
5563   EVT ResVT = Op.getValueType();
5564
5565   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5566
5567   SDValue V1 = Op.getOperand(0);
5568   SDValue V2 = Op.getOperand(1);
5569   unsigned NumElems = ResVT.getVectorNumElements();
5570
5571   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5572 }
5573
5574 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5575   assert(Op.getNumOperands() == 2);
5576
5577   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5578   // from two other 128-bit ones.
5579   return LowerAVXCONCAT_VECTORS(Op, DAG);
5580 }
5581
5582 // Try to lower a shuffle node into a simple blend instruction.
5583 static SDValue
5584 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5585                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5586   SDValue V1 = SVOp->getOperand(0);
5587   SDValue V2 = SVOp->getOperand(1);
5588   DebugLoc dl = SVOp->getDebugLoc();
5589   MVT VT = SVOp->getValueType(0).getSimpleVT();
5590   unsigned NumElems = VT.getVectorNumElements();
5591
5592   if (!Subtarget->hasSSE41())
5593     return SDValue();
5594
5595   unsigned ISDNo = 0;
5596   MVT OpTy;
5597
5598   switch (VT.SimpleTy) {
5599   default: return SDValue();
5600   case MVT::v8i16:
5601     ISDNo = X86ISD::BLENDPW;
5602     OpTy = MVT::v8i16;
5603     break;
5604   case MVT::v4i32:
5605   case MVT::v4f32:
5606     ISDNo = X86ISD::BLENDPS;
5607     OpTy = MVT::v4f32;
5608     break;
5609   case MVT::v2i64:
5610   case MVT::v2f64:
5611     ISDNo = X86ISD::BLENDPD;
5612     OpTy = MVT::v2f64;
5613     break;
5614   case MVT::v8i32:
5615   case MVT::v8f32:
5616     if (!Subtarget->hasAVX())
5617       return SDValue();
5618     ISDNo = X86ISD::BLENDPS;
5619     OpTy = MVT::v8f32;
5620     break;
5621   case MVT::v4i64:
5622   case MVT::v4f64:
5623     if (!Subtarget->hasAVX())
5624       return SDValue();
5625     ISDNo = X86ISD::BLENDPD;
5626     OpTy = MVT::v4f64;
5627     break;
5628   }
5629   assert(ISDNo && "Invalid Op Number");
5630
5631   unsigned MaskVals = 0;
5632
5633   for (unsigned i = 0; i != NumElems; ++i) {
5634     int EltIdx = SVOp->getMaskElt(i);
5635     if (EltIdx == (int)i || EltIdx < 0)
5636       MaskVals |= (1<<i);
5637     else if (EltIdx == (int)(i + NumElems))
5638       continue; // Bit is set to zero;
5639     else
5640       return SDValue();
5641   }
5642
5643   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5644   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5645   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5646                              DAG.getConstant(MaskVals, MVT::i32));
5647   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5648 }
5649
5650 // v8i16 shuffles - Prefer shuffles in the following order:
5651 // 1. [all]   pshuflw, pshufhw, optional move
5652 // 2. [ssse3] 1 x pshufb
5653 // 3. [ssse3] 2 x pshufb + 1 x por
5654 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5655 static SDValue
5656 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5657                          SelectionDAG &DAG) {
5658   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5659   SDValue V1 = SVOp->getOperand(0);
5660   SDValue V2 = SVOp->getOperand(1);
5661   DebugLoc dl = SVOp->getDebugLoc();
5662   SmallVector<int, 8> MaskVals;
5663
5664   // Determine if more than 1 of the words in each of the low and high quadwords
5665   // of the result come from the same quadword of one of the two inputs.  Undef
5666   // mask values count as coming from any quadword, for better codegen.
5667   unsigned LoQuad[] = { 0, 0, 0, 0 };
5668   unsigned HiQuad[] = { 0, 0, 0, 0 };
5669   std::bitset<4> InputQuads;
5670   for (unsigned i = 0; i < 8; ++i) {
5671     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5672     int EltIdx = SVOp->getMaskElt(i);
5673     MaskVals.push_back(EltIdx);
5674     if (EltIdx < 0) {
5675       ++Quad[0];
5676       ++Quad[1];
5677       ++Quad[2];
5678       ++Quad[3];
5679       continue;
5680     }
5681     ++Quad[EltIdx / 4];
5682     InputQuads.set(EltIdx / 4);
5683   }
5684
5685   int BestLoQuad = -1;
5686   unsigned MaxQuad = 1;
5687   for (unsigned i = 0; i < 4; ++i) {
5688     if (LoQuad[i] > MaxQuad) {
5689       BestLoQuad = i;
5690       MaxQuad = LoQuad[i];
5691     }
5692   }
5693
5694   int BestHiQuad = -1;
5695   MaxQuad = 1;
5696   for (unsigned i = 0; i < 4; ++i) {
5697     if (HiQuad[i] > MaxQuad) {
5698       BestHiQuad = i;
5699       MaxQuad = HiQuad[i];
5700     }
5701   }
5702
5703   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5704   // of the two input vectors, shuffle them into one input vector so only a
5705   // single pshufb instruction is necessary. If There are more than 2 input
5706   // quads, disable the next transformation since it does not help SSSE3.
5707   bool V1Used = InputQuads[0] || InputQuads[1];
5708   bool V2Used = InputQuads[2] || InputQuads[3];
5709   if (Subtarget->hasSSSE3()) {
5710     if (InputQuads.count() == 2 && V1Used && V2Used) {
5711       BestLoQuad = InputQuads[0] ? 0 : 1;
5712       BestHiQuad = InputQuads[2] ? 2 : 3;
5713     }
5714     if (InputQuads.count() > 2) {
5715       BestLoQuad = -1;
5716       BestHiQuad = -1;
5717     }
5718   }
5719
5720   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5721   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5722   // words from all 4 input quadwords.
5723   SDValue NewV;
5724   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5725     int MaskV[] = {
5726       BestLoQuad < 0 ? 0 : BestLoQuad,
5727       BestHiQuad < 0 ? 1 : BestHiQuad
5728     };
5729     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5730                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5731                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5732     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5733
5734     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5735     // source words for the shuffle, to aid later transformations.
5736     bool AllWordsInNewV = true;
5737     bool InOrder[2] = { true, true };
5738     for (unsigned i = 0; i != 8; ++i) {
5739       int idx = MaskVals[i];
5740       if (idx != (int)i)
5741         InOrder[i/4] = false;
5742       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5743         continue;
5744       AllWordsInNewV = false;
5745       break;
5746     }
5747
5748     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5749     if (AllWordsInNewV) {
5750       for (int i = 0; i != 8; ++i) {
5751         int idx = MaskVals[i];
5752         if (idx < 0)
5753           continue;
5754         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5755         if ((idx != i) && idx < 4)
5756           pshufhw = false;
5757         if ((idx != i) && idx > 3)
5758           pshuflw = false;
5759       }
5760       V1 = NewV;
5761       V2Used = false;
5762       BestLoQuad = 0;
5763       BestHiQuad = 1;
5764     }
5765
5766     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5767     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5768     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5769       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5770       unsigned TargetMask = 0;
5771       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5772                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5773       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5774       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5775                              getShufflePSHUFLWImmediate(SVOp);
5776       V1 = NewV.getOperand(0);
5777       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5778     }
5779   }
5780
5781   // If we have SSSE3, and all words of the result are from 1 input vector,
5782   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5783   // is present, fall back to case 4.
5784   if (Subtarget->hasSSSE3()) {
5785     SmallVector<SDValue,16> pshufbMask;
5786
5787     // If we have elements from both input vectors, set the high bit of the
5788     // shuffle mask element to zero out elements that come from V2 in the V1
5789     // mask, and elements that come from V1 in the V2 mask, so that the two
5790     // results can be OR'd together.
5791     bool TwoInputs = V1Used && V2Used;
5792     for (unsigned i = 0; i != 8; ++i) {
5793       int EltIdx = MaskVals[i] * 2;
5794       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5795       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5796       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5797       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5798     }
5799     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5800     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5801                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5802                                  MVT::v16i8, &pshufbMask[0], 16));
5803     if (!TwoInputs)
5804       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5805
5806     // Calculate the shuffle mask for the second input, shuffle it, and
5807     // OR it with the first shuffled input.
5808     pshufbMask.clear();
5809     for (unsigned i = 0; i != 8; ++i) {
5810       int EltIdx = MaskVals[i] * 2;
5811       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5812       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5813       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5814       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5815     }
5816     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5817     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5818                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5819                                  MVT::v16i8, &pshufbMask[0], 16));
5820     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5821     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5822   }
5823
5824   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5825   // and update MaskVals with new element order.
5826   std::bitset<8> InOrder;
5827   if (BestLoQuad >= 0) {
5828     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5829     for (int i = 0; i != 4; ++i) {
5830       int idx = MaskVals[i];
5831       if (idx < 0) {
5832         InOrder.set(i);
5833       } else if ((idx / 4) == BestLoQuad) {
5834         MaskV[i] = idx & 3;
5835         InOrder.set(i);
5836       }
5837     }
5838     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5839                                 &MaskV[0]);
5840
5841     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5842       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5843       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5844                                   NewV.getOperand(0),
5845                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5846     }
5847   }
5848
5849   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5850   // and update MaskVals with the new element order.
5851   if (BestHiQuad >= 0) {
5852     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5853     for (unsigned i = 4; i != 8; ++i) {
5854       int idx = MaskVals[i];
5855       if (idx < 0) {
5856         InOrder.set(i);
5857       } else if ((idx / 4) == BestHiQuad) {
5858         MaskV[i] = (idx & 3) + 4;
5859         InOrder.set(i);
5860       }
5861     }
5862     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5863                                 &MaskV[0]);
5864
5865     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5866       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5867       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5868                                   NewV.getOperand(0),
5869                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5870     }
5871   }
5872
5873   // In case BestHi & BestLo were both -1, which means each quadword has a word
5874   // from each of the four input quadwords, calculate the InOrder bitvector now
5875   // before falling through to the insert/extract cleanup.
5876   if (BestLoQuad == -1 && BestHiQuad == -1) {
5877     NewV = V1;
5878     for (int i = 0; i != 8; ++i)
5879       if (MaskVals[i] < 0 || MaskVals[i] == i)
5880         InOrder.set(i);
5881   }
5882
5883   // The other elements are put in the right place using pextrw and pinsrw.
5884   for (unsigned i = 0; i != 8; ++i) {
5885     if (InOrder[i])
5886       continue;
5887     int EltIdx = MaskVals[i];
5888     if (EltIdx < 0)
5889       continue;
5890     SDValue ExtOp = (EltIdx < 8) ?
5891       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5892                   DAG.getIntPtrConstant(EltIdx)) :
5893       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5894                   DAG.getIntPtrConstant(EltIdx - 8));
5895     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5896                        DAG.getIntPtrConstant(i));
5897   }
5898   return NewV;
5899 }
5900
5901 // v16i8 shuffles - Prefer shuffles in the following order:
5902 // 1. [ssse3] 1 x pshufb
5903 // 2. [ssse3] 2 x pshufb + 1 x por
5904 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5905 static
5906 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5907                                  SelectionDAG &DAG,
5908                                  const X86TargetLowering &TLI) {
5909   SDValue V1 = SVOp->getOperand(0);
5910   SDValue V2 = SVOp->getOperand(1);
5911   DebugLoc dl = SVOp->getDebugLoc();
5912   ArrayRef<int> MaskVals = SVOp->getMask();
5913
5914   // If we have SSSE3, case 1 is generated when all result bytes come from
5915   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5916   // present, fall back to case 3.
5917
5918   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5919   if (TLI.getSubtarget()->hasSSSE3()) {
5920     SmallVector<SDValue,16> pshufbMask;
5921
5922     // If all result elements are from one input vector, then only translate
5923     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5924     //
5925     // Otherwise, we have elements from both input vectors, and must zero out
5926     // elements that come from V2 in the first mask, and V1 in the second mask
5927     // so that we can OR them together.
5928     for (unsigned i = 0; i != 16; ++i) {
5929       int EltIdx = MaskVals[i];
5930       if (EltIdx < 0 || EltIdx >= 16)
5931         EltIdx = 0x80;
5932       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5933     }
5934     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5935                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5936                                  MVT::v16i8, &pshufbMask[0], 16));
5937
5938     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5939     // the 2nd operand if it's undefined or zero.
5940     if (V2.getOpcode() == ISD::UNDEF ||
5941         ISD::isBuildVectorAllZeros(V2.getNode()))
5942       return V1;
5943
5944     // Calculate the shuffle mask for the second input, shuffle it, and
5945     // OR it with the first shuffled input.
5946     pshufbMask.clear();
5947     for (unsigned i = 0; i != 16; ++i) {
5948       int EltIdx = MaskVals[i];
5949       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5950       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5951     }
5952     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5953                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5954                                  MVT::v16i8, &pshufbMask[0], 16));
5955     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5956   }
5957
5958   // No SSSE3 - Calculate in place words and then fix all out of place words
5959   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5960   // the 16 different words that comprise the two doublequadword input vectors.
5961   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5962   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5963   SDValue NewV = V1;
5964   for (int i = 0; i != 8; ++i) {
5965     int Elt0 = MaskVals[i*2];
5966     int Elt1 = MaskVals[i*2+1];
5967
5968     // This word of the result is all undef, skip it.
5969     if (Elt0 < 0 && Elt1 < 0)
5970       continue;
5971
5972     // This word of the result is already in the correct place, skip it.
5973     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5974       continue;
5975
5976     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5977     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5978     SDValue InsElt;
5979
5980     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5981     // using a single extract together, load it and store it.
5982     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5983       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5984                            DAG.getIntPtrConstant(Elt1 / 2));
5985       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5986                         DAG.getIntPtrConstant(i));
5987       continue;
5988     }
5989
5990     // If Elt1 is defined, extract it from the appropriate source.  If the
5991     // source byte is not also odd, shift the extracted word left 8 bits
5992     // otherwise clear the bottom 8 bits if we need to do an or.
5993     if (Elt1 >= 0) {
5994       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5995                            DAG.getIntPtrConstant(Elt1 / 2));
5996       if ((Elt1 & 1) == 0)
5997         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5998                              DAG.getConstant(8,
5999                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6000       else if (Elt0 >= 0)
6001         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6002                              DAG.getConstant(0xFF00, MVT::i16));
6003     }
6004     // If Elt0 is defined, extract it from the appropriate source.  If the
6005     // source byte is not also even, shift the extracted word right 8 bits. If
6006     // Elt1 was also defined, OR the extracted values together before
6007     // inserting them in the result.
6008     if (Elt0 >= 0) {
6009       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6010                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6011       if ((Elt0 & 1) != 0)
6012         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6013                               DAG.getConstant(8,
6014                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6015       else if (Elt1 >= 0)
6016         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6017                              DAG.getConstant(0x00FF, MVT::i16));
6018       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6019                          : InsElt0;
6020     }
6021     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6022                        DAG.getIntPtrConstant(i));
6023   }
6024   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6025 }
6026
6027 // v32i8 shuffles - Translate to VPSHUFB if possible.
6028 static
6029 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6030                                  const X86Subtarget *Subtarget,
6031                                  SelectionDAG &DAG) {
6032   EVT VT = SVOp->getValueType(0);
6033   SDValue V1 = SVOp->getOperand(0);
6034   SDValue V2 = SVOp->getOperand(1);
6035   DebugLoc dl = SVOp->getDebugLoc();
6036   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6037
6038   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6039   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6040   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6041
6042   // VPSHUFB may be generated if 
6043   // (1) one of input vector is undefined or zeroinitializer.
6044   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6045   // And (2) the mask indexes don't cross the 128-bit lane.
6046   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6047       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6048     return SDValue();
6049
6050   if (V1IsAllZero && !V2IsAllZero) {
6051     CommuteVectorShuffleMask(MaskVals, 32);
6052     V1 = V2;
6053   }
6054   SmallVector<SDValue, 32> pshufbMask;
6055   for (unsigned i = 0; i != 32; i++) {
6056     int EltIdx = MaskVals[i];
6057     if (EltIdx < 0 || EltIdx >= 32)
6058       EltIdx = 0x80;
6059     else {
6060       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6061         // Cross lane is not allowed.
6062         return SDValue();
6063       EltIdx &= 0xf;
6064     }
6065     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6066   }
6067   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6068                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6069                                   MVT::v32i8, &pshufbMask[0], 32));
6070 }
6071
6072 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6073 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6074 /// done when every pair / quad of shuffle mask elements point to elements in
6075 /// the right sequence. e.g.
6076 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6077 static
6078 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6079                                  SelectionDAG &DAG, DebugLoc dl) {
6080   MVT VT = SVOp->getValueType(0).getSimpleVT();
6081   unsigned NumElems = VT.getVectorNumElements();
6082   MVT NewVT;
6083   unsigned Scale;
6084   switch (VT.SimpleTy) {
6085   default: llvm_unreachable("Unexpected!");
6086   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6087   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6088   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6089   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6090   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6091   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6092   }
6093
6094   SmallVector<int, 8> MaskVec;
6095   for (unsigned i = 0; i != NumElems; i += Scale) {
6096     int StartIdx = -1;
6097     for (unsigned j = 0; j != Scale; ++j) {
6098       int EltIdx = SVOp->getMaskElt(i+j);
6099       if (EltIdx < 0)
6100         continue;
6101       if (StartIdx < 0)
6102         StartIdx = (EltIdx / Scale);
6103       if (EltIdx != (int)(StartIdx*Scale + j))
6104         return SDValue();
6105     }
6106     MaskVec.push_back(StartIdx);
6107   }
6108
6109   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6110   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6111   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6112 }
6113
6114 /// getVZextMovL - Return a zero-extending vector move low node.
6115 ///
6116 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6117                             SDValue SrcOp, SelectionDAG &DAG,
6118                             const X86Subtarget *Subtarget, DebugLoc dl) {
6119   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6120     LoadSDNode *LD = NULL;
6121     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6122       LD = dyn_cast<LoadSDNode>(SrcOp);
6123     if (!LD) {
6124       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6125       // instead.
6126       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6127       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6128           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6129           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6130           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6131         // PR2108
6132         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6133         return DAG.getNode(ISD::BITCAST, dl, VT,
6134                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6135                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6136                                                    OpVT,
6137                                                    SrcOp.getOperand(0)
6138                                                           .getOperand(0))));
6139       }
6140     }
6141   }
6142
6143   return DAG.getNode(ISD::BITCAST, dl, VT,
6144                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6145                                  DAG.getNode(ISD::BITCAST, dl,
6146                                              OpVT, SrcOp)));
6147 }
6148
6149 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6150 /// which could not be matched by any known target speficic shuffle
6151 static SDValue
6152 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6153
6154   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6155   if (NewOp.getNode())
6156     return NewOp;
6157
6158   EVT VT = SVOp->getValueType(0);
6159
6160   unsigned NumElems = VT.getVectorNumElements();
6161   unsigned NumLaneElems = NumElems / 2;
6162
6163   DebugLoc dl = SVOp->getDebugLoc();
6164   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6165   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6166   SDValue Output[2];
6167
6168   SmallVector<int, 16> Mask;
6169   for (unsigned l = 0; l < 2; ++l) {
6170     // Build a shuffle mask for the output, discovering on the fly which
6171     // input vectors to use as shuffle operands (recorded in InputUsed).
6172     // If building a suitable shuffle vector proves too hard, then bail
6173     // out with UseBuildVector set.
6174     bool UseBuildVector = false;
6175     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6176     unsigned LaneStart = l * NumLaneElems;
6177     for (unsigned i = 0; i != NumLaneElems; ++i) {
6178       // The mask element.  This indexes into the input.
6179       int Idx = SVOp->getMaskElt(i+LaneStart);
6180       if (Idx < 0) {
6181         // the mask element does not index into any input vector.
6182         Mask.push_back(-1);
6183         continue;
6184       }
6185
6186       // The input vector this mask element indexes into.
6187       int Input = Idx / NumLaneElems;
6188
6189       // Turn the index into an offset from the start of the input vector.
6190       Idx -= Input * NumLaneElems;
6191
6192       // Find or create a shuffle vector operand to hold this input.
6193       unsigned OpNo;
6194       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6195         if (InputUsed[OpNo] == Input)
6196           // This input vector is already an operand.
6197           break;
6198         if (InputUsed[OpNo] < 0) {
6199           // Create a new operand for this input vector.
6200           InputUsed[OpNo] = Input;
6201           break;
6202         }
6203       }
6204
6205       if (OpNo >= array_lengthof(InputUsed)) {
6206         // More than two input vectors used!  Give up on trying to create a
6207         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6208         UseBuildVector = true;
6209         break;
6210       }
6211
6212       // Add the mask index for the new shuffle vector.
6213       Mask.push_back(Idx + OpNo * NumLaneElems);
6214     }
6215
6216     if (UseBuildVector) {
6217       SmallVector<SDValue, 16> SVOps;
6218       for (unsigned i = 0; i != NumLaneElems; ++i) {
6219         // The mask element.  This indexes into the input.
6220         int Idx = SVOp->getMaskElt(i+LaneStart);
6221         if (Idx < 0) {
6222           SVOps.push_back(DAG.getUNDEF(EltVT));
6223           continue;
6224         }
6225
6226         // The input vector this mask element indexes into.
6227         int Input = Idx / NumElems;
6228
6229         // Turn the index into an offset from the start of the input vector.
6230         Idx -= Input * NumElems;
6231
6232         // Extract the vector element by hand.
6233         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6234                                     SVOp->getOperand(Input),
6235                                     DAG.getIntPtrConstant(Idx)));
6236       }
6237
6238       // Construct the output using a BUILD_VECTOR.
6239       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6240                               SVOps.size());
6241     } else if (InputUsed[0] < 0) {
6242       // No input vectors were used! The result is undefined.
6243       Output[l] = DAG.getUNDEF(NVT);
6244     } else {
6245       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6246                                         (InputUsed[0] % 2) * NumLaneElems,
6247                                         DAG, dl);
6248       // If only one input was used, use an undefined vector for the other.
6249       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6250         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6251                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6252       // At least one input vector was used. Create a new shuffle vector.
6253       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6254     }
6255
6256     Mask.clear();
6257   }
6258
6259   // Concatenate the result back
6260   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6261 }
6262
6263 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6264 /// 4 elements, and match them with several different shuffle types.
6265 static SDValue
6266 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6267   SDValue V1 = SVOp->getOperand(0);
6268   SDValue V2 = SVOp->getOperand(1);
6269   DebugLoc dl = SVOp->getDebugLoc();
6270   EVT VT = SVOp->getValueType(0);
6271
6272   assert(VT.is128BitVector() && "Unsupported vector size");
6273
6274   std::pair<int, int> Locs[4];
6275   int Mask1[] = { -1, -1, -1, -1 };
6276   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6277
6278   unsigned NumHi = 0;
6279   unsigned NumLo = 0;
6280   for (unsigned i = 0; i != 4; ++i) {
6281     int Idx = PermMask[i];
6282     if (Idx < 0) {
6283       Locs[i] = std::make_pair(-1, -1);
6284     } else {
6285       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6286       if (Idx < 4) {
6287         Locs[i] = std::make_pair(0, NumLo);
6288         Mask1[NumLo] = Idx;
6289         NumLo++;
6290       } else {
6291         Locs[i] = std::make_pair(1, NumHi);
6292         if (2+NumHi < 4)
6293           Mask1[2+NumHi] = Idx;
6294         NumHi++;
6295       }
6296     }
6297   }
6298
6299   if (NumLo <= 2 && NumHi <= 2) {
6300     // If no more than two elements come from either vector. This can be
6301     // implemented with two shuffles. First shuffle gather the elements.
6302     // The second shuffle, which takes the first shuffle as both of its
6303     // vector operands, put the elements into the right order.
6304     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6305
6306     int Mask2[] = { -1, -1, -1, -1 };
6307
6308     for (unsigned i = 0; i != 4; ++i)
6309       if (Locs[i].first != -1) {
6310         unsigned Idx = (i < 2) ? 0 : 4;
6311         Idx += Locs[i].first * 2 + Locs[i].second;
6312         Mask2[i] = Idx;
6313       }
6314
6315     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6316   }
6317
6318   if (NumLo == 3 || NumHi == 3) {
6319     // Otherwise, we must have three elements from one vector, call it X, and
6320     // one element from the other, call it Y.  First, use a shufps to build an
6321     // intermediate vector with the one element from Y and the element from X
6322     // that will be in the same half in the final destination (the indexes don't
6323     // matter). Then, use a shufps to build the final vector, taking the half
6324     // containing the element from Y from the intermediate, and the other half
6325     // from X.
6326     if (NumHi == 3) {
6327       // Normalize it so the 3 elements come from V1.
6328       CommuteVectorShuffleMask(PermMask, 4);
6329       std::swap(V1, V2);
6330     }
6331
6332     // Find the element from V2.
6333     unsigned HiIndex;
6334     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6335       int Val = PermMask[HiIndex];
6336       if (Val < 0)
6337         continue;
6338       if (Val >= 4)
6339         break;
6340     }
6341
6342     Mask1[0] = PermMask[HiIndex];
6343     Mask1[1] = -1;
6344     Mask1[2] = PermMask[HiIndex^1];
6345     Mask1[3] = -1;
6346     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6347
6348     if (HiIndex >= 2) {
6349       Mask1[0] = PermMask[0];
6350       Mask1[1] = PermMask[1];
6351       Mask1[2] = HiIndex & 1 ? 6 : 4;
6352       Mask1[3] = HiIndex & 1 ? 4 : 6;
6353       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6354     }
6355
6356     Mask1[0] = HiIndex & 1 ? 2 : 0;
6357     Mask1[1] = HiIndex & 1 ? 0 : 2;
6358     Mask1[2] = PermMask[2];
6359     Mask1[3] = PermMask[3];
6360     if (Mask1[2] >= 0)
6361       Mask1[2] += 4;
6362     if (Mask1[3] >= 0)
6363       Mask1[3] += 4;
6364     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6365   }
6366
6367   // Break it into (shuffle shuffle_hi, shuffle_lo).
6368   int LoMask[] = { -1, -1, -1, -1 };
6369   int HiMask[] = { -1, -1, -1, -1 };
6370
6371   int *MaskPtr = LoMask;
6372   unsigned MaskIdx = 0;
6373   unsigned LoIdx = 0;
6374   unsigned HiIdx = 2;
6375   for (unsigned i = 0; i != 4; ++i) {
6376     if (i == 2) {
6377       MaskPtr = HiMask;
6378       MaskIdx = 1;
6379       LoIdx = 0;
6380       HiIdx = 2;
6381     }
6382     int Idx = PermMask[i];
6383     if (Idx < 0) {
6384       Locs[i] = std::make_pair(-1, -1);
6385     } else if (Idx < 4) {
6386       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6387       MaskPtr[LoIdx] = Idx;
6388       LoIdx++;
6389     } else {
6390       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6391       MaskPtr[HiIdx] = Idx;
6392       HiIdx++;
6393     }
6394   }
6395
6396   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6397   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6398   int MaskOps[] = { -1, -1, -1, -1 };
6399   for (unsigned i = 0; i != 4; ++i)
6400     if (Locs[i].first != -1)
6401       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6402   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6403 }
6404
6405 static bool MayFoldVectorLoad(SDValue V) {
6406   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6407     V = V.getOperand(0);
6408   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6409     V = V.getOperand(0);
6410   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6411       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6412     // BUILD_VECTOR (load), undef
6413     V = V.getOperand(0);
6414   if (MayFoldLoad(V))
6415     return true;
6416   return false;
6417 }
6418
6419 // FIXME: the version above should always be used. Since there's
6420 // a bug where several vector shuffles can't be folded because the
6421 // DAG is not updated during lowering and a node claims to have two
6422 // uses while it only has one, use this version, and let isel match
6423 // another instruction if the load really happens to have more than
6424 // one use. Remove this version after this bug get fixed.
6425 // rdar://8434668, PR8156
6426 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6427   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6428     V = V.getOperand(0);
6429   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6430     V = V.getOperand(0);
6431   if (ISD::isNormalLoad(V.getNode()))
6432     return true;
6433   return false;
6434 }
6435
6436 static
6437 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6438   EVT VT = Op.getValueType();
6439
6440   // Canonizalize to v2f64.
6441   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6442   return DAG.getNode(ISD::BITCAST, dl, VT,
6443                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6444                                           V1, DAG));
6445 }
6446
6447 static
6448 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6449                         bool HasSSE2) {
6450   SDValue V1 = Op.getOperand(0);
6451   SDValue V2 = Op.getOperand(1);
6452   EVT VT = Op.getValueType();
6453
6454   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6455
6456   if (HasSSE2 && VT == MVT::v2f64)
6457     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6458
6459   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6460   return DAG.getNode(ISD::BITCAST, dl, VT,
6461                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6462                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6463                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6464 }
6465
6466 static
6467 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6468   SDValue V1 = Op.getOperand(0);
6469   SDValue V2 = Op.getOperand(1);
6470   EVT VT = Op.getValueType();
6471
6472   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6473          "unsupported shuffle type");
6474
6475   if (V2.getOpcode() == ISD::UNDEF)
6476     V2 = V1;
6477
6478   // v4i32 or v4f32
6479   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6480 }
6481
6482 static
6483 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6484   SDValue V1 = Op.getOperand(0);
6485   SDValue V2 = Op.getOperand(1);
6486   EVT VT = Op.getValueType();
6487   unsigned NumElems = VT.getVectorNumElements();
6488
6489   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6490   // operand of these instructions is only memory, so check if there's a
6491   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6492   // same masks.
6493   bool CanFoldLoad = false;
6494
6495   // Trivial case, when V2 comes from a load.
6496   if (MayFoldVectorLoad(V2))
6497     CanFoldLoad = true;
6498
6499   // When V1 is a load, it can be folded later into a store in isel, example:
6500   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6501   //    turns into:
6502   //  (MOVLPSmr addr:$src1, VR128:$src2)
6503   // So, recognize this potential and also use MOVLPS or MOVLPD
6504   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6505     CanFoldLoad = true;
6506
6507   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6508   if (CanFoldLoad) {
6509     if (HasSSE2 && NumElems == 2)
6510       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6511
6512     if (NumElems == 4)
6513       // If we don't care about the second element, proceed to use movss.
6514       if (SVOp->getMaskElt(1) != -1)
6515         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6516   }
6517
6518   // movl and movlp will both match v2i64, but v2i64 is never matched by
6519   // movl earlier because we make it strict to avoid messing with the movlp load
6520   // folding logic (see the code above getMOVLP call). Match it here then,
6521   // this is horrible, but will stay like this until we move all shuffle
6522   // matching to x86 specific nodes. Note that for the 1st condition all
6523   // types are matched with movsd.
6524   if (HasSSE2) {
6525     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6526     // as to remove this logic from here, as much as possible
6527     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6528       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6529     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6530   }
6531
6532   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6533
6534   // Invert the operand order and use SHUFPS to match it.
6535   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6536                               getShuffleSHUFImmediate(SVOp), DAG);
6537 }
6538
6539 SDValue
6540 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6541   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6542   EVT VT = Op.getValueType();
6543   DebugLoc dl = Op.getDebugLoc();
6544   SDValue V1 = Op.getOperand(0);
6545   SDValue V2 = Op.getOperand(1);
6546
6547   if (isZeroShuffle(SVOp))
6548     return getZeroVector(VT, Subtarget, DAG, dl);
6549
6550   // Handle splat operations
6551   if (SVOp->isSplat()) {
6552     unsigned NumElem = VT.getVectorNumElements();
6553     int Size = VT.getSizeInBits();
6554
6555     // Use vbroadcast whenever the splat comes from a foldable load
6556     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6557     if (Broadcast.getNode())
6558       return Broadcast;
6559
6560     // Handle splats by matching through known shuffle masks
6561     if ((Size == 128 && NumElem <= 4) ||
6562         (Size == 256 && NumElem < 8))
6563       return SDValue();
6564
6565     // All remaning splats are promoted to target supported vector shuffles.
6566     return PromoteSplat(SVOp, DAG);
6567   }
6568
6569   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6570   // do it!
6571   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6572       VT == MVT::v16i16 || VT == MVT::v32i8) {
6573     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6574     if (NewOp.getNode())
6575       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6576   } else if ((VT == MVT::v4i32 ||
6577              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6578     // FIXME: Figure out a cleaner way to do this.
6579     // Try to make use of movq to zero out the top part.
6580     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6581       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6582       if (NewOp.getNode()) {
6583         EVT NewVT = NewOp.getValueType();
6584         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6585                                NewVT, true, false))
6586           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6587                               DAG, Subtarget, dl);
6588       }
6589     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6590       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6591       if (NewOp.getNode()) {
6592         EVT NewVT = NewOp.getValueType();
6593         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6594           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6595                               DAG, Subtarget, dl);
6596       }
6597     }
6598   }
6599   return SDValue();
6600 }
6601
6602 SDValue
6603 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6604   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6605   SDValue V1 = Op.getOperand(0);
6606   SDValue V2 = Op.getOperand(1);
6607   EVT VT = Op.getValueType();
6608   DebugLoc dl = Op.getDebugLoc();
6609   unsigned NumElems = VT.getVectorNumElements();
6610   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6611   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6612   bool V1IsSplat = false;
6613   bool V2IsSplat = false;
6614   bool HasSSE2 = Subtarget->hasSSE2();
6615   bool HasAVX    = Subtarget->hasAVX();
6616   bool HasAVX2   = Subtarget->hasAVX2();
6617   MachineFunction &MF = DAG.getMachineFunction();
6618   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6619
6620   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6621
6622   if (V1IsUndef && V2IsUndef)
6623     return DAG.getUNDEF(VT);
6624
6625   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6626
6627   // Vector shuffle lowering takes 3 steps:
6628   //
6629   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6630   //    narrowing and commutation of operands should be handled.
6631   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6632   //    shuffle nodes.
6633   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6634   //    so the shuffle can be broken into other shuffles and the legalizer can
6635   //    try the lowering again.
6636   //
6637   // The general idea is that no vector_shuffle operation should be left to
6638   // be matched during isel, all of them must be converted to a target specific
6639   // node here.
6640
6641   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6642   // narrowing and commutation of operands should be handled. The actual code
6643   // doesn't include all of those, work in progress...
6644   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6645   if (NewOp.getNode())
6646     return NewOp;
6647
6648   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6649
6650   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6651   // unpckh_undef). Only use pshufd if speed is more important than size.
6652   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6653     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6654   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6655     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6656
6657   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6658       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6659     return getMOVDDup(Op, dl, V1, DAG);
6660
6661   if (isMOVHLPS_v_undef_Mask(M, VT))
6662     return getMOVHighToLow(Op, dl, DAG);
6663
6664   // Use to match splats
6665   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6666       (VT == MVT::v2f64 || VT == MVT::v2i64))
6667     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6668
6669   if (isPSHUFDMask(M, VT)) {
6670     // The actual implementation will match the mask in the if above and then
6671     // during isel it can match several different instructions, not only pshufd
6672     // as its name says, sad but true, emulate the behavior for now...
6673     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6674       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6675
6676     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6677
6678     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6679       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6680
6681     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6682       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6683
6684     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6685                                 TargetMask, DAG);
6686   }
6687
6688   // Check if this can be converted into a logical shift.
6689   bool isLeft = false;
6690   unsigned ShAmt = 0;
6691   SDValue ShVal;
6692   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6693   if (isShift && ShVal.hasOneUse()) {
6694     // If the shifted value has multiple uses, it may be cheaper to use
6695     // v_set0 + movlhps or movhlps, etc.
6696     EVT EltVT = VT.getVectorElementType();
6697     ShAmt *= EltVT.getSizeInBits();
6698     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6699   }
6700
6701   if (isMOVLMask(M, VT)) {
6702     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6703       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6704     if (!isMOVLPMask(M, VT)) {
6705       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6706         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6707
6708       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6709         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6710     }
6711   }
6712
6713   // FIXME: fold these into legal mask.
6714   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6715     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6716
6717   if (isMOVHLPSMask(M, VT))
6718     return getMOVHighToLow(Op, dl, DAG);
6719
6720   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6721     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6722
6723   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6724     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6725
6726   if (isMOVLPMask(M, VT))
6727     return getMOVLP(Op, dl, DAG, HasSSE2);
6728
6729   if (ShouldXformToMOVHLPS(M, VT) ||
6730       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6731     return CommuteVectorShuffle(SVOp, DAG);
6732
6733   if (isShift) {
6734     // No better options. Use a vshldq / vsrldq.
6735     EVT EltVT = VT.getVectorElementType();
6736     ShAmt *= EltVT.getSizeInBits();
6737     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6738   }
6739
6740   bool Commuted = false;
6741   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6742   // 1,1,1,1 -> v8i16 though.
6743   V1IsSplat = isSplatVector(V1.getNode());
6744   V2IsSplat = isSplatVector(V2.getNode());
6745
6746   // Canonicalize the splat or undef, if present, to be on the RHS.
6747   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6748     CommuteVectorShuffleMask(M, NumElems);
6749     std::swap(V1, V2);
6750     std::swap(V1IsSplat, V2IsSplat);
6751     Commuted = true;
6752   }
6753
6754   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6755     // Shuffling low element of v1 into undef, just return v1.
6756     if (V2IsUndef)
6757       return V1;
6758     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6759     // the instruction selector will not match, so get a canonical MOVL with
6760     // swapped operands to undo the commute.
6761     return getMOVL(DAG, dl, VT, V2, V1);
6762   }
6763
6764   if (isUNPCKLMask(M, VT, HasAVX2))
6765     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6766
6767   if (isUNPCKHMask(M, VT, HasAVX2))
6768     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6769
6770   if (V2IsSplat) {
6771     // Normalize mask so all entries that point to V2 points to its first
6772     // element then try to match unpck{h|l} again. If match, return a
6773     // new vector_shuffle with the corrected mask.p
6774     SmallVector<int, 8> NewMask(M.begin(), M.end());
6775     NormalizeMask(NewMask, NumElems);
6776     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6777       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6778     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6779       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6780   }
6781
6782   if (Commuted) {
6783     // Commute is back and try unpck* again.
6784     // FIXME: this seems wrong.
6785     CommuteVectorShuffleMask(M, NumElems);
6786     std::swap(V1, V2);
6787     std::swap(V1IsSplat, V2IsSplat);
6788     Commuted = false;
6789
6790     if (isUNPCKLMask(M, VT, HasAVX2))
6791       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6792
6793     if (isUNPCKHMask(M, VT, HasAVX2))
6794       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6795   }
6796
6797   // Normalize the node to match x86 shuffle ops if needed
6798   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6799     return CommuteVectorShuffle(SVOp, DAG);
6800
6801   // The checks below are all present in isShuffleMaskLegal, but they are
6802   // inlined here right now to enable us to directly emit target specific
6803   // nodes, and remove one by one until they don't return Op anymore.
6804
6805   if (isPALIGNRMask(M, VT, Subtarget))
6806     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6807                                 getShufflePALIGNRImmediate(SVOp),
6808                                 DAG);
6809
6810   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6811       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6812     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6813       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6814   }
6815
6816   if (isPSHUFHWMask(M, VT, HasAVX2))
6817     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6818                                 getShufflePSHUFHWImmediate(SVOp),
6819                                 DAG);
6820
6821   if (isPSHUFLWMask(M, VT, HasAVX2))
6822     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6823                                 getShufflePSHUFLWImmediate(SVOp),
6824                                 DAG);
6825
6826   if (isSHUFPMask(M, VT, HasAVX))
6827     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6828                                 getShuffleSHUFImmediate(SVOp), DAG);
6829
6830   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6831     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6832   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6833     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6834
6835   //===--------------------------------------------------------------------===//
6836   // Generate target specific nodes for 128 or 256-bit shuffles only
6837   // supported in the AVX instruction set.
6838   //
6839
6840   // Handle VMOVDDUPY permutations
6841   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6842     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6843
6844   // Handle VPERMILPS/D* permutations
6845   if (isVPERMILPMask(M, VT, HasAVX)) {
6846     if (HasAVX2 && VT == MVT::v8i32)
6847       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6848                                   getShuffleSHUFImmediate(SVOp), DAG);
6849     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6850                                 getShuffleSHUFImmediate(SVOp), DAG);
6851   }
6852
6853   // Handle VPERM2F128/VPERM2I128 permutations
6854   if (isVPERM2X128Mask(M, VT, HasAVX))
6855     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6856                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6857
6858   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6859   if (BlendOp.getNode())
6860     return BlendOp;
6861
6862   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6863     SmallVector<SDValue, 8> permclMask;
6864     for (unsigned i = 0; i != 8; ++i) {
6865       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6866     }
6867     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6868                                &permclMask[0], 8);
6869     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6870     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6871                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6872   }
6873
6874   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6875     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6876                                 getShuffleCLImmediate(SVOp), DAG);
6877
6878
6879   //===--------------------------------------------------------------------===//
6880   // Since no target specific shuffle was selected for this generic one,
6881   // lower it into other known shuffles. FIXME: this isn't true yet, but
6882   // this is the plan.
6883   //
6884
6885   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6886   if (VT == MVT::v8i16) {
6887     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6888     if (NewOp.getNode())
6889       return NewOp;
6890   }
6891
6892   if (VT == MVT::v16i8) {
6893     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6894     if (NewOp.getNode())
6895       return NewOp;
6896   }
6897
6898   if (VT == MVT::v32i8) {
6899     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6900     if (NewOp.getNode())
6901       return NewOp;
6902   }
6903
6904   // Handle all 128-bit wide vectors with 4 elements, and match them with
6905   // several different shuffle types.
6906   if (NumElems == 4 && VT.is128BitVector())
6907     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6908
6909   // Handle general 256-bit shuffles
6910   if (VT.is256BitVector())
6911     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6912
6913   return SDValue();
6914 }
6915
6916 SDValue
6917 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6918                                                 SelectionDAG &DAG) const {
6919   EVT VT = Op.getValueType();
6920   DebugLoc dl = Op.getDebugLoc();
6921
6922   if (!Op.getOperand(0).getValueType().is128BitVector())
6923     return SDValue();
6924
6925   if (VT.getSizeInBits() == 8) {
6926     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6927                                     Op.getOperand(0), Op.getOperand(1));
6928     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6929                                     DAG.getValueType(VT));
6930     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6931   }
6932
6933   if (VT.getSizeInBits() == 16) {
6934     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6935     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6936     if (Idx == 0)
6937       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6938                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6939                                      DAG.getNode(ISD::BITCAST, dl,
6940                                                  MVT::v4i32,
6941                                                  Op.getOperand(0)),
6942                                      Op.getOperand(1)));
6943     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6944                                     Op.getOperand(0), Op.getOperand(1));
6945     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6946                                     DAG.getValueType(VT));
6947     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6948   }
6949
6950   if (VT == MVT::f32) {
6951     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6952     // the result back to FR32 register. It's only worth matching if the
6953     // result has a single use which is a store or a bitcast to i32.  And in
6954     // the case of a store, it's not worth it if the index is a constant 0,
6955     // because a MOVSSmr can be used instead, which is smaller and faster.
6956     if (!Op.hasOneUse())
6957       return SDValue();
6958     SDNode *User = *Op.getNode()->use_begin();
6959     if ((User->getOpcode() != ISD::STORE ||
6960          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6961           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6962         (User->getOpcode() != ISD::BITCAST ||
6963          User->getValueType(0) != MVT::i32))
6964       return SDValue();
6965     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6966                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6967                                               Op.getOperand(0)),
6968                                               Op.getOperand(1));
6969     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6970   }
6971
6972   if (VT == MVT::i32 || VT == MVT::i64) {
6973     // ExtractPS/pextrq works with constant index.
6974     if (isa<ConstantSDNode>(Op.getOperand(1)))
6975       return Op;
6976   }
6977   return SDValue();
6978 }
6979
6980
6981 SDValue
6982 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6983                                            SelectionDAG &DAG) const {
6984   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6985     return SDValue();
6986
6987   SDValue Vec = Op.getOperand(0);
6988   EVT VecVT = Vec.getValueType();
6989
6990   // If this is a 256-bit vector result, first extract the 128-bit vector and
6991   // then extract the element from the 128-bit vector.
6992   if (VecVT.is256BitVector()) {
6993     DebugLoc dl = Op.getNode()->getDebugLoc();
6994     unsigned NumElems = VecVT.getVectorNumElements();
6995     SDValue Idx = Op.getOperand(1);
6996     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6997
6998     // Get the 128-bit vector.
6999     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7000
7001     if (IdxVal >= NumElems/2)
7002       IdxVal -= NumElems/2;
7003     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7004                        DAG.getConstant(IdxVal, MVT::i32));
7005   }
7006
7007   assert(VecVT.is128BitVector() && "Unexpected vector length");
7008
7009   if (Subtarget->hasSSE41()) {
7010     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7011     if (Res.getNode())
7012       return Res;
7013   }
7014
7015   EVT VT = Op.getValueType();
7016   DebugLoc dl = Op.getDebugLoc();
7017   // TODO: handle v16i8.
7018   if (VT.getSizeInBits() == 16) {
7019     SDValue Vec = Op.getOperand(0);
7020     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7021     if (Idx == 0)
7022       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7023                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7024                                      DAG.getNode(ISD::BITCAST, dl,
7025                                                  MVT::v4i32, Vec),
7026                                      Op.getOperand(1)));
7027     // Transform it so it match pextrw which produces a 32-bit result.
7028     EVT EltVT = MVT::i32;
7029     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7030                                     Op.getOperand(0), Op.getOperand(1));
7031     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7032                                     DAG.getValueType(VT));
7033     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7034   }
7035
7036   if (VT.getSizeInBits() == 32) {
7037     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7038     if (Idx == 0)
7039       return Op;
7040
7041     // SHUFPS the element to the lowest double word, then movss.
7042     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7043     EVT VVT = Op.getOperand(0).getValueType();
7044     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7045                                        DAG.getUNDEF(VVT), Mask);
7046     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7047                        DAG.getIntPtrConstant(0));
7048   }
7049
7050   if (VT.getSizeInBits() == 64) {
7051     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7052     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7053     //        to match extract_elt for f64.
7054     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7055     if (Idx == 0)
7056       return Op;
7057
7058     // UNPCKHPD the element to the lowest double word, then movsd.
7059     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7060     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7061     int Mask[2] = { 1, -1 };
7062     EVT VVT = Op.getOperand(0).getValueType();
7063     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7064                                        DAG.getUNDEF(VVT), Mask);
7065     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7066                        DAG.getIntPtrConstant(0));
7067   }
7068
7069   return SDValue();
7070 }
7071
7072 SDValue
7073 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7074                                                SelectionDAG &DAG) const {
7075   EVT VT = Op.getValueType();
7076   EVT EltVT = VT.getVectorElementType();
7077   DebugLoc dl = Op.getDebugLoc();
7078
7079   SDValue N0 = Op.getOperand(0);
7080   SDValue N1 = Op.getOperand(1);
7081   SDValue N2 = Op.getOperand(2);
7082
7083   if (!VT.is128BitVector())
7084     return SDValue();
7085
7086   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7087       isa<ConstantSDNode>(N2)) {
7088     unsigned Opc;
7089     if (VT == MVT::v8i16)
7090       Opc = X86ISD::PINSRW;
7091     else if (VT == MVT::v16i8)
7092       Opc = X86ISD::PINSRB;
7093     else
7094       Opc = X86ISD::PINSRB;
7095
7096     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7097     // argument.
7098     if (N1.getValueType() != MVT::i32)
7099       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7100     if (N2.getValueType() != MVT::i32)
7101       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7102     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7103   }
7104
7105   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7106     // Bits [7:6] of the constant are the source select.  This will always be
7107     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7108     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7109     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7110     // Bits [5:4] of the constant are the destination select.  This is the
7111     //  value of the incoming immediate.
7112     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7113     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7114     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7115     // Create this as a scalar to vector..
7116     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7117     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7118   }
7119
7120   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7121     // PINSR* works with constant index.
7122     return Op;
7123   }
7124   return SDValue();
7125 }
7126
7127 SDValue
7128 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7129   EVT VT = Op.getValueType();
7130   EVT EltVT = VT.getVectorElementType();
7131
7132   DebugLoc dl = Op.getDebugLoc();
7133   SDValue N0 = Op.getOperand(0);
7134   SDValue N1 = Op.getOperand(1);
7135   SDValue N2 = Op.getOperand(2);
7136
7137   // If this is a 256-bit vector result, first extract the 128-bit vector,
7138   // insert the element into the extracted half and then place it back.
7139   if (VT.is256BitVector()) {
7140     if (!isa<ConstantSDNode>(N2))
7141       return SDValue();
7142
7143     // Get the desired 128-bit vector half.
7144     unsigned NumElems = VT.getVectorNumElements();
7145     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7146     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7147
7148     // Insert the element into the desired half.
7149     bool Upper = IdxVal >= NumElems/2;
7150     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7151                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7152
7153     // Insert the changed part back to the 256-bit vector
7154     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7155   }
7156
7157   if (Subtarget->hasSSE41())
7158     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7159
7160   if (EltVT == MVT::i8)
7161     return SDValue();
7162
7163   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7164     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7165     // as its second argument.
7166     if (N1.getValueType() != MVT::i32)
7167       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7168     if (N2.getValueType() != MVT::i32)
7169       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7170     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7171   }
7172   return SDValue();
7173 }
7174
7175 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7176   LLVMContext *Context = DAG.getContext();
7177   DebugLoc dl = Op.getDebugLoc();
7178   EVT OpVT = Op.getValueType();
7179
7180   // If this is a 256-bit vector result, first insert into a 128-bit
7181   // vector and then insert into the 256-bit vector.
7182   if (!OpVT.is128BitVector()) {
7183     // Insert into a 128-bit vector.
7184     EVT VT128 = EVT::getVectorVT(*Context,
7185                                  OpVT.getVectorElementType(),
7186                                  OpVT.getVectorNumElements() / 2);
7187
7188     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7189
7190     // Insert the 128-bit vector.
7191     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7192   }
7193
7194   if (OpVT == MVT::v1i64 &&
7195       Op.getOperand(0).getValueType() == MVT::i64)
7196     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7197
7198   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7199   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7200   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7201                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7202 }
7203
7204 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7205 // a simple subregister reference or explicit instructions to grab
7206 // upper bits of a vector.
7207 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7208                                       SelectionDAG &DAG) {
7209   if (Subtarget->hasAVX()) {
7210     DebugLoc dl = Op.getNode()->getDebugLoc();
7211     SDValue Vec = Op.getNode()->getOperand(0);
7212     SDValue Idx = Op.getNode()->getOperand(1);
7213
7214     if (Op.getNode()->getValueType(0).is128BitVector() &&
7215         Vec.getNode()->getValueType(0).is256BitVector() &&
7216         isa<ConstantSDNode>(Idx)) {
7217       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7218       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7219     }
7220   }
7221   return SDValue();
7222 }
7223
7224 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7225 // simple superregister reference or explicit instructions to insert
7226 // the upper bits of a vector.
7227 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7228                                      SelectionDAG &DAG) {
7229   if (Subtarget->hasAVX()) {
7230     DebugLoc dl = Op.getNode()->getDebugLoc();
7231     SDValue Vec = Op.getNode()->getOperand(0);
7232     SDValue SubVec = Op.getNode()->getOperand(1);
7233     SDValue Idx = Op.getNode()->getOperand(2);
7234
7235     if (Op.getNode()->getValueType(0).is256BitVector() &&
7236         SubVec.getNode()->getValueType(0).is128BitVector() &&
7237         isa<ConstantSDNode>(Idx)) {
7238       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7239       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7240     }
7241   }
7242   return SDValue();
7243 }
7244
7245 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7246 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7247 // one of the above mentioned nodes. It has to be wrapped because otherwise
7248 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7249 // be used to form addressing mode. These wrapped nodes will be selected
7250 // into MOV32ri.
7251 SDValue
7252 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7253   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7254
7255   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7256   // global base reg.
7257   unsigned char OpFlag = 0;
7258   unsigned WrapperKind = X86ISD::Wrapper;
7259   CodeModel::Model M = getTargetMachine().getCodeModel();
7260
7261   if (Subtarget->isPICStyleRIPRel() &&
7262       (M == CodeModel::Small || M == CodeModel::Kernel))
7263     WrapperKind = X86ISD::WrapperRIP;
7264   else if (Subtarget->isPICStyleGOT())
7265     OpFlag = X86II::MO_GOTOFF;
7266   else if (Subtarget->isPICStyleStubPIC())
7267     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7268
7269   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7270                                              CP->getAlignment(),
7271                                              CP->getOffset(), OpFlag);
7272   DebugLoc DL = CP->getDebugLoc();
7273   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7274   // With PIC, the address is actually $g + Offset.
7275   if (OpFlag) {
7276     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7277                          DAG.getNode(X86ISD::GlobalBaseReg,
7278                                      DebugLoc(), getPointerTy()),
7279                          Result);
7280   }
7281
7282   return Result;
7283 }
7284
7285 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7286   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7287
7288   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7289   // global base reg.
7290   unsigned char OpFlag = 0;
7291   unsigned WrapperKind = X86ISD::Wrapper;
7292   CodeModel::Model M = getTargetMachine().getCodeModel();
7293
7294   if (Subtarget->isPICStyleRIPRel() &&
7295       (M == CodeModel::Small || M == CodeModel::Kernel))
7296     WrapperKind = X86ISD::WrapperRIP;
7297   else if (Subtarget->isPICStyleGOT())
7298     OpFlag = X86II::MO_GOTOFF;
7299   else if (Subtarget->isPICStyleStubPIC())
7300     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7301
7302   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7303                                           OpFlag);
7304   DebugLoc DL = JT->getDebugLoc();
7305   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7306
7307   // With PIC, the address is actually $g + Offset.
7308   if (OpFlag)
7309     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7310                          DAG.getNode(X86ISD::GlobalBaseReg,
7311                                      DebugLoc(), getPointerTy()),
7312                          Result);
7313
7314   return Result;
7315 }
7316
7317 SDValue
7318 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7319   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7320
7321   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7322   // global base reg.
7323   unsigned char OpFlag = 0;
7324   unsigned WrapperKind = X86ISD::Wrapper;
7325   CodeModel::Model M = getTargetMachine().getCodeModel();
7326
7327   if (Subtarget->isPICStyleRIPRel() &&
7328       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7329     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7330       OpFlag = X86II::MO_GOTPCREL;
7331     WrapperKind = X86ISD::WrapperRIP;
7332   } else if (Subtarget->isPICStyleGOT()) {
7333     OpFlag = X86II::MO_GOT;
7334   } else if (Subtarget->isPICStyleStubPIC()) {
7335     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7336   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7337     OpFlag = X86II::MO_DARWIN_NONLAZY;
7338   }
7339
7340   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7341
7342   DebugLoc DL = Op.getDebugLoc();
7343   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7344
7345
7346   // With PIC, the address is actually $g + Offset.
7347   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7348       !Subtarget->is64Bit()) {
7349     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7350                          DAG.getNode(X86ISD::GlobalBaseReg,
7351                                      DebugLoc(), getPointerTy()),
7352                          Result);
7353   }
7354
7355   // For symbols that require a load from a stub to get the address, emit the
7356   // load.
7357   if (isGlobalStubReference(OpFlag))
7358     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7359                          MachinePointerInfo::getGOT(), false, false, false, 0);
7360
7361   return Result;
7362 }
7363
7364 SDValue
7365 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7366   // Create the TargetBlockAddressAddress node.
7367   unsigned char OpFlags =
7368     Subtarget->ClassifyBlockAddressReference();
7369   CodeModel::Model M = getTargetMachine().getCodeModel();
7370   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7371   DebugLoc dl = Op.getDebugLoc();
7372   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7373                                        /*isTarget=*/true, OpFlags);
7374
7375   if (Subtarget->isPICStyleRIPRel() &&
7376       (M == CodeModel::Small || M == CodeModel::Kernel))
7377     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7378   else
7379     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7380
7381   // With PIC, the address is actually $g + Offset.
7382   if (isGlobalRelativeToPICBase(OpFlags)) {
7383     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7384                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7385                          Result);
7386   }
7387
7388   return Result;
7389 }
7390
7391 SDValue
7392 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7393                                       int64_t Offset,
7394                                       SelectionDAG &DAG) const {
7395   // Create the TargetGlobalAddress node, folding in the constant
7396   // offset if it is legal.
7397   unsigned char OpFlags =
7398     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7399   CodeModel::Model M = getTargetMachine().getCodeModel();
7400   SDValue Result;
7401   if (OpFlags == X86II::MO_NO_FLAG &&
7402       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7403     // A direct static reference to a global.
7404     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7405     Offset = 0;
7406   } else {
7407     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7408   }
7409
7410   if (Subtarget->isPICStyleRIPRel() &&
7411       (M == CodeModel::Small || M == CodeModel::Kernel))
7412     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7413   else
7414     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7415
7416   // With PIC, the address is actually $g + Offset.
7417   if (isGlobalRelativeToPICBase(OpFlags)) {
7418     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7419                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7420                          Result);
7421   }
7422
7423   // For globals that require a load from a stub to get the address, emit the
7424   // load.
7425   if (isGlobalStubReference(OpFlags))
7426     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7427                          MachinePointerInfo::getGOT(), false, false, false, 0);
7428
7429   // If there was a non-zero offset that we didn't fold, create an explicit
7430   // addition for it.
7431   if (Offset != 0)
7432     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7433                          DAG.getConstant(Offset, getPointerTy()));
7434
7435   return Result;
7436 }
7437
7438 SDValue
7439 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7440   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7441   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7442   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7443 }
7444
7445 static SDValue
7446 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7447            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7448            unsigned char OperandFlags, bool LocalDynamic = false) {
7449   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7450   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7451   DebugLoc dl = GA->getDebugLoc();
7452   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7453                                            GA->getValueType(0),
7454                                            GA->getOffset(),
7455                                            OperandFlags);
7456
7457   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7458                                            : X86ISD::TLSADDR;
7459
7460   if (InFlag) {
7461     SDValue Ops[] = { Chain,  TGA, *InFlag };
7462     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7463   } else {
7464     SDValue Ops[]  = { Chain, TGA };
7465     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7466   }
7467
7468   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7469   MFI->setAdjustsStack(true);
7470
7471   SDValue Flag = Chain.getValue(1);
7472   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7473 }
7474
7475 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7476 static SDValue
7477 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7478                                 const EVT PtrVT) {
7479   SDValue InFlag;
7480   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7481   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7482                                      DAG.getNode(X86ISD::GlobalBaseReg,
7483                                                  DebugLoc(), PtrVT), InFlag);
7484   InFlag = Chain.getValue(1);
7485
7486   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7487 }
7488
7489 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7490 static SDValue
7491 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7492                                 const EVT PtrVT) {
7493   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7494                     X86::RAX, X86II::MO_TLSGD);
7495 }
7496
7497 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7498                                            SelectionDAG &DAG,
7499                                            const EVT PtrVT,
7500                                            bool is64Bit) {
7501   DebugLoc dl = GA->getDebugLoc();
7502
7503   // Get the start address of the TLS block for this module.
7504   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7505       .getInfo<X86MachineFunctionInfo>();
7506   MFI->incNumLocalDynamicTLSAccesses();
7507
7508   SDValue Base;
7509   if (is64Bit) {
7510     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7511                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7512   } else {
7513     SDValue InFlag;
7514     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7515         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7516     InFlag = Chain.getValue(1);
7517     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7518                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7519   }
7520
7521   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7522   // of Base.
7523
7524   // Build x@dtpoff.
7525   unsigned char OperandFlags = X86II::MO_DTPOFF;
7526   unsigned WrapperKind = X86ISD::Wrapper;
7527   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7528                                            GA->getValueType(0),
7529                                            GA->getOffset(), OperandFlags);
7530   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7531
7532   // Add x@dtpoff with the base.
7533   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7534 }
7535
7536 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7537 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7538                                    const EVT PtrVT, TLSModel::Model model,
7539                                    bool is64Bit, bool isPIC) {
7540   DebugLoc dl = GA->getDebugLoc();
7541
7542   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7543   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7544                                                          is64Bit ? 257 : 256));
7545
7546   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7547                                       DAG.getIntPtrConstant(0),
7548                                       MachinePointerInfo(Ptr),
7549                                       false, false, false, 0);
7550
7551   unsigned char OperandFlags = 0;
7552   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7553   // initialexec.
7554   unsigned WrapperKind = X86ISD::Wrapper;
7555   if (model == TLSModel::LocalExec) {
7556     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7557   } else if (model == TLSModel::InitialExec) {
7558     if (is64Bit) {
7559       OperandFlags = X86II::MO_GOTTPOFF;
7560       WrapperKind = X86ISD::WrapperRIP;
7561     } else {
7562       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7563     }
7564   } else {
7565     llvm_unreachable("Unexpected model");
7566   }
7567
7568   // emit "addl x@ntpoff,%eax" (local exec)
7569   // or "addl x@indntpoff,%eax" (initial exec)
7570   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7571   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7572                                            GA->getValueType(0),
7573                                            GA->getOffset(), OperandFlags);
7574   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7575
7576   if (model == TLSModel::InitialExec) {
7577     if (isPIC && !is64Bit) {
7578       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7579                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7580                            Offset);
7581     }
7582
7583     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7584                          MachinePointerInfo::getGOT(), false, false, false,
7585                          0);
7586   }
7587
7588   // The address of the thread local variable is the add of the thread
7589   // pointer with the offset of the variable.
7590   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7591 }
7592
7593 SDValue
7594 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7595
7596   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7597   const GlobalValue *GV = GA->getGlobal();
7598
7599   if (Subtarget->isTargetELF()) {
7600     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7601
7602     switch (model) {
7603       case TLSModel::GeneralDynamic:
7604         if (Subtarget->is64Bit())
7605           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7606         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7607       case TLSModel::LocalDynamic:
7608         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7609                                            Subtarget->is64Bit());
7610       case TLSModel::InitialExec:
7611       case TLSModel::LocalExec:
7612         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7613                                    Subtarget->is64Bit(),
7614                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7615     }
7616     llvm_unreachable("Unknown TLS model.");
7617   }
7618
7619   if (Subtarget->isTargetDarwin()) {
7620     // Darwin only has one model of TLS.  Lower to that.
7621     unsigned char OpFlag = 0;
7622     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7623                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7624
7625     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7626     // global base reg.
7627     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7628                   !Subtarget->is64Bit();
7629     if (PIC32)
7630       OpFlag = X86II::MO_TLVP_PIC_BASE;
7631     else
7632       OpFlag = X86II::MO_TLVP;
7633     DebugLoc DL = Op.getDebugLoc();
7634     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7635                                                 GA->getValueType(0),
7636                                                 GA->getOffset(), OpFlag);
7637     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7638
7639     // With PIC32, the address is actually $g + Offset.
7640     if (PIC32)
7641       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7642                            DAG.getNode(X86ISD::GlobalBaseReg,
7643                                        DebugLoc(), getPointerTy()),
7644                            Offset);
7645
7646     // Lowering the machine isd will make sure everything is in the right
7647     // location.
7648     SDValue Chain = DAG.getEntryNode();
7649     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7650     SDValue Args[] = { Chain, Offset };
7651     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7652
7653     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7654     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7655     MFI->setAdjustsStack(true);
7656
7657     // And our return value (tls address) is in the standard call return value
7658     // location.
7659     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7660     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7661                               Chain.getValue(1));
7662   }
7663
7664   if (Subtarget->isTargetWindows()) {
7665     // Just use the implicit TLS architecture
7666     // Need to generate someting similar to:
7667     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7668     //                                  ; from TEB
7669     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7670     //   mov     rcx, qword [rdx+rcx*8]
7671     //   mov     eax, .tls$:tlsvar
7672     //   [rax+rcx] contains the address
7673     // Windows 64bit: gs:0x58
7674     // Windows 32bit: fs:__tls_array
7675
7676     // If GV is an alias then use the aliasee for determining
7677     // thread-localness.
7678     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7679       GV = GA->resolveAliasedGlobal(false);
7680     DebugLoc dl = GA->getDebugLoc();
7681     SDValue Chain = DAG.getEntryNode();
7682
7683     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7684     // %gs:0x58 (64-bit).
7685     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7686                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7687                                                              256)
7688                                         : Type::getInt32PtrTy(*DAG.getContext(),
7689                                                               257));
7690
7691     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7692                                         Subtarget->is64Bit()
7693                                         ? DAG.getIntPtrConstant(0x58)
7694                                         : DAG.getExternalSymbol("_tls_array",
7695                                                                 getPointerTy()),
7696                                         MachinePointerInfo(Ptr),
7697                                         false, false, false, 0);
7698
7699     // Load the _tls_index variable
7700     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7701     if (Subtarget->is64Bit())
7702       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7703                            IDX, MachinePointerInfo(), MVT::i32,
7704                            false, false, 0);
7705     else
7706       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7707                         false, false, false, 0);
7708
7709     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7710                                     getPointerTy());
7711     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7712
7713     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7714     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7715                       false, false, false, 0);
7716
7717     // Get the offset of start of .tls section
7718     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7719                                              GA->getValueType(0),
7720                                              GA->getOffset(), X86II::MO_SECREL);
7721     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7722
7723     // The address of the thread local variable is the add of the thread
7724     // pointer with the offset of the variable.
7725     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7726   }
7727
7728   llvm_unreachable("TLS not implemented for this target.");
7729 }
7730
7731
7732 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7733 /// and take a 2 x i32 value to shift plus a shift amount.
7734 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7735   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7736   EVT VT = Op.getValueType();
7737   unsigned VTBits = VT.getSizeInBits();
7738   DebugLoc dl = Op.getDebugLoc();
7739   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7740   SDValue ShOpLo = Op.getOperand(0);
7741   SDValue ShOpHi = Op.getOperand(1);
7742   SDValue ShAmt  = Op.getOperand(2);
7743   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7744                                      DAG.getConstant(VTBits - 1, MVT::i8))
7745                        : DAG.getConstant(0, VT);
7746
7747   SDValue Tmp2, Tmp3;
7748   if (Op.getOpcode() == ISD::SHL_PARTS) {
7749     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7750     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7751   } else {
7752     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7753     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7754   }
7755
7756   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7757                                 DAG.getConstant(VTBits, MVT::i8));
7758   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7759                              AndNode, DAG.getConstant(0, MVT::i8));
7760
7761   SDValue Hi, Lo;
7762   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7763   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7764   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7765
7766   if (Op.getOpcode() == ISD::SHL_PARTS) {
7767     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7768     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7769   } else {
7770     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7771     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7772   }
7773
7774   SDValue Ops[2] = { Lo, Hi };
7775   return DAG.getMergeValues(Ops, 2, dl);
7776 }
7777
7778 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7779                                            SelectionDAG &DAG) const {
7780   EVT SrcVT = Op.getOperand(0).getValueType();
7781
7782   if (SrcVT.isVector())
7783     return SDValue();
7784
7785   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7786          "Unknown SINT_TO_FP to lower!");
7787
7788   // These are really Legal; return the operand so the caller accepts it as
7789   // Legal.
7790   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7791     return Op;
7792   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7793       Subtarget->is64Bit()) {
7794     return Op;
7795   }
7796
7797   DebugLoc dl = Op.getDebugLoc();
7798   unsigned Size = SrcVT.getSizeInBits()/8;
7799   MachineFunction &MF = DAG.getMachineFunction();
7800   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7801   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7802   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7803                                StackSlot,
7804                                MachinePointerInfo::getFixedStack(SSFI),
7805                                false, false, 0);
7806   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7807 }
7808
7809 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7810                                      SDValue StackSlot,
7811                                      SelectionDAG &DAG) const {
7812   // Build the FILD
7813   DebugLoc DL = Op.getDebugLoc();
7814   SDVTList Tys;
7815   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7816   if (useSSE)
7817     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7818   else
7819     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7820
7821   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7822
7823   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7824   MachineMemOperand *MMO;
7825   if (FI) {
7826     int SSFI = FI->getIndex();
7827     MMO =
7828       DAG.getMachineFunction()
7829       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7830                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7831   } else {
7832     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7833     StackSlot = StackSlot.getOperand(1);
7834   }
7835   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7836   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7837                                            X86ISD::FILD, DL,
7838                                            Tys, Ops, array_lengthof(Ops),
7839                                            SrcVT, MMO);
7840
7841   if (useSSE) {
7842     Chain = Result.getValue(1);
7843     SDValue InFlag = Result.getValue(2);
7844
7845     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7846     // shouldn't be necessary except that RFP cannot be live across
7847     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7848     MachineFunction &MF = DAG.getMachineFunction();
7849     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7850     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7851     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7852     Tys = DAG.getVTList(MVT::Other);
7853     SDValue Ops[] = {
7854       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7855     };
7856     MachineMemOperand *MMO =
7857       DAG.getMachineFunction()
7858       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7859                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7860
7861     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7862                                     Ops, array_lengthof(Ops),
7863                                     Op.getValueType(), MMO);
7864     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7865                          MachinePointerInfo::getFixedStack(SSFI),
7866                          false, false, false, 0);
7867   }
7868
7869   return Result;
7870 }
7871
7872 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7873 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7874                                                SelectionDAG &DAG) const {
7875   // This algorithm is not obvious. Here it is what we're trying to output:
7876   /*
7877      movq       %rax,  %xmm0
7878      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7879      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7880      #ifdef __SSE3__
7881        haddpd   %xmm0, %xmm0
7882      #else
7883        pshufd   $0x4e, %xmm0, %xmm1
7884        addpd    %xmm1, %xmm0
7885      #endif
7886   */
7887
7888   DebugLoc dl = Op.getDebugLoc();
7889   LLVMContext *Context = DAG.getContext();
7890
7891   // Build some magic constants.
7892   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7893   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7894   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7895
7896   SmallVector<Constant*,2> CV1;
7897   CV1.push_back(
7898         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7899   CV1.push_back(
7900         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7901   Constant *C1 = ConstantVector::get(CV1);
7902   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7903
7904   // Load the 64-bit value into an XMM register.
7905   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7906                             Op.getOperand(0));
7907   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7908                               MachinePointerInfo::getConstantPool(),
7909                               false, false, false, 16);
7910   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7911                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7912                               CLod0);
7913
7914   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7915                               MachinePointerInfo::getConstantPool(),
7916                               false, false, false, 16);
7917   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7918   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7919   SDValue Result;
7920
7921   if (Subtarget->hasSSE3()) {
7922     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7923     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7924   } else {
7925     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7926     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7927                                            S2F, 0x4E, DAG);
7928     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7929                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7930                          Sub);
7931   }
7932
7933   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7934                      DAG.getIntPtrConstant(0));
7935 }
7936
7937 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7938 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7939                                                SelectionDAG &DAG) const {
7940   DebugLoc dl = Op.getDebugLoc();
7941   // FP constant to bias correct the final result.
7942   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7943                                    MVT::f64);
7944
7945   // Load the 32-bit value into an XMM register.
7946   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7947                              Op.getOperand(0));
7948
7949   // Zero out the upper parts of the register.
7950   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7951
7952   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7953                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7954                      DAG.getIntPtrConstant(0));
7955
7956   // Or the load with the bias.
7957   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7958                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7959                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7960                                                    MVT::v2f64, Load)),
7961                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7962                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7963                                                    MVT::v2f64, Bias)));
7964   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7965                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7966                    DAG.getIntPtrConstant(0));
7967
7968   // Subtract the bias.
7969   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7970
7971   // Handle final rounding.
7972   EVT DestVT = Op.getValueType();
7973
7974   if (DestVT.bitsLT(MVT::f64))
7975     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7976                        DAG.getIntPtrConstant(0));
7977   if (DestVT.bitsGT(MVT::f64))
7978     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7979
7980   // Handle final rounding.
7981   return Sub;
7982 }
7983
7984 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7985                                            SelectionDAG &DAG) const {
7986   SDValue N0 = Op.getOperand(0);
7987   DebugLoc dl = Op.getDebugLoc();
7988
7989   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7990   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7991   // the optimization here.
7992   if (DAG.SignBitIsZero(N0))
7993     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7994
7995   EVT SrcVT = N0.getValueType();
7996   EVT DstVT = Op.getValueType();
7997   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7998     return LowerUINT_TO_FP_i64(Op, DAG);
7999   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8000     return LowerUINT_TO_FP_i32(Op, DAG);
8001   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8002     return SDValue();
8003
8004   // Make a 64-bit buffer, and use it to build an FILD.
8005   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8006   if (SrcVT == MVT::i32) {
8007     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8008     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8009                                      getPointerTy(), StackSlot, WordOff);
8010     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8011                                   StackSlot, MachinePointerInfo(),
8012                                   false, false, 0);
8013     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8014                                   OffsetSlot, MachinePointerInfo(),
8015                                   false, false, 0);
8016     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8017     return Fild;
8018   }
8019
8020   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8021   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8022                                StackSlot, MachinePointerInfo(),
8023                                false, false, 0);
8024   // For i64 source, we need to add the appropriate power of 2 if the input
8025   // was negative.  This is the same as the optimization in
8026   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8027   // we must be careful to do the computation in x87 extended precision, not
8028   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8029   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8030   MachineMemOperand *MMO =
8031     DAG.getMachineFunction()
8032     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8033                           MachineMemOperand::MOLoad, 8, 8);
8034
8035   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8036   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8037   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8038                                          MVT::i64, MMO);
8039
8040   APInt FF(32, 0x5F800000ULL);
8041
8042   // Check whether the sign bit is set.
8043   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8044                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8045                                  ISD::SETLT);
8046
8047   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8048   SDValue FudgePtr = DAG.getConstantPool(
8049                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8050                                          getPointerTy());
8051
8052   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8053   SDValue Zero = DAG.getIntPtrConstant(0);
8054   SDValue Four = DAG.getIntPtrConstant(4);
8055   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8056                                Zero, Four);
8057   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8058
8059   // Load the value out, extending it from f32 to f80.
8060   // FIXME: Avoid the extend by constructing the right constant pool?
8061   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8062                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8063                                  MVT::f32, false, false, 4);
8064   // Extend everything to 80 bits to force it to be done on x87.
8065   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8066   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8067 }
8068
8069 std::pair<SDValue,SDValue> X86TargetLowering::
8070 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8071   DebugLoc DL = Op.getDebugLoc();
8072
8073   EVT DstTy = Op.getValueType();
8074
8075   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8076     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8077     DstTy = MVT::i64;
8078   }
8079
8080   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8081          DstTy.getSimpleVT() >= MVT::i16 &&
8082          "Unknown FP_TO_INT to lower!");
8083
8084   // These are really Legal.
8085   if (DstTy == MVT::i32 &&
8086       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8087     return std::make_pair(SDValue(), SDValue());
8088   if (Subtarget->is64Bit() &&
8089       DstTy == MVT::i64 &&
8090       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8091     return std::make_pair(SDValue(), SDValue());
8092
8093   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8094   // stack slot, or into the FTOL runtime function.
8095   MachineFunction &MF = DAG.getMachineFunction();
8096   unsigned MemSize = DstTy.getSizeInBits()/8;
8097   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8098   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8099
8100   unsigned Opc;
8101   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8102     Opc = X86ISD::WIN_FTOL;
8103   else
8104     switch (DstTy.getSimpleVT().SimpleTy) {
8105     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8106     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8107     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8108     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8109     }
8110
8111   SDValue Chain = DAG.getEntryNode();
8112   SDValue Value = Op.getOperand(0);
8113   EVT TheVT = Op.getOperand(0).getValueType();
8114   // FIXME This causes a redundant load/store if the SSE-class value is already
8115   // in memory, such as if it is on the callstack.
8116   if (isScalarFPTypeInSSEReg(TheVT)) {
8117     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8118     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8119                          MachinePointerInfo::getFixedStack(SSFI),
8120                          false, false, 0);
8121     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8122     SDValue Ops[] = {
8123       Chain, StackSlot, DAG.getValueType(TheVT)
8124     };
8125
8126     MachineMemOperand *MMO =
8127       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8128                               MachineMemOperand::MOLoad, MemSize, MemSize);
8129     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8130                                     DstTy, MMO);
8131     Chain = Value.getValue(1);
8132     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8133     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8134   }
8135
8136   MachineMemOperand *MMO =
8137     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8138                             MachineMemOperand::MOStore, MemSize, MemSize);
8139
8140   if (Opc != X86ISD::WIN_FTOL) {
8141     // Build the FP_TO_INT*_IN_MEM
8142     SDValue Ops[] = { Chain, Value, StackSlot };
8143     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8144                                            Ops, 3, DstTy, MMO);
8145     return std::make_pair(FIST, StackSlot);
8146   } else {
8147     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8148       DAG.getVTList(MVT::Other, MVT::Glue),
8149       Chain, Value);
8150     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8151       MVT::i32, ftol.getValue(1));
8152     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8153       MVT::i32, eax.getValue(2));
8154     SDValue Ops[] = { eax, edx };
8155     SDValue pair = IsReplace
8156       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8157       : DAG.getMergeValues(Ops, 2, DL);
8158     return std::make_pair(pair, SDValue());
8159   }
8160 }
8161
8162 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8163                                            SelectionDAG &DAG) const {
8164   if (Op.getValueType().isVector())
8165     return SDValue();
8166
8167   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8168     /*IsSigned=*/ true, /*IsReplace=*/ false);
8169   SDValue FIST = Vals.first, StackSlot = Vals.second;
8170   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8171   if (FIST.getNode() == 0) return Op;
8172
8173   if (StackSlot.getNode())
8174     // Load the result.
8175     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8176                        FIST, StackSlot, MachinePointerInfo(),
8177                        false, false, false, 0);
8178
8179   // The node is the result.
8180   return FIST;
8181 }
8182
8183 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8184                                            SelectionDAG &DAG) const {
8185   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8186     /*IsSigned=*/ false, /*IsReplace=*/ false);
8187   SDValue FIST = Vals.first, StackSlot = Vals.second;
8188   assert(FIST.getNode() && "Unexpected failure");
8189
8190   if (StackSlot.getNode())
8191     // Load the result.
8192     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8193                        FIST, StackSlot, MachinePointerInfo(),
8194                        false, false, false, 0);
8195
8196   // The node is the result.
8197   return FIST;
8198 }
8199
8200 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8201   LLVMContext *Context = DAG.getContext();
8202   DebugLoc dl = Op.getDebugLoc();
8203   EVT VT = Op.getValueType();
8204   EVT EltVT = VT;
8205   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8206   if (VT.isVector()) {
8207     EltVT = VT.getVectorElementType();
8208     NumElts = VT.getVectorNumElements();
8209   }
8210   Constant *C;
8211   if (EltVT == MVT::f64)
8212     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8213   else
8214     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8215   C = ConstantVector::getSplat(NumElts, C);
8216   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8217   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8218   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8219                              MachinePointerInfo::getConstantPool(),
8220                              false, false, false, Alignment);
8221   if (VT.isVector()) {
8222     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8223     return DAG.getNode(ISD::BITCAST, dl, VT,
8224                        DAG.getNode(ISD::AND, dl, ANDVT,
8225                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8226                                                Op.getOperand(0)),
8227                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8228   }
8229   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8230 }
8231
8232 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8233   LLVMContext *Context = DAG.getContext();
8234   DebugLoc dl = Op.getDebugLoc();
8235   EVT VT = Op.getValueType();
8236   EVT EltVT = VT;
8237   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8238   if (VT.isVector()) {
8239     EltVT = VT.getVectorElementType();
8240     NumElts = VT.getVectorNumElements();
8241   }
8242   Constant *C;
8243   if (EltVT == MVT::f64)
8244     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8245   else
8246     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8247   C = ConstantVector::getSplat(NumElts, C);
8248   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8249   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8250   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8251                              MachinePointerInfo::getConstantPool(),
8252                              false, false, false, Alignment);
8253   if (VT.isVector()) {
8254     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8255     return DAG.getNode(ISD::BITCAST, dl, VT,
8256                        DAG.getNode(ISD::XOR, dl, XORVT,
8257                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8258                                                Op.getOperand(0)),
8259                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8260   }
8261
8262   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8263 }
8264
8265 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8266   LLVMContext *Context = DAG.getContext();
8267   SDValue Op0 = Op.getOperand(0);
8268   SDValue Op1 = Op.getOperand(1);
8269   DebugLoc dl = Op.getDebugLoc();
8270   EVT VT = Op.getValueType();
8271   EVT SrcVT = Op1.getValueType();
8272
8273   // If second operand is smaller, extend it first.
8274   if (SrcVT.bitsLT(VT)) {
8275     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8276     SrcVT = VT;
8277   }
8278   // And if it is bigger, shrink it first.
8279   if (SrcVT.bitsGT(VT)) {
8280     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8281     SrcVT = VT;
8282   }
8283
8284   // At this point the operands and the result should have the same
8285   // type, and that won't be f80 since that is not custom lowered.
8286
8287   // First get the sign bit of second operand.
8288   SmallVector<Constant*,4> CV;
8289   if (SrcVT == MVT::f64) {
8290     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8291     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8292   } else {
8293     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8294     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8295     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8296     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8297   }
8298   Constant *C = ConstantVector::get(CV);
8299   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8300   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8301                               MachinePointerInfo::getConstantPool(),
8302                               false, false, false, 16);
8303   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8304
8305   // Shift sign bit right or left if the two operands have different types.
8306   if (SrcVT.bitsGT(VT)) {
8307     // Op0 is MVT::f32, Op1 is MVT::f64.
8308     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8309     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8310                           DAG.getConstant(32, MVT::i32));
8311     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8312     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8313                           DAG.getIntPtrConstant(0));
8314   }
8315
8316   // Clear first operand sign bit.
8317   CV.clear();
8318   if (VT == MVT::f64) {
8319     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8320     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8321   } else {
8322     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8323     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8324     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8325     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8326   }
8327   C = ConstantVector::get(CV);
8328   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8329   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8330                               MachinePointerInfo::getConstantPool(),
8331                               false, false, false, 16);
8332   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8333
8334   // Or the value with the sign bit.
8335   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8336 }
8337
8338 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8339   SDValue N0 = Op.getOperand(0);
8340   DebugLoc dl = Op.getDebugLoc();
8341   EVT VT = Op.getValueType();
8342
8343   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8344   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8345                                   DAG.getConstant(1, VT));
8346   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8347 }
8348
8349 /// Emit nodes that will be selected as "test Op0,Op0", or something
8350 /// equivalent.
8351 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8352                                     SelectionDAG &DAG) const {
8353   DebugLoc dl = Op.getDebugLoc();
8354
8355   // CF and OF aren't always set the way we want. Determine which
8356   // of these we need.
8357   bool NeedCF = false;
8358   bool NeedOF = false;
8359   switch (X86CC) {
8360   default: break;
8361   case X86::COND_A: case X86::COND_AE:
8362   case X86::COND_B: case X86::COND_BE:
8363     NeedCF = true;
8364     break;
8365   case X86::COND_G: case X86::COND_GE:
8366   case X86::COND_L: case X86::COND_LE:
8367   case X86::COND_O: case X86::COND_NO:
8368     NeedOF = true;
8369     break;
8370   }
8371
8372   // See if we can use the EFLAGS value from the operand instead of
8373   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8374   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8375   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8376     // Emit a CMP with 0, which is the TEST pattern.
8377     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8378                        DAG.getConstant(0, Op.getValueType()));
8379
8380   unsigned Opcode = 0;
8381   unsigned NumOperands = 0;
8382
8383   // Truncate operations may prevent the merge of the SETCC instruction
8384   // and the arithmetic intruction before it. Attempt to truncate the operands
8385   // of the arithmetic instruction and use a reduced bit-width instruction.
8386   bool NeedTruncation = false;
8387   SDValue ArithOp = Op;
8388   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8389     SDValue Arith = Op->getOperand(0);
8390     // Both the trunc and the arithmetic op need to have one user each.
8391     if (Arith->hasOneUse())
8392       switch (Arith.getOpcode()) {
8393         default: break;
8394         case ISD::ADD:
8395         case ISD::SUB:
8396         case ISD::AND:
8397         case ISD::OR:
8398         case ISD::XOR: {
8399           NeedTruncation = true;
8400           ArithOp = Arith;
8401         }
8402       }
8403   }
8404
8405   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8406   // which may be the result of a CAST.  We use the variable 'Op', which is the
8407   // non-casted variable when we check for possible users.
8408   switch (ArithOp.getOpcode()) {
8409   case ISD::ADD:
8410     // Due to an isel shortcoming, be conservative if this add is likely to be
8411     // selected as part of a load-modify-store instruction. When the root node
8412     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8413     // uses of other nodes in the match, such as the ADD in this case. This
8414     // leads to the ADD being left around and reselected, with the result being
8415     // two adds in the output.  Alas, even if none our users are stores, that
8416     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8417     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8418     // climbing the DAG back to the root, and it doesn't seem to be worth the
8419     // effort.
8420     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8421          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8422       if (UI->getOpcode() != ISD::CopyToReg &&
8423           UI->getOpcode() != ISD::SETCC &&
8424           UI->getOpcode() != ISD::STORE)
8425         goto default_case;
8426
8427     if (ConstantSDNode *C =
8428         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8429       // An add of one will be selected as an INC.
8430       if (C->getAPIntValue() == 1) {
8431         Opcode = X86ISD::INC;
8432         NumOperands = 1;
8433         break;
8434       }
8435
8436       // An add of negative one (subtract of one) will be selected as a DEC.
8437       if (C->getAPIntValue().isAllOnesValue()) {
8438         Opcode = X86ISD::DEC;
8439         NumOperands = 1;
8440         break;
8441       }
8442     }
8443
8444     // Otherwise use a regular EFLAGS-setting add.
8445     Opcode = X86ISD::ADD;
8446     NumOperands = 2;
8447     break;
8448   case ISD::AND: {
8449     // If the primary and result isn't used, don't bother using X86ISD::AND,
8450     // because a TEST instruction will be better.
8451     bool NonFlagUse = false;
8452     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8453            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8454       SDNode *User = *UI;
8455       unsigned UOpNo = UI.getOperandNo();
8456       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8457         // Look pass truncate.
8458         UOpNo = User->use_begin().getOperandNo();
8459         User = *User->use_begin();
8460       }
8461
8462       if (User->getOpcode() != ISD::BRCOND &&
8463           User->getOpcode() != ISD::SETCC &&
8464           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8465         NonFlagUse = true;
8466         break;
8467       }
8468     }
8469
8470     if (!NonFlagUse)
8471       break;
8472   }
8473     // FALL THROUGH
8474   case ISD::SUB:
8475   case ISD::OR:
8476   case ISD::XOR:
8477     // Due to the ISEL shortcoming noted above, be conservative if this op is
8478     // likely to be selected as part of a load-modify-store instruction.
8479     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8480            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8481       if (UI->getOpcode() == ISD::STORE)
8482         goto default_case;
8483
8484     // Otherwise use a regular EFLAGS-setting instruction.
8485     switch (ArithOp.getOpcode()) {
8486     default: llvm_unreachable("unexpected operator!");
8487     case ISD::SUB: Opcode = X86ISD::SUB; break;
8488     case ISD::OR:  Opcode = X86ISD::OR;  break;
8489     case ISD::XOR: Opcode = X86ISD::XOR; break;
8490     case ISD::AND: Opcode = X86ISD::AND; break;
8491     }
8492
8493     NumOperands = 2;
8494     break;
8495   case X86ISD::ADD:
8496   case X86ISD::SUB:
8497   case X86ISD::INC:
8498   case X86ISD::DEC:
8499   case X86ISD::OR:
8500   case X86ISD::XOR:
8501   case X86ISD::AND:
8502     return SDValue(Op.getNode(), 1);
8503   default:
8504   default_case:
8505     break;
8506   }
8507
8508   // If we found that truncation is beneficial, perform the truncation and
8509   // update 'Op'.
8510   if (NeedTruncation) {
8511     EVT VT = Op.getValueType();
8512     SDValue WideVal = Op->getOperand(0);
8513     EVT WideVT = WideVal.getValueType();
8514     unsigned ConvertedOp = 0;
8515     // Use a target machine opcode to prevent further DAGCombine
8516     // optimizations that may separate the arithmetic operations
8517     // from the setcc node.
8518     switch (WideVal.getOpcode()) {
8519       default: break;
8520       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8521       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8522       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8523       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8524       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8525     }
8526
8527     if (ConvertedOp) {
8528       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8529       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8530         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8531         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8532         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8533       }
8534     }
8535   }
8536
8537   if (Opcode == 0)
8538     // Emit a CMP with 0, which is the TEST pattern.
8539     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8540                        DAG.getConstant(0, Op.getValueType()));
8541
8542   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8543   SmallVector<SDValue, 4> Ops;
8544   for (unsigned i = 0; i != NumOperands; ++i)
8545     Ops.push_back(Op.getOperand(i));
8546
8547   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8548   DAG.ReplaceAllUsesWith(Op, New);
8549   return SDValue(New.getNode(), 1);
8550 }
8551
8552 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8553 /// equivalent.
8554 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8555                                    SelectionDAG &DAG) const {
8556   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8557     if (C->getAPIntValue() == 0)
8558       return EmitTest(Op0, X86CC, DAG);
8559
8560   DebugLoc dl = Op0.getDebugLoc();
8561   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8562        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8563     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8564     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8565     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8566                               Op0, Op1);
8567     return SDValue(Sub.getNode(), 1);
8568   }
8569   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8570 }
8571
8572 /// Convert a comparison if required by the subtarget.
8573 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8574                                                  SelectionDAG &DAG) const {
8575   // If the subtarget does not support the FUCOMI instruction, floating-point
8576   // comparisons have to be converted.
8577   if (Subtarget->hasCMov() ||
8578       Cmp.getOpcode() != X86ISD::CMP ||
8579       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8580       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8581     return Cmp;
8582
8583   // The instruction selector will select an FUCOM instruction instead of
8584   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8585   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8586   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8587   DebugLoc dl = Cmp.getDebugLoc();
8588   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8589   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8590   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8591                             DAG.getConstant(8, MVT::i8));
8592   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8593   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8594 }
8595
8596 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8597 /// if it's possible.
8598 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8599                                      DebugLoc dl, SelectionDAG &DAG) const {
8600   SDValue Op0 = And.getOperand(0);
8601   SDValue Op1 = And.getOperand(1);
8602   if (Op0.getOpcode() == ISD::TRUNCATE)
8603     Op0 = Op0.getOperand(0);
8604   if (Op1.getOpcode() == ISD::TRUNCATE)
8605     Op1 = Op1.getOperand(0);
8606
8607   SDValue LHS, RHS;
8608   if (Op1.getOpcode() == ISD::SHL)
8609     std::swap(Op0, Op1);
8610   if (Op0.getOpcode() == ISD::SHL) {
8611     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8612       if (And00C->getZExtValue() == 1) {
8613         // If we looked past a truncate, check that it's only truncating away
8614         // known zeros.
8615         unsigned BitWidth = Op0.getValueSizeInBits();
8616         unsigned AndBitWidth = And.getValueSizeInBits();
8617         if (BitWidth > AndBitWidth) {
8618           APInt Zeros, Ones;
8619           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8620           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8621             return SDValue();
8622         }
8623         LHS = Op1;
8624         RHS = Op0.getOperand(1);
8625       }
8626   } else if (Op1.getOpcode() == ISD::Constant) {
8627     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8628     uint64_t AndRHSVal = AndRHS->getZExtValue();
8629     SDValue AndLHS = Op0;
8630
8631     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8632       LHS = AndLHS.getOperand(0);
8633       RHS = AndLHS.getOperand(1);
8634     }
8635
8636     // Use BT if the immediate can't be encoded in a TEST instruction.
8637     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8638       LHS = AndLHS;
8639       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8640     }
8641   }
8642
8643   if (LHS.getNode()) {
8644     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8645     // instruction.  Since the shift amount is in-range-or-undefined, we know
8646     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8647     // the encoding for the i16 version is larger than the i32 version.
8648     // Also promote i16 to i32 for performance / code size reason.
8649     if (LHS.getValueType() == MVT::i8 ||
8650         LHS.getValueType() == MVT::i16)
8651       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8652
8653     // If the operand types disagree, extend the shift amount to match.  Since
8654     // BT ignores high bits (like shifts) we can use anyextend.
8655     if (LHS.getValueType() != RHS.getValueType())
8656       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8657
8658     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8659     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8660     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8661                        DAG.getConstant(Cond, MVT::i8), BT);
8662   }
8663
8664   return SDValue();
8665 }
8666
8667 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8668
8669   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8670
8671   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8672   SDValue Op0 = Op.getOperand(0);
8673   SDValue Op1 = Op.getOperand(1);
8674   DebugLoc dl = Op.getDebugLoc();
8675   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8676
8677   // Optimize to BT if possible.
8678   // Lower (X & (1 << N)) == 0 to BT(X, N).
8679   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8680   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8681   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8682       Op1.getOpcode() == ISD::Constant &&
8683       cast<ConstantSDNode>(Op1)->isNullValue() &&
8684       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8685     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8686     if (NewSetCC.getNode())
8687       return NewSetCC;
8688   }
8689
8690   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8691   // these.
8692   if (Op1.getOpcode() == ISD::Constant &&
8693       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8694        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8695       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8696
8697     // If the input is a setcc, then reuse the input setcc or use a new one with
8698     // the inverted condition.
8699     if (Op0.getOpcode() == X86ISD::SETCC) {
8700       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8701       bool Invert = (CC == ISD::SETNE) ^
8702         cast<ConstantSDNode>(Op1)->isNullValue();
8703       if (!Invert) return Op0;
8704
8705       CCode = X86::GetOppositeBranchCondition(CCode);
8706       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8707                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8708     }
8709   }
8710
8711   bool isFP = Op1.getValueType().isFloatingPoint();
8712   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8713   if (X86CC == X86::COND_INVALID)
8714     return SDValue();
8715
8716   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8717   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8718   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8719                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8720 }
8721
8722 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8723 // ones, and then concatenate the result back.
8724 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8725   EVT VT = Op.getValueType();
8726
8727   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8728          "Unsupported value type for operation");
8729
8730   unsigned NumElems = VT.getVectorNumElements();
8731   DebugLoc dl = Op.getDebugLoc();
8732   SDValue CC = Op.getOperand(2);
8733
8734   // Extract the LHS vectors
8735   SDValue LHS = Op.getOperand(0);
8736   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8737   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8738
8739   // Extract the RHS vectors
8740   SDValue RHS = Op.getOperand(1);
8741   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8742   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8743
8744   // Issue the operation on the smaller types and concatenate the result back
8745   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8746   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8747   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8748                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8749                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8750 }
8751
8752
8753 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8754   SDValue Cond;
8755   SDValue Op0 = Op.getOperand(0);
8756   SDValue Op1 = Op.getOperand(1);
8757   SDValue CC = Op.getOperand(2);
8758   EVT VT = Op.getValueType();
8759   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8760   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8761   DebugLoc dl = Op.getDebugLoc();
8762
8763   if (isFP) {
8764 #ifndef NDEBUG
8765     EVT EltVT = Op0.getValueType().getVectorElementType();
8766     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8767 #endif
8768
8769     unsigned SSECC;
8770     bool Swap = false;
8771
8772     // SSE Condition code mapping:
8773     //  0 - EQ
8774     //  1 - LT
8775     //  2 - LE
8776     //  3 - UNORD
8777     //  4 - NEQ
8778     //  5 - NLT
8779     //  6 - NLE
8780     //  7 - ORD
8781     switch (SetCCOpcode) {
8782     default: llvm_unreachable("Unexpected SETCC condition");
8783     case ISD::SETOEQ:
8784     case ISD::SETEQ:  SSECC = 0; break;
8785     case ISD::SETOGT:
8786     case ISD::SETGT: Swap = true; // Fallthrough
8787     case ISD::SETLT:
8788     case ISD::SETOLT: SSECC = 1; break;
8789     case ISD::SETOGE:
8790     case ISD::SETGE: Swap = true; // Fallthrough
8791     case ISD::SETLE:
8792     case ISD::SETOLE: SSECC = 2; break;
8793     case ISD::SETUO:  SSECC = 3; break;
8794     case ISD::SETUNE:
8795     case ISD::SETNE:  SSECC = 4; break;
8796     case ISD::SETULE: Swap = true; // Fallthrough
8797     case ISD::SETUGE: SSECC = 5; break;
8798     case ISD::SETULT: Swap = true; // Fallthrough
8799     case ISD::SETUGT: SSECC = 6; break;
8800     case ISD::SETO:   SSECC = 7; break;
8801     case ISD::SETUEQ:
8802     case ISD::SETONE: SSECC = 8; break;
8803     }
8804     if (Swap)
8805       std::swap(Op0, Op1);
8806
8807     // In the two special cases we can't handle, emit two comparisons.
8808     if (SSECC == 8) {
8809       unsigned CC0, CC1;
8810       unsigned CombineOpc;
8811       if (SetCCOpcode == ISD::SETUEQ) {
8812         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8813       } else {
8814         assert(SetCCOpcode == ISD::SETONE);
8815         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8816       }
8817
8818       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8819                                  DAG.getConstant(CC0, MVT::i8));
8820       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8821                                  DAG.getConstant(CC1, MVT::i8));
8822       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8823     }
8824     // Handle all other FP comparisons here.
8825     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8826                        DAG.getConstant(SSECC, MVT::i8));
8827   }
8828
8829   // Break 256-bit integer vector compare into smaller ones.
8830   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8831     return Lower256IntVSETCC(Op, DAG);
8832
8833   // We are handling one of the integer comparisons here.  Since SSE only has
8834   // GT and EQ comparisons for integer, swapping operands and multiple
8835   // operations may be required for some comparisons.
8836   unsigned Opc;
8837   bool Swap = false, Invert = false, FlipSigns = false;
8838
8839   switch (SetCCOpcode) {
8840   default: llvm_unreachable("Unexpected SETCC condition");
8841   case ISD::SETNE:  Invert = true;
8842   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8843   case ISD::SETLT:  Swap = true;
8844   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8845   case ISD::SETGE:  Swap = true;
8846   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8847   case ISD::SETULT: Swap = true;
8848   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8849   case ISD::SETUGE: Swap = true;
8850   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8851   }
8852   if (Swap)
8853     std::swap(Op0, Op1);
8854
8855   // Check that the operation in question is available (most are plain SSE2,
8856   // but PCMPGTQ and PCMPEQQ have different requirements).
8857   if (VT == MVT::v2i64) {
8858     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8859       return SDValue();
8860     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8861       return SDValue();
8862   }
8863
8864   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8865   // bits of the inputs before performing those operations.
8866   if (FlipSigns) {
8867     EVT EltVT = VT.getVectorElementType();
8868     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8869                                       EltVT);
8870     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8871     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8872                                     SignBits.size());
8873     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8874     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8875   }
8876
8877   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8878
8879   // If the logical-not of the result is required, perform that now.
8880   if (Invert)
8881     Result = DAG.getNOT(dl, Result, VT);
8882
8883   return Result;
8884 }
8885
8886 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8887 static bool isX86LogicalCmp(SDValue Op) {
8888   unsigned Opc = Op.getNode()->getOpcode();
8889   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8890       Opc == X86ISD::SAHF)
8891     return true;
8892   if (Op.getResNo() == 1 &&
8893       (Opc == X86ISD::ADD ||
8894        Opc == X86ISD::SUB ||
8895        Opc == X86ISD::ADC ||
8896        Opc == X86ISD::SBB ||
8897        Opc == X86ISD::SMUL ||
8898        Opc == X86ISD::UMUL ||
8899        Opc == X86ISD::INC ||
8900        Opc == X86ISD::DEC ||
8901        Opc == X86ISD::OR ||
8902        Opc == X86ISD::XOR ||
8903        Opc == X86ISD::AND))
8904     return true;
8905
8906   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8907     return true;
8908
8909   return false;
8910 }
8911
8912 static bool isZero(SDValue V) {
8913   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8914   return C && C->isNullValue();
8915 }
8916
8917 static bool isAllOnes(SDValue V) {
8918   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8919   return C && C->isAllOnesValue();
8920 }
8921
8922 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8923   if (V.getOpcode() != ISD::TRUNCATE)
8924     return false;
8925
8926   SDValue VOp0 = V.getOperand(0);
8927   unsigned InBits = VOp0.getValueSizeInBits();
8928   unsigned Bits = V.getValueSizeInBits();
8929   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8930 }
8931
8932 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8933   bool addTest = true;
8934   SDValue Cond  = Op.getOperand(0);
8935   SDValue Op1 = Op.getOperand(1);
8936   SDValue Op2 = Op.getOperand(2);
8937   DebugLoc DL = Op.getDebugLoc();
8938   SDValue CC;
8939
8940   if (Cond.getOpcode() == ISD::SETCC) {
8941     SDValue NewCond = LowerSETCC(Cond, DAG);
8942     if (NewCond.getNode())
8943       Cond = NewCond;
8944   }
8945
8946   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8947   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8948   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8949   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8950   if (Cond.getOpcode() == X86ISD::SETCC &&
8951       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8952       isZero(Cond.getOperand(1).getOperand(1))) {
8953     SDValue Cmp = Cond.getOperand(1);
8954
8955     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8956
8957     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8958         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8959       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8960
8961       SDValue CmpOp0 = Cmp.getOperand(0);
8962       // Apply further optimizations for special cases
8963       // (select (x != 0), -1, 0) -> neg & sbb
8964       // (select (x == 0), 0, -1) -> neg & sbb
8965       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8966         if (YC->isNullValue() &&
8967             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8968           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8969           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8970                                     DAG.getConstant(0, CmpOp0.getValueType()),
8971                                     CmpOp0);
8972           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8973                                     DAG.getConstant(X86::COND_B, MVT::i8),
8974                                     SDValue(Neg.getNode(), 1));
8975           return Res;
8976         }
8977
8978       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8979                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8980       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8981
8982       SDValue Res =   // Res = 0 or -1.
8983         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8984                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8985
8986       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8987         Res = DAG.getNOT(DL, Res, Res.getValueType());
8988
8989       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8990       if (N2C == 0 || !N2C->isNullValue())
8991         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8992       return Res;
8993     }
8994   }
8995
8996   // Look past (and (setcc_carry (cmp ...)), 1).
8997   if (Cond.getOpcode() == ISD::AND &&
8998       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8999     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9000     if (C && C->getAPIntValue() == 1)
9001       Cond = Cond.getOperand(0);
9002   }
9003
9004   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9005   // setting operand in place of the X86ISD::SETCC.
9006   unsigned CondOpcode = Cond.getOpcode();
9007   if (CondOpcode == X86ISD::SETCC ||
9008       CondOpcode == X86ISD::SETCC_CARRY) {
9009     CC = Cond.getOperand(0);
9010
9011     SDValue Cmp = Cond.getOperand(1);
9012     unsigned Opc = Cmp.getOpcode();
9013     EVT VT = Op.getValueType();
9014
9015     bool IllegalFPCMov = false;
9016     if (VT.isFloatingPoint() && !VT.isVector() &&
9017         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9018       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9019
9020     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9021         Opc == X86ISD::BT) { // FIXME
9022       Cond = Cmp;
9023       addTest = false;
9024     }
9025   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9026              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9027              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9028               Cond.getOperand(0).getValueType() != MVT::i8)) {
9029     SDValue LHS = Cond.getOperand(0);
9030     SDValue RHS = Cond.getOperand(1);
9031     unsigned X86Opcode;
9032     unsigned X86Cond;
9033     SDVTList VTs;
9034     switch (CondOpcode) {
9035     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9036     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9037     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9038     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9039     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9040     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9041     default: llvm_unreachable("unexpected overflowing operator");
9042     }
9043     if (CondOpcode == ISD::UMULO)
9044       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9045                           MVT::i32);
9046     else
9047       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9048
9049     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9050
9051     if (CondOpcode == ISD::UMULO)
9052       Cond = X86Op.getValue(2);
9053     else
9054       Cond = X86Op.getValue(1);
9055
9056     CC = DAG.getConstant(X86Cond, MVT::i8);
9057     addTest = false;
9058   }
9059
9060   if (addTest) {
9061     // Look pass the truncate if the high bits are known zero.
9062     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9063         Cond = Cond.getOperand(0);
9064
9065     // We know the result of AND is compared against zero. Try to match
9066     // it to BT.
9067     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9068       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9069       if (NewSetCC.getNode()) {
9070         CC = NewSetCC.getOperand(0);
9071         Cond = NewSetCC.getOperand(1);
9072         addTest = false;
9073       }
9074     }
9075   }
9076
9077   if (addTest) {
9078     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9079     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9080   }
9081
9082   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9083   // a <  b ?  0 : -1 -> RES = setcc_carry
9084   // a >= b ? -1 :  0 -> RES = setcc_carry
9085   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9086   if (Cond.getOpcode() == X86ISD::SUB) {
9087     Cond = ConvertCmpIfNecessary(Cond, DAG);
9088     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9089
9090     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9091         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9092       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9093                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9094       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9095         return DAG.getNOT(DL, Res, Res.getValueType());
9096       return Res;
9097     }
9098   }
9099
9100   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9101   // condition is true.
9102   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9103   SDValue Ops[] = { Op2, Op1, CC, Cond };
9104   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9105 }
9106
9107 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9108 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9109 // from the AND / OR.
9110 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9111   Opc = Op.getOpcode();
9112   if (Opc != ISD::OR && Opc != ISD::AND)
9113     return false;
9114   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9115           Op.getOperand(0).hasOneUse() &&
9116           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9117           Op.getOperand(1).hasOneUse());
9118 }
9119
9120 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9121 // 1 and that the SETCC node has a single use.
9122 static bool isXor1OfSetCC(SDValue Op) {
9123   if (Op.getOpcode() != ISD::XOR)
9124     return false;
9125   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9126   if (N1C && N1C->getAPIntValue() == 1) {
9127     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9128       Op.getOperand(0).hasOneUse();
9129   }
9130   return false;
9131 }
9132
9133 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9134   bool addTest = true;
9135   SDValue Chain = Op.getOperand(0);
9136   SDValue Cond  = Op.getOperand(1);
9137   SDValue Dest  = Op.getOperand(2);
9138   DebugLoc dl = Op.getDebugLoc();
9139   SDValue CC;
9140   bool Inverted = false;
9141
9142   if (Cond.getOpcode() == ISD::SETCC) {
9143     // Check for setcc([su]{add,sub,mul}o == 0).
9144     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9145         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9146         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9147         Cond.getOperand(0).getResNo() == 1 &&
9148         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9149          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9150          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9151          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9152          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9153          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9154       Inverted = true;
9155       Cond = Cond.getOperand(0);
9156     } else {
9157       SDValue NewCond = LowerSETCC(Cond, DAG);
9158       if (NewCond.getNode())
9159         Cond = NewCond;
9160     }
9161   }
9162 #if 0
9163   // FIXME: LowerXALUO doesn't handle these!!
9164   else if (Cond.getOpcode() == X86ISD::ADD  ||
9165            Cond.getOpcode() == X86ISD::SUB  ||
9166            Cond.getOpcode() == X86ISD::SMUL ||
9167            Cond.getOpcode() == X86ISD::UMUL)
9168     Cond = LowerXALUO(Cond, DAG);
9169 #endif
9170
9171   // Look pass (and (setcc_carry (cmp ...)), 1).
9172   if (Cond.getOpcode() == ISD::AND &&
9173       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9174     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9175     if (C && C->getAPIntValue() == 1)
9176       Cond = Cond.getOperand(0);
9177   }
9178
9179   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9180   // setting operand in place of the X86ISD::SETCC.
9181   unsigned CondOpcode = Cond.getOpcode();
9182   if (CondOpcode == X86ISD::SETCC ||
9183       CondOpcode == X86ISD::SETCC_CARRY) {
9184     CC = Cond.getOperand(0);
9185
9186     SDValue Cmp = Cond.getOperand(1);
9187     unsigned Opc = Cmp.getOpcode();
9188     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9189     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9190       Cond = Cmp;
9191       addTest = false;
9192     } else {
9193       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9194       default: break;
9195       case X86::COND_O:
9196       case X86::COND_B:
9197         // These can only come from an arithmetic instruction with overflow,
9198         // e.g. SADDO, UADDO.
9199         Cond = Cond.getNode()->getOperand(1);
9200         addTest = false;
9201         break;
9202       }
9203     }
9204   }
9205   CondOpcode = Cond.getOpcode();
9206   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9207       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9208       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9209        Cond.getOperand(0).getValueType() != MVT::i8)) {
9210     SDValue LHS = Cond.getOperand(0);
9211     SDValue RHS = Cond.getOperand(1);
9212     unsigned X86Opcode;
9213     unsigned X86Cond;
9214     SDVTList VTs;
9215     switch (CondOpcode) {
9216     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9217     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9218     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9219     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9220     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9221     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9222     default: llvm_unreachable("unexpected overflowing operator");
9223     }
9224     if (Inverted)
9225       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9226     if (CondOpcode == ISD::UMULO)
9227       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9228                           MVT::i32);
9229     else
9230       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9231
9232     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9233
9234     if (CondOpcode == ISD::UMULO)
9235       Cond = X86Op.getValue(2);
9236     else
9237       Cond = X86Op.getValue(1);
9238
9239     CC = DAG.getConstant(X86Cond, MVT::i8);
9240     addTest = false;
9241   } else {
9242     unsigned CondOpc;
9243     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9244       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9245       if (CondOpc == ISD::OR) {
9246         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9247         // two branches instead of an explicit OR instruction with a
9248         // separate test.
9249         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9250             isX86LogicalCmp(Cmp)) {
9251           CC = Cond.getOperand(0).getOperand(0);
9252           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9253                               Chain, Dest, CC, Cmp);
9254           CC = Cond.getOperand(1).getOperand(0);
9255           Cond = Cmp;
9256           addTest = false;
9257         }
9258       } else { // ISD::AND
9259         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9260         // two branches instead of an explicit AND instruction with a
9261         // separate test. However, we only do this if this block doesn't
9262         // have a fall-through edge, because this requires an explicit
9263         // jmp when the condition is false.
9264         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9265             isX86LogicalCmp(Cmp) &&
9266             Op.getNode()->hasOneUse()) {
9267           X86::CondCode CCode =
9268             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9269           CCode = X86::GetOppositeBranchCondition(CCode);
9270           CC = DAG.getConstant(CCode, MVT::i8);
9271           SDNode *User = *Op.getNode()->use_begin();
9272           // Look for an unconditional branch following this conditional branch.
9273           // We need this because we need to reverse the successors in order
9274           // to implement FCMP_OEQ.
9275           if (User->getOpcode() == ISD::BR) {
9276             SDValue FalseBB = User->getOperand(1);
9277             SDNode *NewBR =
9278               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9279             assert(NewBR == User);
9280             (void)NewBR;
9281             Dest = FalseBB;
9282
9283             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9284                                 Chain, Dest, CC, Cmp);
9285             X86::CondCode CCode =
9286               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9287             CCode = X86::GetOppositeBranchCondition(CCode);
9288             CC = DAG.getConstant(CCode, MVT::i8);
9289             Cond = Cmp;
9290             addTest = false;
9291           }
9292         }
9293       }
9294     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9295       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9296       // It should be transformed during dag combiner except when the condition
9297       // is set by a arithmetics with overflow node.
9298       X86::CondCode CCode =
9299         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9300       CCode = X86::GetOppositeBranchCondition(CCode);
9301       CC = DAG.getConstant(CCode, MVT::i8);
9302       Cond = Cond.getOperand(0).getOperand(1);
9303       addTest = false;
9304     } else if (Cond.getOpcode() == ISD::SETCC &&
9305                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9306       // For FCMP_OEQ, we can emit
9307       // two branches instead of an explicit AND instruction with a
9308       // separate test. However, we only do this if this block doesn't
9309       // have a fall-through edge, because this requires an explicit
9310       // jmp when the condition is false.
9311       if (Op.getNode()->hasOneUse()) {
9312         SDNode *User = *Op.getNode()->use_begin();
9313         // Look for an unconditional branch following this conditional branch.
9314         // We need this because we need to reverse the successors in order
9315         // to implement FCMP_OEQ.
9316         if (User->getOpcode() == ISD::BR) {
9317           SDValue FalseBB = User->getOperand(1);
9318           SDNode *NewBR =
9319             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9320           assert(NewBR == User);
9321           (void)NewBR;
9322           Dest = FalseBB;
9323
9324           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9325                                     Cond.getOperand(0), Cond.getOperand(1));
9326           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9327           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9328           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9329                               Chain, Dest, CC, Cmp);
9330           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9331           Cond = Cmp;
9332           addTest = false;
9333         }
9334       }
9335     } else if (Cond.getOpcode() == ISD::SETCC &&
9336                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9337       // For FCMP_UNE, we can emit
9338       // two branches instead of an explicit AND instruction with a
9339       // separate test. However, we only do this if this block doesn't
9340       // have a fall-through edge, because this requires an explicit
9341       // jmp when the condition is false.
9342       if (Op.getNode()->hasOneUse()) {
9343         SDNode *User = *Op.getNode()->use_begin();
9344         // Look for an unconditional branch following this conditional branch.
9345         // We need this because we need to reverse the successors in order
9346         // to implement FCMP_UNE.
9347         if (User->getOpcode() == ISD::BR) {
9348           SDValue FalseBB = User->getOperand(1);
9349           SDNode *NewBR =
9350             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9351           assert(NewBR == User);
9352           (void)NewBR;
9353
9354           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9355                                     Cond.getOperand(0), Cond.getOperand(1));
9356           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9357           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9358           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9359                               Chain, Dest, CC, Cmp);
9360           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9361           Cond = Cmp;
9362           addTest = false;
9363           Dest = FalseBB;
9364         }
9365       }
9366     }
9367   }
9368
9369   if (addTest) {
9370     // Look pass the truncate if the high bits are known zero.
9371     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9372         Cond = Cond.getOperand(0);
9373
9374     // We know the result of AND is compared against zero. Try to match
9375     // it to BT.
9376     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9377       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9378       if (NewSetCC.getNode()) {
9379         CC = NewSetCC.getOperand(0);
9380         Cond = NewSetCC.getOperand(1);
9381         addTest = false;
9382       }
9383     }
9384   }
9385
9386   if (addTest) {
9387     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9388     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9389   }
9390   Cond = ConvertCmpIfNecessary(Cond, DAG);
9391   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9392                      Chain, Dest, CC, Cond);
9393 }
9394
9395
9396 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9397 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9398 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9399 // that the guard pages used by the OS virtual memory manager are allocated in
9400 // correct sequence.
9401 SDValue
9402 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9403                                            SelectionDAG &DAG) const {
9404   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9405           getTargetMachine().Options.EnableSegmentedStacks) &&
9406          "This should be used only on Windows targets or when segmented stacks "
9407          "are being used");
9408   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9409   DebugLoc dl = Op.getDebugLoc();
9410
9411   // Get the inputs.
9412   SDValue Chain = Op.getOperand(0);
9413   SDValue Size  = Op.getOperand(1);
9414   // FIXME: Ensure alignment here
9415
9416   bool Is64Bit = Subtarget->is64Bit();
9417   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9418
9419   if (getTargetMachine().Options.EnableSegmentedStacks) {
9420     MachineFunction &MF = DAG.getMachineFunction();
9421     MachineRegisterInfo &MRI = MF.getRegInfo();
9422
9423     if (Is64Bit) {
9424       // The 64 bit implementation of segmented stacks needs to clobber both r10
9425       // r11. This makes it impossible to use it along with nested parameters.
9426       const Function *F = MF.getFunction();
9427
9428       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9429            I != E; ++I)
9430         if (I->hasNestAttr())
9431           report_fatal_error("Cannot use segmented stacks with functions that "
9432                              "have nested arguments.");
9433     }
9434
9435     const TargetRegisterClass *AddrRegClass =
9436       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9437     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9438     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9439     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9440                                 DAG.getRegister(Vreg, SPTy));
9441     SDValue Ops1[2] = { Value, Chain };
9442     return DAG.getMergeValues(Ops1, 2, dl);
9443   } else {
9444     SDValue Flag;
9445     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9446
9447     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9448     Flag = Chain.getValue(1);
9449     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9450
9451     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9452     Flag = Chain.getValue(1);
9453
9454     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9455
9456     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9457     return DAG.getMergeValues(Ops1, 2, dl);
9458   }
9459 }
9460
9461 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9462   MachineFunction &MF = DAG.getMachineFunction();
9463   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9464
9465   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9466   DebugLoc DL = Op.getDebugLoc();
9467
9468   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9469     // vastart just stores the address of the VarArgsFrameIndex slot into the
9470     // memory location argument.
9471     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9472                                    getPointerTy());
9473     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9474                         MachinePointerInfo(SV), false, false, 0);
9475   }
9476
9477   // __va_list_tag:
9478   //   gp_offset         (0 - 6 * 8)
9479   //   fp_offset         (48 - 48 + 8 * 16)
9480   //   overflow_arg_area (point to parameters coming in memory).
9481   //   reg_save_area
9482   SmallVector<SDValue, 8> MemOps;
9483   SDValue FIN = Op.getOperand(1);
9484   // Store gp_offset
9485   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9486                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9487                                                MVT::i32),
9488                                FIN, MachinePointerInfo(SV), false, false, 0);
9489   MemOps.push_back(Store);
9490
9491   // Store fp_offset
9492   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9493                     FIN, DAG.getIntPtrConstant(4));
9494   Store = DAG.getStore(Op.getOperand(0), DL,
9495                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9496                                        MVT::i32),
9497                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9498   MemOps.push_back(Store);
9499
9500   // Store ptr to overflow_arg_area
9501   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9502                     FIN, DAG.getIntPtrConstant(4));
9503   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9504                                     getPointerTy());
9505   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9506                        MachinePointerInfo(SV, 8),
9507                        false, false, 0);
9508   MemOps.push_back(Store);
9509
9510   // Store ptr to reg_save_area.
9511   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9512                     FIN, DAG.getIntPtrConstant(8));
9513   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9514                                     getPointerTy());
9515   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9516                        MachinePointerInfo(SV, 16), false, false, 0);
9517   MemOps.push_back(Store);
9518   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9519                      &MemOps[0], MemOps.size());
9520 }
9521
9522 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9523   assert(Subtarget->is64Bit() &&
9524          "LowerVAARG only handles 64-bit va_arg!");
9525   assert((Subtarget->isTargetLinux() ||
9526           Subtarget->isTargetDarwin()) &&
9527           "Unhandled target in LowerVAARG");
9528   assert(Op.getNode()->getNumOperands() == 4);
9529   SDValue Chain = Op.getOperand(0);
9530   SDValue SrcPtr = Op.getOperand(1);
9531   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9532   unsigned Align = Op.getConstantOperandVal(3);
9533   DebugLoc dl = Op.getDebugLoc();
9534
9535   EVT ArgVT = Op.getNode()->getValueType(0);
9536   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9537   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9538   uint8_t ArgMode;
9539
9540   // Decide which area this value should be read from.
9541   // TODO: Implement the AMD64 ABI in its entirety. This simple
9542   // selection mechanism works only for the basic types.
9543   if (ArgVT == MVT::f80) {
9544     llvm_unreachable("va_arg for f80 not yet implemented");
9545   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9546     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9547   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9548     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9549   } else {
9550     llvm_unreachable("Unhandled argument type in LowerVAARG");
9551   }
9552
9553   if (ArgMode == 2) {
9554     // Sanity Check: Make sure using fp_offset makes sense.
9555     assert(!getTargetMachine().Options.UseSoftFloat &&
9556            !(DAG.getMachineFunction()
9557                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9558            Subtarget->hasSSE1());
9559   }
9560
9561   // Insert VAARG_64 node into the DAG
9562   // VAARG_64 returns two values: Variable Argument Address, Chain
9563   SmallVector<SDValue, 11> InstOps;
9564   InstOps.push_back(Chain);
9565   InstOps.push_back(SrcPtr);
9566   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9567   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9568   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9569   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9570   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9571                                           VTs, &InstOps[0], InstOps.size(),
9572                                           MVT::i64,
9573                                           MachinePointerInfo(SV),
9574                                           /*Align=*/0,
9575                                           /*Volatile=*/false,
9576                                           /*ReadMem=*/true,
9577                                           /*WriteMem=*/true);
9578   Chain = VAARG.getValue(1);
9579
9580   // Load the next argument and return it
9581   return DAG.getLoad(ArgVT, dl,
9582                      Chain,
9583                      VAARG,
9584                      MachinePointerInfo(),
9585                      false, false, false, 0);
9586 }
9587
9588 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9589                            SelectionDAG &DAG) {
9590   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9591   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9592   SDValue Chain = Op.getOperand(0);
9593   SDValue DstPtr = Op.getOperand(1);
9594   SDValue SrcPtr = Op.getOperand(2);
9595   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9596   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9597   DebugLoc DL = Op.getDebugLoc();
9598
9599   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9600                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9601                        false,
9602                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9603 }
9604
9605 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9606 // may or may not be a constant. Takes immediate version of shift as input.
9607 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9608                                    SDValue SrcOp, SDValue ShAmt,
9609                                    SelectionDAG &DAG) {
9610   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9611
9612   if (isa<ConstantSDNode>(ShAmt)) {
9613     // Constant may be a TargetConstant. Use a regular constant.
9614     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9615     switch (Opc) {
9616       default: llvm_unreachable("Unknown target vector shift node");
9617       case X86ISD::VSHLI:
9618       case X86ISD::VSRLI:
9619       case X86ISD::VSRAI:
9620         return DAG.getNode(Opc, dl, VT, SrcOp,
9621                            DAG.getConstant(ShiftAmt, MVT::i32));
9622     }
9623   }
9624
9625   // Change opcode to non-immediate version
9626   switch (Opc) {
9627     default: llvm_unreachable("Unknown target vector shift node");
9628     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9629     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9630     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9631   }
9632
9633   // Need to build a vector containing shift amount
9634   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9635   SDValue ShOps[4];
9636   ShOps[0] = ShAmt;
9637   ShOps[1] = DAG.getConstant(0, MVT::i32);
9638   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9639   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9640
9641   // The return type has to be a 128-bit type with the same element
9642   // type as the input type.
9643   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9644   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9645
9646   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9647   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9648 }
9649
9650 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9651   DebugLoc dl = Op.getDebugLoc();
9652   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9653   switch (IntNo) {
9654   default: return SDValue();    // Don't custom lower most intrinsics.
9655   // Comparison intrinsics.
9656   case Intrinsic::x86_sse_comieq_ss:
9657   case Intrinsic::x86_sse_comilt_ss:
9658   case Intrinsic::x86_sse_comile_ss:
9659   case Intrinsic::x86_sse_comigt_ss:
9660   case Intrinsic::x86_sse_comige_ss:
9661   case Intrinsic::x86_sse_comineq_ss:
9662   case Intrinsic::x86_sse_ucomieq_ss:
9663   case Intrinsic::x86_sse_ucomilt_ss:
9664   case Intrinsic::x86_sse_ucomile_ss:
9665   case Intrinsic::x86_sse_ucomigt_ss:
9666   case Intrinsic::x86_sse_ucomige_ss:
9667   case Intrinsic::x86_sse_ucomineq_ss:
9668   case Intrinsic::x86_sse2_comieq_sd:
9669   case Intrinsic::x86_sse2_comilt_sd:
9670   case Intrinsic::x86_sse2_comile_sd:
9671   case Intrinsic::x86_sse2_comigt_sd:
9672   case Intrinsic::x86_sse2_comige_sd:
9673   case Intrinsic::x86_sse2_comineq_sd:
9674   case Intrinsic::x86_sse2_ucomieq_sd:
9675   case Intrinsic::x86_sse2_ucomilt_sd:
9676   case Intrinsic::x86_sse2_ucomile_sd:
9677   case Intrinsic::x86_sse2_ucomigt_sd:
9678   case Intrinsic::x86_sse2_ucomige_sd:
9679   case Intrinsic::x86_sse2_ucomineq_sd: {
9680     unsigned Opc;
9681     ISD::CondCode CC;
9682     switch (IntNo) {
9683     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9684     case Intrinsic::x86_sse_comieq_ss:
9685     case Intrinsic::x86_sse2_comieq_sd:
9686       Opc = X86ISD::COMI;
9687       CC = ISD::SETEQ;
9688       break;
9689     case Intrinsic::x86_sse_comilt_ss:
9690     case Intrinsic::x86_sse2_comilt_sd:
9691       Opc = X86ISD::COMI;
9692       CC = ISD::SETLT;
9693       break;
9694     case Intrinsic::x86_sse_comile_ss:
9695     case Intrinsic::x86_sse2_comile_sd:
9696       Opc = X86ISD::COMI;
9697       CC = ISD::SETLE;
9698       break;
9699     case Intrinsic::x86_sse_comigt_ss:
9700     case Intrinsic::x86_sse2_comigt_sd:
9701       Opc = X86ISD::COMI;
9702       CC = ISD::SETGT;
9703       break;
9704     case Intrinsic::x86_sse_comige_ss:
9705     case Intrinsic::x86_sse2_comige_sd:
9706       Opc = X86ISD::COMI;
9707       CC = ISD::SETGE;
9708       break;
9709     case Intrinsic::x86_sse_comineq_ss:
9710     case Intrinsic::x86_sse2_comineq_sd:
9711       Opc = X86ISD::COMI;
9712       CC = ISD::SETNE;
9713       break;
9714     case Intrinsic::x86_sse_ucomieq_ss:
9715     case Intrinsic::x86_sse2_ucomieq_sd:
9716       Opc = X86ISD::UCOMI;
9717       CC = ISD::SETEQ;
9718       break;
9719     case Intrinsic::x86_sse_ucomilt_ss:
9720     case Intrinsic::x86_sse2_ucomilt_sd:
9721       Opc = X86ISD::UCOMI;
9722       CC = ISD::SETLT;
9723       break;
9724     case Intrinsic::x86_sse_ucomile_ss:
9725     case Intrinsic::x86_sse2_ucomile_sd:
9726       Opc = X86ISD::UCOMI;
9727       CC = ISD::SETLE;
9728       break;
9729     case Intrinsic::x86_sse_ucomigt_ss:
9730     case Intrinsic::x86_sse2_ucomigt_sd:
9731       Opc = X86ISD::UCOMI;
9732       CC = ISD::SETGT;
9733       break;
9734     case Intrinsic::x86_sse_ucomige_ss:
9735     case Intrinsic::x86_sse2_ucomige_sd:
9736       Opc = X86ISD::UCOMI;
9737       CC = ISD::SETGE;
9738       break;
9739     case Intrinsic::x86_sse_ucomineq_ss:
9740     case Intrinsic::x86_sse2_ucomineq_sd:
9741       Opc = X86ISD::UCOMI;
9742       CC = ISD::SETNE;
9743       break;
9744     }
9745
9746     SDValue LHS = Op.getOperand(1);
9747     SDValue RHS = Op.getOperand(2);
9748     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9749     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9750     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9751     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9752                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9753     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9754   }
9755
9756   // Arithmetic intrinsics.
9757   case Intrinsic::x86_sse2_pmulu_dq:
9758   case Intrinsic::x86_avx2_pmulu_dq:
9759     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9760                        Op.getOperand(1), Op.getOperand(2));
9761
9762   // SSE3/AVX horizontal add/sub intrinsics
9763   case Intrinsic::x86_sse3_hadd_ps:
9764   case Intrinsic::x86_sse3_hadd_pd:
9765   case Intrinsic::x86_avx_hadd_ps_256:
9766   case Intrinsic::x86_avx_hadd_pd_256:
9767   case Intrinsic::x86_sse3_hsub_ps:
9768   case Intrinsic::x86_sse3_hsub_pd:
9769   case Intrinsic::x86_avx_hsub_ps_256:
9770   case Intrinsic::x86_avx_hsub_pd_256:
9771   case Intrinsic::x86_ssse3_phadd_w_128:
9772   case Intrinsic::x86_ssse3_phadd_d_128:
9773   case Intrinsic::x86_avx2_phadd_w:
9774   case Intrinsic::x86_avx2_phadd_d:
9775   case Intrinsic::x86_ssse3_phsub_w_128:
9776   case Intrinsic::x86_ssse3_phsub_d_128:
9777   case Intrinsic::x86_avx2_phsub_w:
9778   case Intrinsic::x86_avx2_phsub_d: {
9779     unsigned Opcode;
9780     switch (IntNo) {
9781     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9782     case Intrinsic::x86_sse3_hadd_ps:
9783     case Intrinsic::x86_sse3_hadd_pd:
9784     case Intrinsic::x86_avx_hadd_ps_256:
9785     case Intrinsic::x86_avx_hadd_pd_256:
9786       Opcode = X86ISD::FHADD;
9787       break;
9788     case Intrinsic::x86_sse3_hsub_ps:
9789     case Intrinsic::x86_sse3_hsub_pd:
9790     case Intrinsic::x86_avx_hsub_ps_256:
9791     case Intrinsic::x86_avx_hsub_pd_256:
9792       Opcode = X86ISD::FHSUB;
9793       break;
9794     case Intrinsic::x86_ssse3_phadd_w_128:
9795     case Intrinsic::x86_ssse3_phadd_d_128:
9796     case Intrinsic::x86_avx2_phadd_w:
9797     case Intrinsic::x86_avx2_phadd_d:
9798       Opcode = X86ISD::HADD;
9799       break;
9800     case Intrinsic::x86_ssse3_phsub_w_128:
9801     case Intrinsic::x86_ssse3_phsub_d_128:
9802     case Intrinsic::x86_avx2_phsub_w:
9803     case Intrinsic::x86_avx2_phsub_d:
9804       Opcode = X86ISD::HSUB;
9805       break;
9806     }
9807     return DAG.getNode(Opcode, dl, Op.getValueType(),
9808                        Op.getOperand(1), Op.getOperand(2));
9809   }
9810
9811   // AVX2 variable shift intrinsics
9812   case Intrinsic::x86_avx2_psllv_d:
9813   case Intrinsic::x86_avx2_psllv_q:
9814   case Intrinsic::x86_avx2_psllv_d_256:
9815   case Intrinsic::x86_avx2_psllv_q_256:
9816   case Intrinsic::x86_avx2_psrlv_d:
9817   case Intrinsic::x86_avx2_psrlv_q:
9818   case Intrinsic::x86_avx2_psrlv_d_256:
9819   case Intrinsic::x86_avx2_psrlv_q_256:
9820   case Intrinsic::x86_avx2_psrav_d:
9821   case Intrinsic::x86_avx2_psrav_d_256: {
9822     unsigned Opcode;
9823     switch (IntNo) {
9824     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9825     case Intrinsic::x86_avx2_psllv_d:
9826     case Intrinsic::x86_avx2_psllv_q:
9827     case Intrinsic::x86_avx2_psllv_d_256:
9828     case Intrinsic::x86_avx2_psllv_q_256:
9829       Opcode = ISD::SHL;
9830       break;
9831     case Intrinsic::x86_avx2_psrlv_d:
9832     case Intrinsic::x86_avx2_psrlv_q:
9833     case Intrinsic::x86_avx2_psrlv_d_256:
9834     case Intrinsic::x86_avx2_psrlv_q_256:
9835       Opcode = ISD::SRL;
9836       break;
9837     case Intrinsic::x86_avx2_psrav_d:
9838     case Intrinsic::x86_avx2_psrav_d_256:
9839       Opcode = ISD::SRA;
9840       break;
9841     }
9842     return DAG.getNode(Opcode, dl, Op.getValueType(),
9843                        Op.getOperand(1), Op.getOperand(2));
9844   }
9845
9846   case Intrinsic::x86_ssse3_pshuf_b_128:
9847   case Intrinsic::x86_avx2_pshuf_b:
9848     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9849                        Op.getOperand(1), Op.getOperand(2));
9850
9851   case Intrinsic::x86_ssse3_psign_b_128:
9852   case Intrinsic::x86_ssse3_psign_w_128:
9853   case Intrinsic::x86_ssse3_psign_d_128:
9854   case Intrinsic::x86_avx2_psign_b:
9855   case Intrinsic::x86_avx2_psign_w:
9856   case Intrinsic::x86_avx2_psign_d:
9857     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9858                        Op.getOperand(1), Op.getOperand(2));
9859
9860   case Intrinsic::x86_sse41_insertps:
9861     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9862                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9863
9864   case Intrinsic::x86_avx_vperm2f128_ps_256:
9865   case Intrinsic::x86_avx_vperm2f128_pd_256:
9866   case Intrinsic::x86_avx_vperm2f128_si_256:
9867   case Intrinsic::x86_avx2_vperm2i128:
9868     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9869                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9870
9871   case Intrinsic::x86_avx2_permd:
9872   case Intrinsic::x86_avx2_permps:
9873     // Operands intentionally swapped. Mask is last operand to intrinsic,
9874     // but second operand for node/intruction.
9875     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9876                        Op.getOperand(2), Op.getOperand(1));
9877
9878   // ptest and testp intrinsics. The intrinsic these come from are designed to
9879   // return an integer value, not just an instruction so lower it to the ptest
9880   // or testp pattern and a setcc for the result.
9881   case Intrinsic::x86_sse41_ptestz:
9882   case Intrinsic::x86_sse41_ptestc:
9883   case Intrinsic::x86_sse41_ptestnzc:
9884   case Intrinsic::x86_avx_ptestz_256:
9885   case Intrinsic::x86_avx_ptestc_256:
9886   case Intrinsic::x86_avx_ptestnzc_256:
9887   case Intrinsic::x86_avx_vtestz_ps:
9888   case Intrinsic::x86_avx_vtestc_ps:
9889   case Intrinsic::x86_avx_vtestnzc_ps:
9890   case Intrinsic::x86_avx_vtestz_pd:
9891   case Intrinsic::x86_avx_vtestc_pd:
9892   case Intrinsic::x86_avx_vtestnzc_pd:
9893   case Intrinsic::x86_avx_vtestz_ps_256:
9894   case Intrinsic::x86_avx_vtestc_ps_256:
9895   case Intrinsic::x86_avx_vtestnzc_ps_256:
9896   case Intrinsic::x86_avx_vtestz_pd_256:
9897   case Intrinsic::x86_avx_vtestc_pd_256:
9898   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9899     bool IsTestPacked = false;
9900     unsigned X86CC;
9901     switch (IntNo) {
9902     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9903     case Intrinsic::x86_avx_vtestz_ps:
9904     case Intrinsic::x86_avx_vtestz_pd:
9905     case Intrinsic::x86_avx_vtestz_ps_256:
9906     case Intrinsic::x86_avx_vtestz_pd_256:
9907       IsTestPacked = true; // Fallthrough
9908     case Intrinsic::x86_sse41_ptestz:
9909     case Intrinsic::x86_avx_ptestz_256:
9910       // ZF = 1
9911       X86CC = X86::COND_E;
9912       break;
9913     case Intrinsic::x86_avx_vtestc_ps:
9914     case Intrinsic::x86_avx_vtestc_pd:
9915     case Intrinsic::x86_avx_vtestc_ps_256:
9916     case Intrinsic::x86_avx_vtestc_pd_256:
9917       IsTestPacked = true; // Fallthrough
9918     case Intrinsic::x86_sse41_ptestc:
9919     case Intrinsic::x86_avx_ptestc_256:
9920       // CF = 1
9921       X86CC = X86::COND_B;
9922       break;
9923     case Intrinsic::x86_avx_vtestnzc_ps:
9924     case Intrinsic::x86_avx_vtestnzc_pd:
9925     case Intrinsic::x86_avx_vtestnzc_ps_256:
9926     case Intrinsic::x86_avx_vtestnzc_pd_256:
9927       IsTestPacked = true; // Fallthrough
9928     case Intrinsic::x86_sse41_ptestnzc:
9929     case Intrinsic::x86_avx_ptestnzc_256:
9930       // ZF and CF = 0
9931       X86CC = X86::COND_A;
9932       break;
9933     }
9934
9935     SDValue LHS = Op.getOperand(1);
9936     SDValue RHS = Op.getOperand(2);
9937     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9938     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9939     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9940     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9941     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9942   }
9943
9944   // SSE/AVX shift intrinsics
9945   case Intrinsic::x86_sse2_psll_w:
9946   case Intrinsic::x86_sse2_psll_d:
9947   case Intrinsic::x86_sse2_psll_q:
9948   case Intrinsic::x86_avx2_psll_w:
9949   case Intrinsic::x86_avx2_psll_d:
9950   case Intrinsic::x86_avx2_psll_q:
9951   case Intrinsic::x86_sse2_psrl_w:
9952   case Intrinsic::x86_sse2_psrl_d:
9953   case Intrinsic::x86_sse2_psrl_q:
9954   case Intrinsic::x86_avx2_psrl_w:
9955   case Intrinsic::x86_avx2_psrl_d:
9956   case Intrinsic::x86_avx2_psrl_q:
9957   case Intrinsic::x86_sse2_psra_w:
9958   case Intrinsic::x86_sse2_psra_d:
9959   case Intrinsic::x86_avx2_psra_w:
9960   case Intrinsic::x86_avx2_psra_d: {
9961     unsigned Opcode;
9962     switch (IntNo) {
9963     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9964     case Intrinsic::x86_sse2_psll_w:
9965     case Intrinsic::x86_sse2_psll_d:
9966     case Intrinsic::x86_sse2_psll_q:
9967     case Intrinsic::x86_avx2_psll_w:
9968     case Intrinsic::x86_avx2_psll_d:
9969     case Intrinsic::x86_avx2_psll_q:
9970       Opcode = X86ISD::VSHL;
9971       break;
9972     case Intrinsic::x86_sse2_psrl_w:
9973     case Intrinsic::x86_sse2_psrl_d:
9974     case Intrinsic::x86_sse2_psrl_q:
9975     case Intrinsic::x86_avx2_psrl_w:
9976     case Intrinsic::x86_avx2_psrl_d:
9977     case Intrinsic::x86_avx2_psrl_q:
9978       Opcode = X86ISD::VSRL;
9979       break;
9980     case Intrinsic::x86_sse2_psra_w:
9981     case Intrinsic::x86_sse2_psra_d:
9982     case Intrinsic::x86_avx2_psra_w:
9983     case Intrinsic::x86_avx2_psra_d:
9984       Opcode = X86ISD::VSRA;
9985       break;
9986     }
9987     return DAG.getNode(Opcode, dl, Op.getValueType(),
9988                        Op.getOperand(1), Op.getOperand(2));
9989   }
9990
9991   // SSE/AVX immediate shift intrinsics
9992   case Intrinsic::x86_sse2_pslli_w:
9993   case Intrinsic::x86_sse2_pslli_d:
9994   case Intrinsic::x86_sse2_pslli_q:
9995   case Intrinsic::x86_avx2_pslli_w:
9996   case Intrinsic::x86_avx2_pslli_d:
9997   case Intrinsic::x86_avx2_pslli_q:
9998   case Intrinsic::x86_sse2_psrli_w:
9999   case Intrinsic::x86_sse2_psrli_d:
10000   case Intrinsic::x86_sse2_psrli_q:
10001   case Intrinsic::x86_avx2_psrli_w:
10002   case Intrinsic::x86_avx2_psrli_d:
10003   case Intrinsic::x86_avx2_psrli_q:
10004   case Intrinsic::x86_sse2_psrai_w:
10005   case Intrinsic::x86_sse2_psrai_d:
10006   case Intrinsic::x86_avx2_psrai_w:
10007   case Intrinsic::x86_avx2_psrai_d: {
10008     unsigned Opcode;
10009     switch (IntNo) {
10010     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10011     case Intrinsic::x86_sse2_pslli_w:
10012     case Intrinsic::x86_sse2_pslli_d:
10013     case Intrinsic::x86_sse2_pslli_q:
10014     case Intrinsic::x86_avx2_pslli_w:
10015     case Intrinsic::x86_avx2_pslli_d:
10016     case Intrinsic::x86_avx2_pslli_q:
10017       Opcode = X86ISD::VSHLI;
10018       break;
10019     case Intrinsic::x86_sse2_psrli_w:
10020     case Intrinsic::x86_sse2_psrli_d:
10021     case Intrinsic::x86_sse2_psrli_q:
10022     case Intrinsic::x86_avx2_psrli_w:
10023     case Intrinsic::x86_avx2_psrli_d:
10024     case Intrinsic::x86_avx2_psrli_q:
10025       Opcode = X86ISD::VSRLI;
10026       break;
10027     case Intrinsic::x86_sse2_psrai_w:
10028     case Intrinsic::x86_sse2_psrai_d:
10029     case Intrinsic::x86_avx2_psrai_w:
10030     case Intrinsic::x86_avx2_psrai_d:
10031       Opcode = X86ISD::VSRAI;
10032       break;
10033     }
10034     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10035                                Op.getOperand(1), Op.getOperand(2), DAG);
10036   }
10037
10038   case Intrinsic::x86_sse42_pcmpistria128:
10039   case Intrinsic::x86_sse42_pcmpestria128:
10040   case Intrinsic::x86_sse42_pcmpistric128:
10041   case Intrinsic::x86_sse42_pcmpestric128:
10042   case Intrinsic::x86_sse42_pcmpistrio128:
10043   case Intrinsic::x86_sse42_pcmpestrio128:
10044   case Intrinsic::x86_sse42_pcmpistris128:
10045   case Intrinsic::x86_sse42_pcmpestris128:
10046   case Intrinsic::x86_sse42_pcmpistriz128:
10047   case Intrinsic::x86_sse42_pcmpestriz128: {
10048     unsigned Opcode;
10049     unsigned X86CC;
10050     switch (IntNo) {
10051     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10052     case Intrinsic::x86_sse42_pcmpistria128:
10053       Opcode = X86ISD::PCMPISTRI;
10054       X86CC = X86::COND_A;
10055       break;
10056     case Intrinsic::x86_sse42_pcmpestria128:
10057       Opcode = X86ISD::PCMPESTRI;
10058       X86CC = X86::COND_A;
10059       break;
10060     case Intrinsic::x86_sse42_pcmpistric128:
10061       Opcode = X86ISD::PCMPISTRI;
10062       X86CC = X86::COND_B;
10063       break;
10064     case Intrinsic::x86_sse42_pcmpestric128:
10065       Opcode = X86ISD::PCMPESTRI;
10066       X86CC = X86::COND_B;
10067       break;
10068     case Intrinsic::x86_sse42_pcmpistrio128:
10069       Opcode = X86ISD::PCMPISTRI;
10070       X86CC = X86::COND_O;
10071       break;
10072     case Intrinsic::x86_sse42_pcmpestrio128:
10073       Opcode = X86ISD::PCMPESTRI;
10074       X86CC = X86::COND_O;
10075       break;
10076     case Intrinsic::x86_sse42_pcmpistris128:
10077       Opcode = X86ISD::PCMPISTRI;
10078       X86CC = X86::COND_S;
10079       break;
10080     case Intrinsic::x86_sse42_pcmpestris128:
10081       Opcode = X86ISD::PCMPESTRI;
10082       X86CC = X86::COND_S;
10083       break;
10084     case Intrinsic::x86_sse42_pcmpistriz128:
10085       Opcode = X86ISD::PCMPISTRI;
10086       X86CC = X86::COND_E;
10087       break;
10088     case Intrinsic::x86_sse42_pcmpestriz128:
10089       Opcode = X86ISD::PCMPESTRI;
10090       X86CC = X86::COND_E;
10091       break;
10092     }
10093     SmallVector<SDValue, 5> NewOps;
10094     NewOps.append(Op->op_begin()+1, Op->op_end());
10095     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10096     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10097     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10098                                 DAG.getConstant(X86CC, MVT::i8),
10099                                 SDValue(PCMP.getNode(), 1));
10100     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10101   }
10102
10103   case Intrinsic::x86_sse42_pcmpistri128:
10104   case Intrinsic::x86_sse42_pcmpestri128: {
10105     unsigned Opcode;
10106     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10107       Opcode = X86ISD::PCMPISTRI;
10108     else
10109       Opcode = X86ISD::PCMPESTRI;
10110
10111     SmallVector<SDValue, 5> NewOps;
10112     NewOps.append(Op->op_begin()+1, Op->op_end());
10113     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10114     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10115   }
10116   case Intrinsic::x86_fma_vfmadd_ps:
10117   case Intrinsic::x86_fma_vfmadd_pd:
10118   case Intrinsic::x86_fma_vfmsub_ps:
10119   case Intrinsic::x86_fma_vfmsub_pd:
10120   case Intrinsic::x86_fma_vfnmadd_ps:
10121   case Intrinsic::x86_fma_vfnmadd_pd:
10122   case Intrinsic::x86_fma_vfnmsub_ps:
10123   case Intrinsic::x86_fma_vfnmsub_pd:
10124   case Intrinsic::x86_fma_vfmaddsub_ps:
10125   case Intrinsic::x86_fma_vfmaddsub_pd:
10126   case Intrinsic::x86_fma_vfmsubadd_ps:
10127   case Intrinsic::x86_fma_vfmsubadd_pd:
10128   case Intrinsic::x86_fma_vfmadd_ps_256:
10129   case Intrinsic::x86_fma_vfmadd_pd_256:
10130   case Intrinsic::x86_fma_vfmsub_ps_256:
10131   case Intrinsic::x86_fma_vfmsub_pd_256:
10132   case Intrinsic::x86_fma_vfnmadd_ps_256:
10133   case Intrinsic::x86_fma_vfnmadd_pd_256:
10134   case Intrinsic::x86_fma_vfnmsub_ps_256:
10135   case Intrinsic::x86_fma_vfnmsub_pd_256:
10136   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10137   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10138   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10139   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10140     unsigned Opc;
10141     switch (IntNo) {
10142     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10143     case Intrinsic::x86_fma_vfmadd_ps:
10144     case Intrinsic::x86_fma_vfmadd_pd:
10145     case Intrinsic::x86_fma_vfmadd_ps_256:
10146     case Intrinsic::x86_fma_vfmadd_pd_256:
10147       Opc = X86ISD::FMADD;
10148       break;
10149     case Intrinsic::x86_fma_vfmsub_ps:
10150     case Intrinsic::x86_fma_vfmsub_pd:
10151     case Intrinsic::x86_fma_vfmsub_ps_256:
10152     case Intrinsic::x86_fma_vfmsub_pd_256:
10153       Opc = X86ISD::FMSUB;
10154       break;
10155     case Intrinsic::x86_fma_vfnmadd_ps:
10156     case Intrinsic::x86_fma_vfnmadd_pd:
10157     case Intrinsic::x86_fma_vfnmadd_ps_256:
10158     case Intrinsic::x86_fma_vfnmadd_pd_256:
10159       Opc = X86ISD::FNMADD;
10160       break;
10161     case Intrinsic::x86_fma_vfnmsub_ps:
10162     case Intrinsic::x86_fma_vfnmsub_pd:
10163     case Intrinsic::x86_fma_vfnmsub_ps_256:
10164     case Intrinsic::x86_fma_vfnmsub_pd_256:
10165       Opc = X86ISD::FNMSUB;
10166       break;
10167     case Intrinsic::x86_fma_vfmaddsub_ps:
10168     case Intrinsic::x86_fma_vfmaddsub_pd:
10169     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10170     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10171       Opc = X86ISD::FMADDSUB;
10172       break;
10173     case Intrinsic::x86_fma_vfmsubadd_ps:
10174     case Intrinsic::x86_fma_vfmsubadd_pd:
10175     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10176     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10177       Opc = X86ISD::FMSUBADD;
10178       break;
10179     }
10180
10181     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10182                        Op.getOperand(2), Op.getOperand(3));
10183   }
10184   }
10185 }
10186
10187 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10188   DebugLoc dl = Op.getDebugLoc();
10189   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10190   switch (IntNo) {
10191   default: return SDValue();    // Don't custom lower most intrinsics.
10192
10193   // RDRAND intrinsics.
10194   case Intrinsic::x86_rdrand_16:
10195   case Intrinsic::x86_rdrand_32:
10196   case Intrinsic::x86_rdrand_64: {
10197     // Emit the node with the right value type.
10198     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10199     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10200
10201     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10202     // return the value from Rand, which is always 0, casted to i32.
10203     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10204                       DAG.getConstant(1, Op->getValueType(1)),
10205                       DAG.getConstant(X86::COND_B, MVT::i32),
10206                       SDValue(Result.getNode(), 1) };
10207     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10208                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10209                                   Ops, 4);
10210
10211     // Return { result, isValid, chain }.
10212     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10213                        SDValue(Result.getNode(), 2));
10214   }
10215   }
10216 }
10217
10218 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10219                                            SelectionDAG &DAG) const {
10220   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10221   MFI->setReturnAddressIsTaken(true);
10222
10223   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10224   DebugLoc dl = Op.getDebugLoc();
10225
10226   if (Depth > 0) {
10227     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10228     SDValue Offset =
10229       DAG.getConstant(TD->getPointerSize(),
10230                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10231     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10232                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10233                                    FrameAddr, Offset),
10234                        MachinePointerInfo(), false, false, false, 0);
10235   }
10236
10237   // Just load the return address.
10238   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10239   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10240                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10241 }
10242
10243 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10244   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10245   MFI->setFrameAddressIsTaken(true);
10246
10247   EVT VT = Op.getValueType();
10248   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10249   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10250   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10251   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10252   while (Depth--)
10253     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10254                             MachinePointerInfo(),
10255                             false, false, false, 0);
10256   return FrameAddr;
10257 }
10258
10259 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10260                                                      SelectionDAG &DAG) const {
10261   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10262 }
10263
10264 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10265   SDValue Chain     = Op.getOperand(0);
10266   SDValue Offset    = Op.getOperand(1);
10267   SDValue Handler   = Op.getOperand(2);
10268   DebugLoc dl       = Op.getDebugLoc();
10269
10270   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10271                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10272                                      getPointerTy());
10273   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10274
10275   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10276                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10277   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10278   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10279                        false, false, 0);
10280   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10281
10282   return DAG.getNode(X86ISD::EH_RETURN, dl,
10283                      MVT::Other,
10284                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10285 }
10286
10287 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10288   return Op.getOperand(0);
10289 }
10290
10291 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10292                                                 SelectionDAG &DAG) const {
10293   SDValue Root = Op.getOperand(0);
10294   SDValue Trmp = Op.getOperand(1); // trampoline
10295   SDValue FPtr = Op.getOperand(2); // nested function
10296   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10297   DebugLoc dl  = Op.getDebugLoc();
10298
10299   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10300
10301   if (Subtarget->is64Bit()) {
10302     SDValue OutChains[6];
10303
10304     // Large code-model.
10305     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10306     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10307
10308     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10309     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10310
10311     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10312
10313     // Load the pointer to the nested function into R11.
10314     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10315     SDValue Addr = Trmp;
10316     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10317                                 Addr, MachinePointerInfo(TrmpAddr),
10318                                 false, false, 0);
10319
10320     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10321                        DAG.getConstant(2, MVT::i64));
10322     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10323                                 MachinePointerInfo(TrmpAddr, 2),
10324                                 false, false, 2);
10325
10326     // Load the 'nest' parameter value into R10.
10327     // R10 is specified in X86CallingConv.td
10328     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10329     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10330                        DAG.getConstant(10, MVT::i64));
10331     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10332                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10333                                 false, false, 0);
10334
10335     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10336                        DAG.getConstant(12, MVT::i64));
10337     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10338                                 MachinePointerInfo(TrmpAddr, 12),
10339                                 false, false, 2);
10340
10341     // Jump to the nested function.
10342     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10343     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10344                        DAG.getConstant(20, MVT::i64));
10345     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10346                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10347                                 false, false, 0);
10348
10349     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10350     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10351                        DAG.getConstant(22, MVT::i64));
10352     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10353                                 MachinePointerInfo(TrmpAddr, 22),
10354                                 false, false, 0);
10355
10356     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10357   } else {
10358     const Function *Func =
10359       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10360     CallingConv::ID CC = Func->getCallingConv();
10361     unsigned NestReg;
10362
10363     switch (CC) {
10364     default:
10365       llvm_unreachable("Unsupported calling convention");
10366     case CallingConv::C:
10367     case CallingConv::X86_StdCall: {
10368       // Pass 'nest' parameter in ECX.
10369       // Must be kept in sync with X86CallingConv.td
10370       NestReg = X86::ECX;
10371
10372       // Check that ECX wasn't needed by an 'inreg' parameter.
10373       FunctionType *FTy = Func->getFunctionType();
10374       const AttrListPtr &Attrs = Func->getAttributes();
10375
10376       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10377         unsigned InRegCount = 0;
10378         unsigned Idx = 1;
10379
10380         for (FunctionType::param_iterator I = FTy->param_begin(),
10381              E = FTy->param_end(); I != E; ++I, ++Idx)
10382           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10383             // FIXME: should only count parameters that are lowered to integers.
10384             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10385
10386         if (InRegCount > 2) {
10387           report_fatal_error("Nest register in use - reduce number of inreg"
10388                              " parameters!");
10389         }
10390       }
10391       break;
10392     }
10393     case CallingConv::X86_FastCall:
10394     case CallingConv::X86_ThisCall:
10395     case CallingConv::Fast:
10396       // Pass 'nest' parameter in EAX.
10397       // Must be kept in sync with X86CallingConv.td
10398       NestReg = X86::EAX;
10399       break;
10400     }
10401
10402     SDValue OutChains[4];
10403     SDValue Addr, Disp;
10404
10405     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10406                        DAG.getConstant(10, MVT::i32));
10407     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10408
10409     // This is storing the opcode for MOV32ri.
10410     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10411     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10412     OutChains[0] = DAG.getStore(Root, dl,
10413                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10414                                 Trmp, MachinePointerInfo(TrmpAddr),
10415                                 false, false, 0);
10416
10417     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10418                        DAG.getConstant(1, MVT::i32));
10419     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10420                                 MachinePointerInfo(TrmpAddr, 1),
10421                                 false, false, 1);
10422
10423     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10424     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10425                        DAG.getConstant(5, MVT::i32));
10426     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10427                                 MachinePointerInfo(TrmpAddr, 5),
10428                                 false, false, 1);
10429
10430     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10431                        DAG.getConstant(6, MVT::i32));
10432     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10433                                 MachinePointerInfo(TrmpAddr, 6),
10434                                 false, false, 1);
10435
10436     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10437   }
10438 }
10439
10440 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10441                                             SelectionDAG &DAG) const {
10442   /*
10443    The rounding mode is in bits 11:10 of FPSR, and has the following
10444    settings:
10445      00 Round to nearest
10446      01 Round to -inf
10447      10 Round to +inf
10448      11 Round to 0
10449
10450   FLT_ROUNDS, on the other hand, expects the following:
10451     -1 Undefined
10452      0 Round to 0
10453      1 Round to nearest
10454      2 Round to +inf
10455      3 Round to -inf
10456
10457   To perform the conversion, we do:
10458     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10459   */
10460
10461   MachineFunction &MF = DAG.getMachineFunction();
10462   const TargetMachine &TM = MF.getTarget();
10463   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10464   unsigned StackAlignment = TFI.getStackAlignment();
10465   EVT VT = Op.getValueType();
10466   DebugLoc DL = Op.getDebugLoc();
10467
10468   // Save FP Control Word to stack slot
10469   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10470   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10471
10472
10473   MachineMemOperand *MMO =
10474    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10475                            MachineMemOperand::MOStore, 2, 2);
10476
10477   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10478   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10479                                           DAG.getVTList(MVT::Other),
10480                                           Ops, 2, MVT::i16, MMO);
10481
10482   // Load FP Control Word from stack slot
10483   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10484                             MachinePointerInfo(), false, false, false, 0);
10485
10486   // Transform as necessary
10487   SDValue CWD1 =
10488     DAG.getNode(ISD::SRL, DL, MVT::i16,
10489                 DAG.getNode(ISD::AND, DL, MVT::i16,
10490                             CWD, DAG.getConstant(0x800, MVT::i16)),
10491                 DAG.getConstant(11, MVT::i8));
10492   SDValue CWD2 =
10493     DAG.getNode(ISD::SRL, DL, MVT::i16,
10494                 DAG.getNode(ISD::AND, DL, MVT::i16,
10495                             CWD, DAG.getConstant(0x400, MVT::i16)),
10496                 DAG.getConstant(9, MVT::i8));
10497
10498   SDValue RetVal =
10499     DAG.getNode(ISD::AND, DL, MVT::i16,
10500                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10501                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10502                             DAG.getConstant(1, MVT::i16)),
10503                 DAG.getConstant(3, MVT::i16));
10504
10505
10506   return DAG.getNode((VT.getSizeInBits() < 16 ?
10507                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10508 }
10509
10510 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10511   EVT VT = Op.getValueType();
10512   EVT OpVT = VT;
10513   unsigned NumBits = VT.getSizeInBits();
10514   DebugLoc dl = Op.getDebugLoc();
10515
10516   Op = Op.getOperand(0);
10517   if (VT == MVT::i8) {
10518     // Zero extend to i32 since there is not an i8 bsr.
10519     OpVT = MVT::i32;
10520     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10521   }
10522
10523   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10524   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10525   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10526
10527   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10528   SDValue Ops[] = {
10529     Op,
10530     DAG.getConstant(NumBits+NumBits-1, OpVT),
10531     DAG.getConstant(X86::COND_E, MVT::i8),
10532     Op.getValue(1)
10533   };
10534   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10535
10536   // Finally xor with NumBits-1.
10537   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10538
10539   if (VT == MVT::i8)
10540     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10541   return Op;
10542 }
10543
10544 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10545   EVT VT = Op.getValueType();
10546   EVT OpVT = VT;
10547   unsigned NumBits = VT.getSizeInBits();
10548   DebugLoc dl = Op.getDebugLoc();
10549
10550   Op = Op.getOperand(0);
10551   if (VT == MVT::i8) {
10552     // Zero extend to i32 since there is not an i8 bsr.
10553     OpVT = MVT::i32;
10554     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10555   }
10556
10557   // Issue a bsr (scan bits in reverse).
10558   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10559   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10560
10561   // And xor with NumBits-1.
10562   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10563
10564   if (VT == MVT::i8)
10565     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10566   return Op;
10567 }
10568
10569 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10570   EVT VT = Op.getValueType();
10571   unsigned NumBits = VT.getSizeInBits();
10572   DebugLoc dl = Op.getDebugLoc();
10573   Op = Op.getOperand(0);
10574
10575   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10576   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10577   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10578
10579   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10580   SDValue Ops[] = {
10581     Op,
10582     DAG.getConstant(NumBits, VT),
10583     DAG.getConstant(X86::COND_E, MVT::i8),
10584     Op.getValue(1)
10585   };
10586   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10587 }
10588
10589 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10590 // ones, and then concatenate the result back.
10591 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10592   EVT VT = Op.getValueType();
10593
10594   assert(VT.is256BitVector() && VT.isInteger() &&
10595          "Unsupported value type for operation");
10596
10597   unsigned NumElems = VT.getVectorNumElements();
10598   DebugLoc dl = Op.getDebugLoc();
10599
10600   // Extract the LHS vectors
10601   SDValue LHS = Op.getOperand(0);
10602   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10603   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10604
10605   // Extract the RHS vectors
10606   SDValue RHS = Op.getOperand(1);
10607   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10608   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10609
10610   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10611   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10612
10613   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10614                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10615                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10616 }
10617
10618 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10619   assert(Op.getValueType().is256BitVector() &&
10620          Op.getValueType().isInteger() &&
10621          "Only handle AVX 256-bit vector integer operation");
10622   return Lower256IntArith(Op, DAG);
10623 }
10624
10625 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10626   assert(Op.getValueType().is256BitVector() &&
10627          Op.getValueType().isInteger() &&
10628          "Only handle AVX 256-bit vector integer operation");
10629   return Lower256IntArith(Op, DAG);
10630 }
10631
10632 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10633                         SelectionDAG &DAG) {
10634   EVT VT = Op.getValueType();
10635
10636   // Decompose 256-bit ops into smaller 128-bit ops.
10637   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10638     return Lower256IntArith(Op, DAG);
10639
10640   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10641          "Only know how to lower V2I64/V4I64 multiply");
10642
10643   DebugLoc dl = Op.getDebugLoc();
10644
10645   //  Ahi = psrlqi(a, 32);
10646   //  Bhi = psrlqi(b, 32);
10647   //
10648   //  AloBlo = pmuludq(a, b);
10649   //  AloBhi = pmuludq(a, Bhi);
10650   //  AhiBlo = pmuludq(Ahi, b);
10651
10652   //  AloBhi = psllqi(AloBhi, 32);
10653   //  AhiBlo = psllqi(AhiBlo, 32);
10654   //  return AloBlo + AloBhi + AhiBlo;
10655
10656   SDValue A = Op.getOperand(0);
10657   SDValue B = Op.getOperand(1);
10658
10659   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10660
10661   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10662   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10663
10664   // Bit cast to 32-bit vectors for MULUDQ
10665   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10666   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10667   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10668   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10669   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10670
10671   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10672   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10673   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10674
10675   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10676   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10677
10678   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10679   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10680 }
10681
10682 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10683
10684   EVT VT = Op.getValueType();
10685   DebugLoc dl = Op.getDebugLoc();
10686   SDValue R = Op.getOperand(0);
10687   SDValue Amt = Op.getOperand(1);
10688   LLVMContext *Context = DAG.getContext();
10689
10690   if (!Subtarget->hasSSE2())
10691     return SDValue();
10692
10693   // Optimize shl/srl/sra with constant shift amount.
10694   if (isSplatVector(Amt.getNode())) {
10695     SDValue SclrAmt = Amt->getOperand(0);
10696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10697       uint64_t ShiftAmt = C->getZExtValue();
10698
10699       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10700           (Subtarget->hasAVX2() &&
10701            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10702         if (Op.getOpcode() == ISD::SHL)
10703           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10704                              DAG.getConstant(ShiftAmt, MVT::i32));
10705         if (Op.getOpcode() == ISD::SRL)
10706           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10707                              DAG.getConstant(ShiftAmt, MVT::i32));
10708         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10709           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10710                              DAG.getConstant(ShiftAmt, MVT::i32));
10711       }
10712
10713       if (VT == MVT::v16i8) {
10714         if (Op.getOpcode() == ISD::SHL) {
10715           // Make a large shift.
10716           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10717                                     DAG.getConstant(ShiftAmt, MVT::i32));
10718           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10719           // Zero out the rightmost bits.
10720           SmallVector<SDValue, 16> V(16,
10721                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10722                                                      MVT::i8));
10723           return DAG.getNode(ISD::AND, dl, VT, SHL,
10724                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10725         }
10726         if (Op.getOpcode() == ISD::SRL) {
10727           // Make a large shift.
10728           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10729                                     DAG.getConstant(ShiftAmt, MVT::i32));
10730           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10731           // Zero out the leftmost bits.
10732           SmallVector<SDValue, 16> V(16,
10733                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10734                                                      MVT::i8));
10735           return DAG.getNode(ISD::AND, dl, VT, SRL,
10736                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10737         }
10738         if (Op.getOpcode() == ISD::SRA) {
10739           if (ShiftAmt == 7) {
10740             // R s>> 7  ===  R s< 0
10741             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10742             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10743           }
10744
10745           // R s>> a === ((R u>> a) ^ m) - m
10746           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10747           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10748                                                          MVT::i8));
10749           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10750           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10751           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10752           return Res;
10753         }
10754         llvm_unreachable("Unknown shift opcode.");
10755       }
10756
10757       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10758         if (Op.getOpcode() == ISD::SHL) {
10759           // Make a large shift.
10760           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10761                                     DAG.getConstant(ShiftAmt, MVT::i32));
10762           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10763           // Zero out the rightmost bits.
10764           SmallVector<SDValue, 32> V(32,
10765                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10766                                                      MVT::i8));
10767           return DAG.getNode(ISD::AND, dl, VT, SHL,
10768                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10769         }
10770         if (Op.getOpcode() == ISD::SRL) {
10771           // Make a large shift.
10772           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10773                                     DAG.getConstant(ShiftAmt, MVT::i32));
10774           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10775           // Zero out the leftmost bits.
10776           SmallVector<SDValue, 32> V(32,
10777                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10778                                                      MVT::i8));
10779           return DAG.getNode(ISD::AND, dl, VT, SRL,
10780                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10781         }
10782         if (Op.getOpcode() == ISD::SRA) {
10783           if (ShiftAmt == 7) {
10784             // R s>> 7  ===  R s< 0
10785             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10786             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10787           }
10788
10789           // R s>> a === ((R u>> a) ^ m) - m
10790           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10791           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10792                                                          MVT::i8));
10793           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10794           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10795           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10796           return Res;
10797         }
10798         llvm_unreachable("Unknown shift opcode.");
10799       }
10800     }
10801   }
10802
10803   // Lower SHL with variable shift amount.
10804   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10805     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10806                      DAG.getConstant(23, MVT::i32));
10807
10808     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10809     Constant *C = ConstantDataVector::get(*Context, CV);
10810     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10811     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10812                                  MachinePointerInfo::getConstantPool(),
10813                                  false, false, false, 16);
10814
10815     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10816     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10817     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10818     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10819   }
10820   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10821     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10822
10823     // a = a << 5;
10824     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10825                      DAG.getConstant(5, MVT::i32));
10826     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10827
10828     // Turn 'a' into a mask suitable for VSELECT
10829     SDValue VSelM = DAG.getConstant(0x80, VT);
10830     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10831     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10832
10833     SDValue CM1 = DAG.getConstant(0x0f, VT);
10834     SDValue CM2 = DAG.getConstant(0x3f, VT);
10835
10836     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10837     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10838     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10839                             DAG.getConstant(4, MVT::i32), DAG);
10840     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10841     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10842
10843     // a += a
10844     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10845     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10846     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10847
10848     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10849     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10850     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10851                             DAG.getConstant(2, MVT::i32), DAG);
10852     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10853     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10854
10855     // a += a
10856     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10857     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10858     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10859
10860     // return VSELECT(r, r+r, a);
10861     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10862                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10863     return R;
10864   }
10865
10866   // Decompose 256-bit shifts into smaller 128-bit shifts.
10867   if (VT.is256BitVector()) {
10868     unsigned NumElems = VT.getVectorNumElements();
10869     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10870     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10871
10872     // Extract the two vectors
10873     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10874     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10875
10876     // Recreate the shift amount vectors
10877     SDValue Amt1, Amt2;
10878     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10879       // Constant shift amount
10880       SmallVector<SDValue, 4> Amt1Csts;
10881       SmallVector<SDValue, 4> Amt2Csts;
10882       for (unsigned i = 0; i != NumElems/2; ++i)
10883         Amt1Csts.push_back(Amt->getOperand(i));
10884       for (unsigned i = NumElems/2; i != NumElems; ++i)
10885         Amt2Csts.push_back(Amt->getOperand(i));
10886
10887       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10888                                  &Amt1Csts[0], NumElems/2);
10889       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10890                                  &Amt2Csts[0], NumElems/2);
10891     } else {
10892       // Variable shift amount
10893       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10894       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10895     }
10896
10897     // Issue new vector shifts for the smaller types
10898     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10899     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10900
10901     // Concatenate the result back
10902     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10903   }
10904
10905   return SDValue();
10906 }
10907
10908 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
10909   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10910   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10911   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10912   // has only one use.
10913   SDNode *N = Op.getNode();
10914   SDValue LHS = N->getOperand(0);
10915   SDValue RHS = N->getOperand(1);
10916   unsigned BaseOp = 0;
10917   unsigned Cond = 0;
10918   DebugLoc DL = Op.getDebugLoc();
10919   switch (Op.getOpcode()) {
10920   default: llvm_unreachable("Unknown ovf instruction!");
10921   case ISD::SADDO:
10922     // A subtract of one will be selected as a INC. Note that INC doesn't
10923     // set CF, so we can't do this for UADDO.
10924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10925       if (C->isOne()) {
10926         BaseOp = X86ISD::INC;
10927         Cond = X86::COND_O;
10928         break;
10929       }
10930     BaseOp = X86ISD::ADD;
10931     Cond = X86::COND_O;
10932     break;
10933   case ISD::UADDO:
10934     BaseOp = X86ISD::ADD;
10935     Cond = X86::COND_B;
10936     break;
10937   case ISD::SSUBO:
10938     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10939     // set CF, so we can't do this for USUBO.
10940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10941       if (C->isOne()) {
10942         BaseOp = X86ISD::DEC;
10943         Cond = X86::COND_O;
10944         break;
10945       }
10946     BaseOp = X86ISD::SUB;
10947     Cond = X86::COND_O;
10948     break;
10949   case ISD::USUBO:
10950     BaseOp = X86ISD::SUB;
10951     Cond = X86::COND_B;
10952     break;
10953   case ISD::SMULO:
10954     BaseOp = X86ISD::SMUL;
10955     Cond = X86::COND_O;
10956     break;
10957   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10958     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10959                                  MVT::i32);
10960     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10961
10962     SDValue SetCC =
10963       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10964                   DAG.getConstant(X86::COND_O, MVT::i32),
10965                   SDValue(Sum.getNode(), 2));
10966
10967     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10968   }
10969   }
10970
10971   // Also sets EFLAGS.
10972   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10973   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10974
10975   SDValue SetCC =
10976     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10977                 DAG.getConstant(Cond, MVT::i32),
10978                 SDValue(Sum.getNode(), 1));
10979
10980   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10981 }
10982
10983 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10984                                                   SelectionDAG &DAG) const {
10985   DebugLoc dl = Op.getDebugLoc();
10986   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10987   EVT VT = Op.getValueType();
10988
10989   if (!Subtarget->hasSSE2() || !VT.isVector())
10990     return SDValue();
10991
10992   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10993                       ExtraVT.getScalarType().getSizeInBits();
10994   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10995
10996   switch (VT.getSimpleVT().SimpleTy) {
10997     default: return SDValue();
10998     case MVT::v8i32:
10999     case MVT::v16i16:
11000       if (!Subtarget->hasAVX())
11001         return SDValue();
11002       if (!Subtarget->hasAVX2()) {
11003         // needs to be split
11004         unsigned NumElems = VT.getVectorNumElements();
11005
11006         // Extract the LHS vectors
11007         SDValue LHS = Op.getOperand(0);
11008         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11009         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11010
11011         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11012         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11013
11014         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11015         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11016         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11017                                    ExtraNumElems/2);
11018         SDValue Extra = DAG.getValueType(ExtraVT);
11019
11020         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11021         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11022
11023         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11024       }
11025       // fall through
11026     case MVT::v4i32:
11027     case MVT::v8i16: {
11028       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11029                                          Op.getOperand(0), ShAmt, DAG);
11030       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11031     }
11032   }
11033 }
11034
11035
11036 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11037                               SelectionDAG &DAG) {
11038   DebugLoc dl = Op.getDebugLoc();
11039
11040   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11041   // There isn't any reason to disable it if the target processor supports it.
11042   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11043     SDValue Chain = Op.getOperand(0);
11044     SDValue Zero = DAG.getConstant(0, MVT::i32);
11045     SDValue Ops[] = {
11046       DAG.getRegister(X86::ESP, MVT::i32), // Base
11047       DAG.getTargetConstant(1, MVT::i8),   // Scale
11048       DAG.getRegister(0, MVT::i32),        // Index
11049       DAG.getTargetConstant(0, MVT::i32),  // Disp
11050       DAG.getRegister(0, MVT::i32),        // Segment.
11051       Zero,
11052       Chain
11053     };
11054     SDNode *Res =
11055       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11056                           array_lengthof(Ops));
11057     return SDValue(Res, 0);
11058   }
11059
11060   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11061   if (!isDev)
11062     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11063
11064   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11065   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11066   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11067   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11068
11069   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11070   if (!Op1 && !Op2 && !Op3 && Op4)
11071     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11072
11073   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11074   if (Op1 && !Op2 && !Op3 && !Op4)
11075     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11076
11077   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11078   //           (MFENCE)>;
11079   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11080 }
11081
11082 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11083                                  SelectionDAG &DAG) {
11084   DebugLoc dl = Op.getDebugLoc();
11085   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11086     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11087   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11088     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11089
11090   // The only fence that needs an instruction is a sequentially-consistent
11091   // cross-thread fence.
11092   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11093     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11094     // no-sse2). There isn't any reason to disable it if the target processor
11095     // supports it.
11096     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11097       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11098
11099     SDValue Chain = Op.getOperand(0);
11100     SDValue Zero = DAG.getConstant(0, MVT::i32);
11101     SDValue Ops[] = {
11102       DAG.getRegister(X86::ESP, MVT::i32), // Base
11103       DAG.getTargetConstant(1, MVT::i8),   // Scale
11104       DAG.getRegister(0, MVT::i32),        // Index
11105       DAG.getTargetConstant(0, MVT::i32),  // Disp
11106       DAG.getRegister(0, MVT::i32),        // Segment.
11107       Zero,
11108       Chain
11109     };
11110     SDNode *Res =
11111       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11112                          array_lengthof(Ops));
11113     return SDValue(Res, 0);
11114   }
11115
11116   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11117   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11118 }
11119
11120
11121 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11122                              SelectionDAG &DAG) {
11123   EVT T = Op.getValueType();
11124   DebugLoc DL = Op.getDebugLoc();
11125   unsigned Reg = 0;
11126   unsigned size = 0;
11127   switch(T.getSimpleVT().SimpleTy) {
11128   default: llvm_unreachable("Invalid value type!");
11129   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11130   case MVT::i16: Reg = X86::AX;  size = 2; break;
11131   case MVT::i32: Reg = X86::EAX; size = 4; break;
11132   case MVT::i64:
11133     assert(Subtarget->is64Bit() && "Node not type legal!");
11134     Reg = X86::RAX; size = 8;
11135     break;
11136   }
11137   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11138                                     Op.getOperand(2), SDValue());
11139   SDValue Ops[] = { cpIn.getValue(0),
11140                     Op.getOperand(1),
11141                     Op.getOperand(3),
11142                     DAG.getTargetConstant(size, MVT::i8),
11143                     cpIn.getValue(1) };
11144   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11145   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11146   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11147                                            Ops, 5, T, MMO);
11148   SDValue cpOut =
11149     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11150   return cpOut;
11151 }
11152
11153 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11154                                      SelectionDAG &DAG) {
11155   assert(Subtarget->is64Bit() && "Result not type legalized?");
11156   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11157   SDValue TheChain = Op.getOperand(0);
11158   DebugLoc dl = Op.getDebugLoc();
11159   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11160   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11161   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11162                                    rax.getValue(2));
11163   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11164                             DAG.getConstant(32, MVT::i8));
11165   SDValue Ops[] = {
11166     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11167     rdx.getValue(1)
11168   };
11169   return DAG.getMergeValues(Ops, 2, dl);
11170 }
11171
11172 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11173   EVT SrcVT = Op.getOperand(0).getValueType();
11174   EVT DstVT = Op.getValueType();
11175   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11176          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11177   assert((DstVT == MVT::i64 ||
11178           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11179          "Unexpected custom BITCAST");
11180   // i64 <=> MMX conversions are Legal.
11181   if (SrcVT==MVT::i64 && DstVT.isVector())
11182     return Op;
11183   if (DstVT==MVT::i64 && SrcVT.isVector())
11184     return Op;
11185   // MMX <=> MMX conversions are Legal.
11186   if (SrcVT.isVector() && DstVT.isVector())
11187     return Op;
11188   // All other conversions need to be expanded.
11189   return SDValue();
11190 }
11191
11192 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11193   SDNode *Node = Op.getNode();
11194   DebugLoc dl = Node->getDebugLoc();
11195   EVT T = Node->getValueType(0);
11196   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11197                               DAG.getConstant(0, T), Node->getOperand(2));
11198   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11199                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11200                        Node->getOperand(0),
11201                        Node->getOperand(1), negOp,
11202                        cast<AtomicSDNode>(Node)->getSrcValue(),
11203                        cast<AtomicSDNode>(Node)->getAlignment(),
11204                        cast<AtomicSDNode>(Node)->getOrdering(),
11205                        cast<AtomicSDNode>(Node)->getSynchScope());
11206 }
11207
11208 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11209   SDNode *Node = Op.getNode();
11210   DebugLoc dl = Node->getDebugLoc();
11211   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11212
11213   // Convert seq_cst store -> xchg
11214   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11215   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11216   //        (The only way to get a 16-byte store is cmpxchg16b)
11217   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11218   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11219       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11220     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11221                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11222                                  Node->getOperand(0),
11223                                  Node->getOperand(1), Node->getOperand(2),
11224                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11225                                  cast<AtomicSDNode>(Node)->getOrdering(),
11226                                  cast<AtomicSDNode>(Node)->getSynchScope());
11227     return Swap.getValue(1);
11228   }
11229   // Other atomic stores have a simple pattern.
11230   return Op;
11231 }
11232
11233 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11234   EVT VT = Op.getNode()->getValueType(0);
11235
11236   // Let legalize expand this if it isn't a legal type yet.
11237   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11238     return SDValue();
11239
11240   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11241
11242   unsigned Opc;
11243   bool ExtraOp = false;
11244   switch (Op.getOpcode()) {
11245   default: llvm_unreachable("Invalid code");
11246   case ISD::ADDC: Opc = X86ISD::ADD; break;
11247   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11248   case ISD::SUBC: Opc = X86ISD::SUB; break;
11249   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11250   }
11251
11252   if (!ExtraOp)
11253     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11254                        Op.getOperand(1));
11255   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11256                      Op.getOperand(1), Op.getOperand(2));
11257 }
11258
11259 /// LowerOperation - Provide custom lowering hooks for some operations.
11260 ///
11261 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11262   switch (Op.getOpcode()) {
11263   default: llvm_unreachable("Should not custom lower this!");
11264   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11265   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11266   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11267   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11268   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11269   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11270   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11271   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11272   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11273   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11274   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11275   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11276   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11277   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11278   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11279   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11280   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11281   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11282   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11283   case ISD::SHL_PARTS:
11284   case ISD::SRA_PARTS:
11285   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11286   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11287   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11288   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11289   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11290   case ISD::FABS:               return LowerFABS(Op, DAG);
11291   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11292   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11293   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11294   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11295   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11296   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11297   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11298   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11299   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11300   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11301   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11302   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11303   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11304   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11305   case ISD::FRAME_TO_ARGS_OFFSET:
11306                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11307   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11308   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11309   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11310   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11311   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11312   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11313   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11314   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11315   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11316   case ISD::SRA:
11317   case ISD::SRL:
11318   case ISD::SHL:                return LowerShift(Op, DAG);
11319   case ISD::SADDO:
11320   case ISD::UADDO:
11321   case ISD::SSUBO:
11322   case ISD::USUBO:
11323   case ISD::SMULO:
11324   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11325   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11326   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11327   case ISD::ADDC:
11328   case ISD::ADDE:
11329   case ISD::SUBC:
11330   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11331   case ISD::ADD:                return LowerADD(Op, DAG);
11332   case ISD::SUB:                return LowerSUB(Op, DAG);
11333   }
11334 }
11335
11336 static void ReplaceATOMIC_LOAD(SDNode *Node,
11337                                   SmallVectorImpl<SDValue> &Results,
11338                                   SelectionDAG &DAG) {
11339   DebugLoc dl = Node->getDebugLoc();
11340   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11341
11342   // Convert wide load -> cmpxchg8b/cmpxchg16b
11343   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11344   //        (The only way to get a 16-byte load is cmpxchg16b)
11345   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11346   SDValue Zero = DAG.getConstant(0, VT);
11347   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11348                                Node->getOperand(0),
11349                                Node->getOperand(1), Zero, Zero,
11350                                cast<AtomicSDNode>(Node)->getMemOperand(),
11351                                cast<AtomicSDNode>(Node)->getOrdering(),
11352                                cast<AtomicSDNode>(Node)->getSynchScope());
11353   Results.push_back(Swap.getValue(0));
11354   Results.push_back(Swap.getValue(1));
11355 }
11356
11357 static void
11358 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11359                         SelectionDAG &DAG, unsigned NewOp) {
11360   DebugLoc dl = Node->getDebugLoc();
11361   assert (Node->getValueType(0) == MVT::i64 &&
11362           "Only know how to expand i64 atomics");
11363
11364   SDValue Chain = Node->getOperand(0);
11365   SDValue In1 = Node->getOperand(1);
11366   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11367                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11368   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11369                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11370   SDValue Ops[] = { Chain, In1, In2L, In2H };
11371   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11372   SDValue Result =
11373     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11374                             cast<MemSDNode>(Node)->getMemOperand());
11375   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11376   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11377   Results.push_back(Result.getValue(2));
11378 }
11379
11380 /// ReplaceNodeResults - Replace a node with an illegal result type
11381 /// with a new node built out of custom code.
11382 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11383                                            SmallVectorImpl<SDValue>&Results,
11384                                            SelectionDAG &DAG) const {
11385   DebugLoc dl = N->getDebugLoc();
11386   switch (N->getOpcode()) {
11387   default:
11388     llvm_unreachable("Do not know how to custom type legalize this operation!");
11389   case ISD::SIGN_EXTEND_INREG:
11390   case ISD::ADDC:
11391   case ISD::ADDE:
11392   case ISD::SUBC:
11393   case ISD::SUBE:
11394     // We don't want to expand or promote these.
11395     return;
11396   case ISD::FP_TO_SINT:
11397   case ISD::FP_TO_UINT: {
11398     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11399
11400     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11401       return;
11402
11403     std::pair<SDValue,SDValue> Vals =
11404         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11405     SDValue FIST = Vals.first, StackSlot = Vals.second;
11406     if (FIST.getNode() != 0) {
11407       EVT VT = N->getValueType(0);
11408       // Return a load from the stack slot.
11409       if (StackSlot.getNode() != 0)
11410         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11411                                       MachinePointerInfo(),
11412                                       false, false, false, 0));
11413       else
11414         Results.push_back(FIST);
11415     }
11416     return;
11417   }
11418   case ISD::READCYCLECOUNTER: {
11419     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11420     SDValue TheChain = N->getOperand(0);
11421     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11422     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11423                                      rd.getValue(1));
11424     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11425                                      eax.getValue(2));
11426     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11427     SDValue Ops[] = { eax, edx };
11428     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11429     Results.push_back(edx.getValue(1));
11430     return;
11431   }
11432   case ISD::ATOMIC_CMP_SWAP: {
11433     EVT T = N->getValueType(0);
11434     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11435     bool Regs64bit = T == MVT::i128;
11436     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11437     SDValue cpInL, cpInH;
11438     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11439                         DAG.getConstant(0, HalfT));
11440     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11441                         DAG.getConstant(1, HalfT));
11442     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11443                              Regs64bit ? X86::RAX : X86::EAX,
11444                              cpInL, SDValue());
11445     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11446                              Regs64bit ? X86::RDX : X86::EDX,
11447                              cpInH, cpInL.getValue(1));
11448     SDValue swapInL, swapInH;
11449     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11450                           DAG.getConstant(0, HalfT));
11451     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11452                           DAG.getConstant(1, HalfT));
11453     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11454                                Regs64bit ? X86::RBX : X86::EBX,
11455                                swapInL, cpInH.getValue(1));
11456     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11457                                Regs64bit ? X86::RCX : X86::ECX,
11458                                swapInH, swapInL.getValue(1));
11459     SDValue Ops[] = { swapInH.getValue(0),
11460                       N->getOperand(1),
11461                       swapInH.getValue(1) };
11462     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11463     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11464     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11465                                   X86ISD::LCMPXCHG8_DAG;
11466     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11467                                              Ops, 3, T, MMO);
11468     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11469                                         Regs64bit ? X86::RAX : X86::EAX,
11470                                         HalfT, Result.getValue(1));
11471     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11472                                         Regs64bit ? X86::RDX : X86::EDX,
11473                                         HalfT, cpOutL.getValue(2));
11474     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11475     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11476     Results.push_back(cpOutH.getValue(1));
11477     return;
11478   }
11479   case ISD::ATOMIC_LOAD_ADD:
11480   case ISD::ATOMIC_LOAD_AND:
11481   case ISD::ATOMIC_LOAD_NAND:
11482   case ISD::ATOMIC_LOAD_OR:
11483   case ISD::ATOMIC_LOAD_SUB:
11484   case ISD::ATOMIC_LOAD_XOR:
11485   case ISD::ATOMIC_SWAP: {
11486     unsigned Opc;
11487     switch (N->getOpcode()) {
11488     default: llvm_unreachable("Unexpected opcode");
11489     case ISD::ATOMIC_LOAD_ADD:
11490       Opc = X86ISD::ATOMADD64_DAG;
11491       break;
11492     case ISD::ATOMIC_LOAD_AND:
11493       Opc = X86ISD::ATOMAND64_DAG;
11494       break;
11495     case ISD::ATOMIC_LOAD_NAND:
11496       Opc = X86ISD::ATOMNAND64_DAG;
11497       break;
11498     case ISD::ATOMIC_LOAD_OR:
11499       Opc = X86ISD::ATOMOR64_DAG;
11500       break;
11501     case ISD::ATOMIC_LOAD_SUB:
11502       Opc = X86ISD::ATOMSUB64_DAG;
11503       break;
11504     case ISD::ATOMIC_LOAD_XOR:
11505       Opc = X86ISD::ATOMXOR64_DAG;
11506       break;
11507     case ISD::ATOMIC_SWAP:
11508       Opc = X86ISD::ATOMSWAP64_DAG;
11509       break;
11510     }
11511     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11512     return;
11513   }
11514   case ISD::ATOMIC_LOAD:
11515     ReplaceATOMIC_LOAD(N, Results, DAG);
11516   }
11517 }
11518
11519 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11520   switch (Opcode) {
11521   default: return NULL;
11522   case X86ISD::BSF:                return "X86ISD::BSF";
11523   case X86ISD::BSR:                return "X86ISD::BSR";
11524   case X86ISD::SHLD:               return "X86ISD::SHLD";
11525   case X86ISD::SHRD:               return "X86ISD::SHRD";
11526   case X86ISD::FAND:               return "X86ISD::FAND";
11527   case X86ISD::FOR:                return "X86ISD::FOR";
11528   case X86ISD::FXOR:               return "X86ISD::FXOR";
11529   case X86ISD::FSRL:               return "X86ISD::FSRL";
11530   case X86ISD::FILD:               return "X86ISD::FILD";
11531   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11532   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11533   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11534   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11535   case X86ISD::FLD:                return "X86ISD::FLD";
11536   case X86ISD::FST:                return "X86ISD::FST";
11537   case X86ISD::CALL:               return "X86ISD::CALL";
11538   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11539   case X86ISD::BT:                 return "X86ISD::BT";
11540   case X86ISD::CMP:                return "X86ISD::CMP";
11541   case X86ISD::COMI:               return "X86ISD::COMI";
11542   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11543   case X86ISD::SETCC:              return "X86ISD::SETCC";
11544   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11545   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11546   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11547   case X86ISD::CMOV:               return "X86ISD::CMOV";
11548   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11549   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11550   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11551   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11552   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11553   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11554   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11555   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11556   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11557   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11558   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11559   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11560   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11561   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11562   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11563   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11564   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11565   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11566   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11567   case X86ISD::HADD:               return "X86ISD::HADD";
11568   case X86ISD::HSUB:               return "X86ISD::HSUB";
11569   case X86ISD::FHADD:              return "X86ISD::FHADD";
11570   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11571   case X86ISD::FMAX:               return "X86ISD::FMAX";
11572   case X86ISD::FMIN:               return "X86ISD::FMIN";
11573   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11574   case X86ISD::FMINC:              return "X86ISD::FMINC";
11575   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11576   case X86ISD::FRCP:               return "X86ISD::FRCP";
11577   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11578   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11579   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11580   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11581   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11582   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11583   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11584   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11585   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11586   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11587   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11588   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11589   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11590   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11591   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11592   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11593   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11594   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11595   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11596   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11597   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11598   case X86ISD::VSHL:               return "X86ISD::VSHL";
11599   case X86ISD::VSRL:               return "X86ISD::VSRL";
11600   case X86ISD::VSRA:               return "X86ISD::VSRA";
11601   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11602   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11603   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11604   case X86ISD::CMPP:               return "X86ISD::CMPP";
11605   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11606   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11607   case X86ISD::ADD:                return "X86ISD::ADD";
11608   case X86ISD::SUB:                return "X86ISD::SUB";
11609   case X86ISD::ADC:                return "X86ISD::ADC";
11610   case X86ISD::SBB:                return "X86ISD::SBB";
11611   case X86ISD::SMUL:               return "X86ISD::SMUL";
11612   case X86ISD::UMUL:               return "X86ISD::UMUL";
11613   case X86ISD::INC:                return "X86ISD::INC";
11614   case X86ISD::DEC:                return "X86ISD::DEC";
11615   case X86ISD::OR:                 return "X86ISD::OR";
11616   case X86ISD::XOR:                return "X86ISD::XOR";
11617   case X86ISD::AND:                return "X86ISD::AND";
11618   case X86ISD::ANDN:               return "X86ISD::ANDN";
11619   case X86ISD::BLSI:               return "X86ISD::BLSI";
11620   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11621   case X86ISD::BLSR:               return "X86ISD::BLSR";
11622   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11623   case X86ISD::PTEST:              return "X86ISD::PTEST";
11624   case X86ISD::TESTP:              return "X86ISD::TESTP";
11625   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11626   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11627   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11628   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11629   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11630   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11631   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11632   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11633   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11634   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11635   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11636   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11637   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11638   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11639   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11640   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11641   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11642   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11643   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11644   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11645   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11646   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11647   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11648   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11649   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11650   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11651   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11652   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11653   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11654   case X86ISD::SAHF:               return "X86ISD::SAHF";
11655   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11656   case X86ISD::FMADD:              return "X86ISD::FMADD";
11657   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11658   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11659   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11660   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11661   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11662   }
11663 }
11664
11665 // isLegalAddressingMode - Return true if the addressing mode represented
11666 // by AM is legal for this target, for a load/store of the specified type.
11667 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11668                                               Type *Ty) const {
11669   // X86 supports extremely general addressing modes.
11670   CodeModel::Model M = getTargetMachine().getCodeModel();
11671   Reloc::Model R = getTargetMachine().getRelocationModel();
11672
11673   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11674   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11675     return false;
11676
11677   if (AM.BaseGV) {
11678     unsigned GVFlags =
11679       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11680
11681     // If a reference to this global requires an extra load, we can't fold it.
11682     if (isGlobalStubReference(GVFlags))
11683       return false;
11684
11685     // If BaseGV requires a register for the PIC base, we cannot also have a
11686     // BaseReg specified.
11687     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11688       return false;
11689
11690     // If lower 4G is not available, then we must use rip-relative addressing.
11691     if ((M != CodeModel::Small || R != Reloc::Static) &&
11692         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11693       return false;
11694   }
11695
11696   switch (AM.Scale) {
11697   case 0:
11698   case 1:
11699   case 2:
11700   case 4:
11701   case 8:
11702     // These scales always work.
11703     break;
11704   case 3:
11705   case 5:
11706   case 9:
11707     // These scales are formed with basereg+scalereg.  Only accept if there is
11708     // no basereg yet.
11709     if (AM.HasBaseReg)
11710       return false;
11711     break;
11712   default:  // Other stuff never works.
11713     return false;
11714   }
11715
11716   return true;
11717 }
11718
11719
11720 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11721   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11722     return false;
11723   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11724   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11725   if (NumBits1 <= NumBits2)
11726     return false;
11727   return true;
11728 }
11729
11730 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11731   return Imm == (int32_t)Imm;
11732 }
11733
11734 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11735   // Can also use sub to handle negated immediates.
11736   return Imm == (int32_t)Imm;
11737 }
11738
11739 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11740   if (!VT1.isInteger() || !VT2.isInteger())
11741     return false;
11742   unsigned NumBits1 = VT1.getSizeInBits();
11743   unsigned NumBits2 = VT2.getSizeInBits();
11744   if (NumBits1 <= NumBits2)
11745     return false;
11746   return true;
11747 }
11748
11749 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11750   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11751   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11752 }
11753
11754 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11755   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11756   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11757 }
11758
11759 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11760   // i16 instructions are longer (0x66 prefix) and potentially slower.
11761   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11762 }
11763
11764 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11765 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11766 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11767 /// are assumed to be legal.
11768 bool
11769 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11770                                       EVT VT) const {
11771   // Very little shuffling can be done for 64-bit vectors right now.
11772   if (VT.getSizeInBits() == 64)
11773     return false;
11774
11775   // FIXME: pshufb, blends, shifts.
11776   return (VT.getVectorNumElements() == 2 ||
11777           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11778           isMOVLMask(M, VT) ||
11779           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11780           isPSHUFDMask(M, VT) ||
11781           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11782           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11783           isPALIGNRMask(M, VT, Subtarget) ||
11784           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11785           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11786           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11787           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11788 }
11789
11790 bool
11791 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11792                                           EVT VT) const {
11793   unsigned NumElts = VT.getVectorNumElements();
11794   // FIXME: This collection of masks seems suspect.
11795   if (NumElts == 2)
11796     return true;
11797   if (NumElts == 4 && VT.is128BitVector()) {
11798     return (isMOVLMask(Mask, VT)  ||
11799             isCommutedMOVLMask(Mask, VT, true) ||
11800             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11801             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11802   }
11803   return false;
11804 }
11805
11806 //===----------------------------------------------------------------------===//
11807 //                           X86 Scheduler Hooks
11808 //===----------------------------------------------------------------------===//
11809
11810 // private utility function
11811 MachineBasicBlock *
11812 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11813                                                        MachineBasicBlock *MBB,
11814                                                        unsigned regOpc,
11815                                                        unsigned immOpc,
11816                                                        unsigned LoadOpc,
11817                                                        unsigned CXchgOpc,
11818                                                        unsigned notOpc,
11819                                                        unsigned EAXreg,
11820                                                  const TargetRegisterClass *RC,
11821                                                        bool Invert) const {
11822   // For the atomic bitwise operator, we generate
11823   //   thisMBB:
11824   //   newMBB:
11825   //     ld  t1 = [bitinstr.addr]
11826   //     op  t2 = t1, [bitinstr.val]
11827   //     not t3 = t2  (if Invert)
11828   //     mov EAX = t1
11829   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11830   //     bz  newMBB
11831   //     fallthrough -->nextMBB
11832   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11833   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11834   MachineFunction::iterator MBBIter = MBB;
11835   ++MBBIter;
11836
11837   /// First build the CFG
11838   MachineFunction *F = MBB->getParent();
11839   MachineBasicBlock *thisMBB = MBB;
11840   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11841   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11842   F->insert(MBBIter, newMBB);
11843   F->insert(MBBIter, nextMBB);
11844
11845   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11846   nextMBB->splice(nextMBB->begin(), thisMBB,
11847                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11848                   thisMBB->end());
11849   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11850
11851   // Update thisMBB to fall through to newMBB
11852   thisMBB->addSuccessor(newMBB);
11853
11854   // newMBB jumps to itself and fall through to nextMBB
11855   newMBB->addSuccessor(nextMBB);
11856   newMBB->addSuccessor(newMBB);
11857
11858   // Insert instructions into newMBB based on incoming instruction
11859   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11860          "unexpected number of operands");
11861   DebugLoc dl = bInstr->getDebugLoc();
11862   MachineOperand& destOper = bInstr->getOperand(0);
11863   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11864   int numArgs = bInstr->getNumOperands() - 1;
11865   for (int i=0; i < numArgs; ++i)
11866     argOpers[i] = &bInstr->getOperand(i+1);
11867
11868   // x86 address has 4 operands: base, index, scale, and displacement
11869   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11870   int valArgIndx = lastAddrIndx + 1;
11871
11872   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11873   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11874   for (int i=0; i <= lastAddrIndx; ++i)
11875     (*MIB).addOperand(*argOpers[i]);
11876
11877   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11878   assert((argOpers[valArgIndx]->isReg() ||
11879           argOpers[valArgIndx]->isImm()) &&
11880          "invalid operand");
11881   if (argOpers[valArgIndx]->isReg())
11882     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11883   else
11884     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11885   MIB.addReg(t1);
11886   (*MIB).addOperand(*argOpers[valArgIndx]);
11887
11888   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11889   if (Invert) {
11890     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11891   }
11892   else
11893     t3 = t2;
11894
11895   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11896   MIB.addReg(t1);
11897
11898   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11899   for (int i=0; i <= lastAddrIndx; ++i)
11900     (*MIB).addOperand(*argOpers[i]);
11901   MIB.addReg(t3);
11902   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11903   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11904                     bInstr->memoperands_end());
11905
11906   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11907   MIB.addReg(EAXreg);
11908
11909   // insert branch
11910   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11911
11912   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11913   return nextMBB;
11914 }
11915
11916 // private utility function:  64 bit atomics on 32 bit host.
11917 MachineBasicBlock *
11918 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11919                                                        MachineBasicBlock *MBB,
11920                                                        unsigned regOpcL,
11921                                                        unsigned regOpcH,
11922                                                        unsigned immOpcL,
11923                                                        unsigned immOpcH,
11924                                                        bool Invert) const {
11925   // For the atomic bitwise operator, we generate
11926   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11927   //     ld t1,t2 = [bitinstr.addr]
11928   //   newMBB:
11929   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11930   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11931   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11932   //     neg t7, t8 < t5, t6  (if Invert)
11933   //     mov ECX, EBX <- t5, t6
11934   //     mov EAX, EDX <- t1, t2
11935   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11936   //     mov t3, t4 <- EAX, EDX
11937   //     bz  newMBB
11938   //     result in out1, out2
11939   //     fallthrough -->nextMBB
11940
11941   const TargetRegisterClass *RC = &X86::GR32RegClass;
11942   const unsigned LoadOpc = X86::MOV32rm;
11943   const unsigned NotOpc = X86::NOT32r;
11944   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11945   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11946   MachineFunction::iterator MBBIter = MBB;
11947   ++MBBIter;
11948
11949   /// First build the CFG
11950   MachineFunction *F = MBB->getParent();
11951   MachineBasicBlock *thisMBB = MBB;
11952   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11953   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11954   F->insert(MBBIter, newMBB);
11955   F->insert(MBBIter, nextMBB);
11956
11957   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11958   nextMBB->splice(nextMBB->begin(), thisMBB,
11959                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11960                   thisMBB->end());
11961   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11962
11963   // Update thisMBB to fall through to newMBB
11964   thisMBB->addSuccessor(newMBB);
11965
11966   // newMBB jumps to itself and fall through to nextMBB
11967   newMBB->addSuccessor(nextMBB);
11968   newMBB->addSuccessor(newMBB);
11969
11970   DebugLoc dl = bInstr->getDebugLoc();
11971   // Insert instructions into newMBB based on incoming instruction
11972   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11973   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11974          "unexpected number of operands");
11975   MachineOperand& dest1Oper = bInstr->getOperand(0);
11976   MachineOperand& dest2Oper = bInstr->getOperand(1);
11977   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11978   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11979     argOpers[i] = &bInstr->getOperand(i+2);
11980
11981     // We use some of the operands multiple times, so conservatively just
11982     // clear any kill flags that might be present.
11983     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11984       argOpers[i]->setIsKill(false);
11985   }
11986
11987   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11988   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11989
11990   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11991   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11992   for (int i=0; i <= lastAddrIndx; ++i)
11993     (*MIB).addOperand(*argOpers[i]);
11994   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11995   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11996   // add 4 to displacement.
11997   for (int i=0; i <= lastAddrIndx-2; ++i)
11998     (*MIB).addOperand(*argOpers[i]);
11999   MachineOperand newOp3 = *(argOpers[3]);
12000   if (newOp3.isImm())
12001     newOp3.setImm(newOp3.getImm()+4);
12002   else
12003     newOp3.setOffset(newOp3.getOffset()+4);
12004   (*MIB).addOperand(newOp3);
12005   (*MIB).addOperand(*argOpers[lastAddrIndx]);
12006
12007   // t3/4 are defined later, at the bottom of the loop
12008   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
12009   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
12010   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
12011     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
12012   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
12013     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
12014
12015   // The subsequent operations should be using the destination registers of
12016   // the PHI instructions.
12017   t1 = dest1Oper.getReg();
12018   t2 = dest2Oper.getReg();
12019
12020   int valArgIndx = lastAddrIndx + 1;
12021   assert((argOpers[valArgIndx]->isReg() ||
12022           argOpers[valArgIndx]->isImm()) &&
12023          "invalid operand");
12024   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12025   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12026   if (argOpers[valArgIndx]->isReg())
12027     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12028   else
12029     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12030   if (regOpcL != X86::MOV32rr)
12031     MIB.addReg(t1);
12032   (*MIB).addOperand(*argOpers[valArgIndx]);
12033   assert(argOpers[valArgIndx + 1]->isReg() ==
12034          argOpers[valArgIndx]->isReg());
12035   assert(argOpers[valArgIndx + 1]->isImm() ==
12036          argOpers[valArgIndx]->isImm());
12037   if (argOpers[valArgIndx + 1]->isReg())
12038     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12039   else
12040     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12041   if (regOpcH != X86::MOV32rr)
12042     MIB.addReg(t2);
12043   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12044
12045   unsigned t7, t8;
12046   if (Invert) {
12047     t7 = F->getRegInfo().createVirtualRegister(RC);
12048     t8 = F->getRegInfo().createVirtualRegister(RC);
12049     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12050     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12051   } else {
12052     t7 = t5;
12053     t8 = t6;
12054   }
12055
12056   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12057   MIB.addReg(t1);
12058   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12059   MIB.addReg(t2);
12060
12061   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12062   MIB.addReg(t7);
12063   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12064   MIB.addReg(t8);
12065
12066   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12067   for (int i=0; i <= lastAddrIndx; ++i)
12068     (*MIB).addOperand(*argOpers[i]);
12069
12070   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12071   (*MIB).setMemRefs(bInstr->memoperands_begin(),
12072                     bInstr->memoperands_end());
12073
12074   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12075   MIB.addReg(X86::EAX);
12076   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12077   MIB.addReg(X86::EDX);
12078
12079   // insert branch
12080   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12081
12082   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12083   return nextMBB;
12084 }
12085
12086 // private utility function
12087 MachineBasicBlock *
12088 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12089                                                       MachineBasicBlock *MBB,
12090                                                       unsigned cmovOpc) const {
12091   // For the atomic min/max operator, we generate
12092   //   thisMBB:
12093   //   newMBB:
12094   //     ld t1 = [min/max.addr]
12095   //     mov t2 = [min/max.val]
12096   //     cmp  t1, t2
12097   //     cmov[cond] t2 = t1
12098   //     mov EAX = t1
12099   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12100   //     bz   newMBB
12101   //     fallthrough -->nextMBB
12102   //
12103   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12104   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12105   MachineFunction::iterator MBBIter = MBB;
12106   ++MBBIter;
12107
12108   /// First build the CFG
12109   MachineFunction *F = MBB->getParent();
12110   MachineBasicBlock *thisMBB = MBB;
12111   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12112   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12113   F->insert(MBBIter, newMBB);
12114   F->insert(MBBIter, nextMBB);
12115
12116   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12117   nextMBB->splice(nextMBB->begin(), thisMBB,
12118                   llvm::next(MachineBasicBlock::iterator(mInstr)),
12119                   thisMBB->end());
12120   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12121
12122   // Update thisMBB to fall through to newMBB
12123   thisMBB->addSuccessor(newMBB);
12124
12125   // newMBB jumps to newMBB and fall through to nextMBB
12126   newMBB->addSuccessor(nextMBB);
12127   newMBB->addSuccessor(newMBB);
12128
12129   DebugLoc dl = mInstr->getDebugLoc();
12130   // Insert instructions into newMBB based on incoming instruction
12131   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12132          "unexpected number of operands");
12133   MachineOperand& destOper = mInstr->getOperand(0);
12134   MachineOperand* argOpers[2 + X86::AddrNumOperands];
12135   int numArgs = mInstr->getNumOperands() - 1;
12136   for (int i=0; i < numArgs; ++i)
12137     argOpers[i] = &mInstr->getOperand(i+1);
12138
12139   // x86 address has 4 operands: base, index, scale, and displacement
12140   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12141   int valArgIndx = lastAddrIndx + 1;
12142
12143   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12144   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12145   for (int i=0; i <= lastAddrIndx; ++i)
12146     (*MIB).addOperand(*argOpers[i]);
12147
12148   // We only support register and immediate values
12149   assert((argOpers[valArgIndx]->isReg() ||
12150           argOpers[valArgIndx]->isImm()) &&
12151          "invalid operand");
12152
12153   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12154   if (argOpers[valArgIndx]->isReg())
12155     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12156   else
12157     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12158   (*MIB).addOperand(*argOpers[valArgIndx]);
12159
12160   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12161   MIB.addReg(t1);
12162
12163   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12164   MIB.addReg(t1);
12165   MIB.addReg(t2);
12166
12167   // Generate movc
12168   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12169   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12170   MIB.addReg(t2);
12171   MIB.addReg(t1);
12172
12173   // Cmp and exchange if none has modified the memory location
12174   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12175   for (int i=0; i <= lastAddrIndx; ++i)
12176     (*MIB).addOperand(*argOpers[i]);
12177   MIB.addReg(t3);
12178   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12179   (*MIB).setMemRefs(mInstr->memoperands_begin(),
12180                     mInstr->memoperands_end());
12181
12182   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12183   MIB.addReg(X86::EAX);
12184
12185   // insert branch
12186   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12187
12188   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12189   return nextMBB;
12190 }
12191
12192 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12193 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12194 // in the .td file.
12195 MachineBasicBlock *
12196 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12197                             unsigned numArgs, bool memArg) const {
12198   assert(Subtarget->hasSSE42() &&
12199          "Target must have SSE4.2 or AVX features enabled");
12200
12201   DebugLoc dl = MI->getDebugLoc();
12202   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12203   unsigned Opc;
12204   if (!Subtarget->hasAVX()) {
12205     if (memArg)
12206       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12207     else
12208       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12209   } else {
12210     if (memArg)
12211       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12212     else
12213       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12214   }
12215
12216   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12217   for (unsigned i = 0; i < numArgs; ++i) {
12218     MachineOperand &Op = MI->getOperand(i+1);
12219     if (!(Op.isReg() && Op.isImplicit()))
12220       MIB.addOperand(Op);
12221   }
12222   BuildMI(*BB, MI, dl,
12223     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12224     .addReg(X86::XMM0);
12225
12226   MI->eraseFromParent();
12227   return BB;
12228 }
12229
12230 MachineBasicBlock *
12231 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12232   DebugLoc dl = MI->getDebugLoc();
12233   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12234
12235   // Address into RAX/EAX, other two args into ECX, EDX.
12236   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12237   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12238   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12239   for (int i = 0; i < X86::AddrNumOperands; ++i)
12240     MIB.addOperand(MI->getOperand(i));
12241
12242   unsigned ValOps = X86::AddrNumOperands;
12243   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12244     .addReg(MI->getOperand(ValOps).getReg());
12245   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12246     .addReg(MI->getOperand(ValOps+1).getReg());
12247
12248   // The instruction doesn't actually take any operands though.
12249   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12250
12251   MI->eraseFromParent(); // The pseudo is gone now.
12252   return BB;
12253 }
12254
12255 MachineBasicBlock *
12256 X86TargetLowering::EmitVAARG64WithCustomInserter(
12257                    MachineInstr *MI,
12258                    MachineBasicBlock *MBB) const {
12259   // Emit va_arg instruction on X86-64.
12260
12261   // Operands to this pseudo-instruction:
12262   // 0  ) Output        : destination address (reg)
12263   // 1-5) Input         : va_list address (addr, i64mem)
12264   // 6  ) ArgSize       : Size (in bytes) of vararg type
12265   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12266   // 8  ) Align         : Alignment of type
12267   // 9  ) EFLAGS (implicit-def)
12268
12269   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12270   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12271
12272   unsigned DestReg = MI->getOperand(0).getReg();
12273   MachineOperand &Base = MI->getOperand(1);
12274   MachineOperand &Scale = MI->getOperand(2);
12275   MachineOperand &Index = MI->getOperand(3);
12276   MachineOperand &Disp = MI->getOperand(4);
12277   MachineOperand &Segment = MI->getOperand(5);
12278   unsigned ArgSize = MI->getOperand(6).getImm();
12279   unsigned ArgMode = MI->getOperand(7).getImm();
12280   unsigned Align = MI->getOperand(8).getImm();
12281
12282   // Memory Reference
12283   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12284   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12285   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12286
12287   // Machine Information
12288   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12289   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12290   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12291   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12292   DebugLoc DL = MI->getDebugLoc();
12293
12294   // struct va_list {
12295   //   i32   gp_offset
12296   //   i32   fp_offset
12297   //   i64   overflow_area (address)
12298   //   i64   reg_save_area (address)
12299   // }
12300   // sizeof(va_list) = 24
12301   // alignment(va_list) = 8
12302
12303   unsigned TotalNumIntRegs = 6;
12304   unsigned TotalNumXMMRegs = 8;
12305   bool UseGPOffset = (ArgMode == 1);
12306   bool UseFPOffset = (ArgMode == 2);
12307   unsigned MaxOffset = TotalNumIntRegs * 8 +
12308                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12309
12310   /* Align ArgSize to a multiple of 8 */
12311   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12312   bool NeedsAlign = (Align > 8);
12313
12314   MachineBasicBlock *thisMBB = MBB;
12315   MachineBasicBlock *overflowMBB;
12316   MachineBasicBlock *offsetMBB;
12317   MachineBasicBlock *endMBB;
12318
12319   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12320   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12321   unsigned OffsetReg = 0;
12322
12323   if (!UseGPOffset && !UseFPOffset) {
12324     // If we only pull from the overflow region, we don't create a branch.
12325     // We don't need to alter control flow.
12326     OffsetDestReg = 0; // unused
12327     OverflowDestReg = DestReg;
12328
12329     offsetMBB = NULL;
12330     overflowMBB = thisMBB;
12331     endMBB = thisMBB;
12332   } else {
12333     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12334     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12335     // If not, pull from overflow_area. (branch to overflowMBB)
12336     //
12337     //       thisMBB
12338     //         |     .
12339     //         |        .
12340     //     offsetMBB   overflowMBB
12341     //         |        .
12342     //         |     .
12343     //        endMBB
12344
12345     // Registers for the PHI in endMBB
12346     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12347     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12348
12349     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12350     MachineFunction *MF = MBB->getParent();
12351     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12352     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12353     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12354
12355     MachineFunction::iterator MBBIter = MBB;
12356     ++MBBIter;
12357
12358     // Insert the new basic blocks
12359     MF->insert(MBBIter, offsetMBB);
12360     MF->insert(MBBIter, overflowMBB);
12361     MF->insert(MBBIter, endMBB);
12362
12363     // Transfer the remainder of MBB and its successor edges to endMBB.
12364     endMBB->splice(endMBB->begin(), thisMBB,
12365                     llvm::next(MachineBasicBlock::iterator(MI)),
12366                     thisMBB->end());
12367     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12368
12369     // Make offsetMBB and overflowMBB successors of thisMBB
12370     thisMBB->addSuccessor(offsetMBB);
12371     thisMBB->addSuccessor(overflowMBB);
12372
12373     // endMBB is a successor of both offsetMBB and overflowMBB
12374     offsetMBB->addSuccessor(endMBB);
12375     overflowMBB->addSuccessor(endMBB);
12376
12377     // Load the offset value into a register
12378     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12379     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12380       .addOperand(Base)
12381       .addOperand(Scale)
12382       .addOperand(Index)
12383       .addDisp(Disp, UseFPOffset ? 4 : 0)
12384       .addOperand(Segment)
12385       .setMemRefs(MMOBegin, MMOEnd);
12386
12387     // Check if there is enough room left to pull this argument.
12388     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12389       .addReg(OffsetReg)
12390       .addImm(MaxOffset + 8 - ArgSizeA8);
12391
12392     // Branch to "overflowMBB" if offset >= max
12393     // Fall through to "offsetMBB" otherwise
12394     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12395       .addMBB(overflowMBB);
12396   }
12397
12398   // In offsetMBB, emit code to use the reg_save_area.
12399   if (offsetMBB) {
12400     assert(OffsetReg != 0);
12401
12402     // Read the reg_save_area address.
12403     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12404     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12405       .addOperand(Base)
12406       .addOperand(Scale)
12407       .addOperand(Index)
12408       .addDisp(Disp, 16)
12409       .addOperand(Segment)
12410       .setMemRefs(MMOBegin, MMOEnd);
12411
12412     // Zero-extend the offset
12413     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12414       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12415         .addImm(0)
12416         .addReg(OffsetReg)
12417         .addImm(X86::sub_32bit);
12418
12419     // Add the offset to the reg_save_area to get the final address.
12420     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12421       .addReg(OffsetReg64)
12422       .addReg(RegSaveReg);
12423
12424     // Compute the offset for the next argument
12425     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12426     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12427       .addReg(OffsetReg)
12428       .addImm(UseFPOffset ? 16 : 8);
12429
12430     // Store it back into the va_list.
12431     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12432       .addOperand(Base)
12433       .addOperand(Scale)
12434       .addOperand(Index)
12435       .addDisp(Disp, UseFPOffset ? 4 : 0)
12436       .addOperand(Segment)
12437       .addReg(NextOffsetReg)
12438       .setMemRefs(MMOBegin, MMOEnd);
12439
12440     // Jump to endMBB
12441     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12442       .addMBB(endMBB);
12443   }
12444
12445   //
12446   // Emit code to use overflow area
12447   //
12448
12449   // Load the overflow_area address into a register.
12450   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12451   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12452     .addOperand(Base)
12453     .addOperand(Scale)
12454     .addOperand(Index)
12455     .addDisp(Disp, 8)
12456     .addOperand(Segment)
12457     .setMemRefs(MMOBegin, MMOEnd);
12458
12459   // If we need to align it, do so. Otherwise, just copy the address
12460   // to OverflowDestReg.
12461   if (NeedsAlign) {
12462     // Align the overflow address
12463     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12464     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12465
12466     // aligned_addr = (addr + (align-1)) & ~(align-1)
12467     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12468       .addReg(OverflowAddrReg)
12469       .addImm(Align-1);
12470
12471     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12472       .addReg(TmpReg)
12473       .addImm(~(uint64_t)(Align-1));
12474   } else {
12475     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12476       .addReg(OverflowAddrReg);
12477   }
12478
12479   // Compute the next overflow address after this argument.
12480   // (the overflow address should be kept 8-byte aligned)
12481   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12482   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12483     .addReg(OverflowDestReg)
12484     .addImm(ArgSizeA8);
12485
12486   // Store the new overflow address.
12487   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12488     .addOperand(Base)
12489     .addOperand(Scale)
12490     .addOperand(Index)
12491     .addDisp(Disp, 8)
12492     .addOperand(Segment)
12493     .addReg(NextAddrReg)
12494     .setMemRefs(MMOBegin, MMOEnd);
12495
12496   // If we branched, emit the PHI to the front of endMBB.
12497   if (offsetMBB) {
12498     BuildMI(*endMBB, endMBB->begin(), DL,
12499             TII->get(X86::PHI), DestReg)
12500       .addReg(OffsetDestReg).addMBB(offsetMBB)
12501       .addReg(OverflowDestReg).addMBB(overflowMBB);
12502   }
12503
12504   // Erase the pseudo instruction
12505   MI->eraseFromParent();
12506
12507   return endMBB;
12508 }
12509
12510 MachineBasicBlock *
12511 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12512                                                  MachineInstr *MI,
12513                                                  MachineBasicBlock *MBB) const {
12514   // Emit code to save XMM registers to the stack. The ABI says that the
12515   // number of registers to save is given in %al, so it's theoretically
12516   // possible to do an indirect jump trick to avoid saving all of them,
12517   // however this code takes a simpler approach and just executes all
12518   // of the stores if %al is non-zero. It's less code, and it's probably
12519   // easier on the hardware branch predictor, and stores aren't all that
12520   // expensive anyway.
12521
12522   // Create the new basic blocks. One block contains all the XMM stores,
12523   // and one block is the final destination regardless of whether any
12524   // stores were performed.
12525   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12526   MachineFunction *F = MBB->getParent();
12527   MachineFunction::iterator MBBIter = MBB;
12528   ++MBBIter;
12529   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12530   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12531   F->insert(MBBIter, XMMSaveMBB);
12532   F->insert(MBBIter, EndMBB);
12533
12534   // Transfer the remainder of MBB and its successor edges to EndMBB.
12535   EndMBB->splice(EndMBB->begin(), MBB,
12536                  llvm::next(MachineBasicBlock::iterator(MI)),
12537                  MBB->end());
12538   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12539
12540   // The original block will now fall through to the XMM save block.
12541   MBB->addSuccessor(XMMSaveMBB);
12542   // The XMMSaveMBB will fall through to the end block.
12543   XMMSaveMBB->addSuccessor(EndMBB);
12544
12545   // Now add the instructions.
12546   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12547   DebugLoc DL = MI->getDebugLoc();
12548
12549   unsigned CountReg = MI->getOperand(0).getReg();
12550   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12551   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12552
12553   if (!Subtarget->isTargetWin64()) {
12554     // If %al is 0, branch around the XMM save block.
12555     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12556     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12557     MBB->addSuccessor(EndMBB);
12558   }
12559
12560   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12561   // In the XMM save block, save all the XMM argument registers.
12562   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12563     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12564     MachineMemOperand *MMO =
12565       F->getMachineMemOperand(
12566           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12567         MachineMemOperand::MOStore,
12568         /*Size=*/16, /*Align=*/16);
12569     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12570       .addFrameIndex(RegSaveFrameIndex)
12571       .addImm(/*Scale=*/1)
12572       .addReg(/*IndexReg=*/0)
12573       .addImm(/*Disp=*/Offset)
12574       .addReg(/*Segment=*/0)
12575       .addReg(MI->getOperand(i).getReg())
12576       .addMemOperand(MMO);
12577   }
12578
12579   MI->eraseFromParent();   // The pseudo instruction is gone now.
12580
12581   return EndMBB;
12582 }
12583
12584 // The EFLAGS operand of SelectItr might be missing a kill marker
12585 // because there were multiple uses of EFLAGS, and ISel didn't know
12586 // which to mark. Figure out whether SelectItr should have had a
12587 // kill marker, and set it if it should. Returns the correct kill
12588 // marker value.
12589 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12590                                      MachineBasicBlock* BB,
12591                                      const TargetRegisterInfo* TRI) {
12592   // Scan forward through BB for a use/def of EFLAGS.
12593   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12594   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12595     const MachineInstr& mi = *miI;
12596     if (mi.readsRegister(X86::EFLAGS))
12597       return false;
12598     if (mi.definesRegister(X86::EFLAGS))
12599       break; // Should have kill-flag - update below.
12600   }
12601
12602   // If we hit the end of the block, check whether EFLAGS is live into a
12603   // successor.
12604   if (miI == BB->end()) {
12605     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12606                                           sEnd = BB->succ_end();
12607          sItr != sEnd; ++sItr) {
12608       MachineBasicBlock* succ = *sItr;
12609       if (succ->isLiveIn(X86::EFLAGS))
12610         return false;
12611     }
12612   }
12613
12614   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12615   // out. SelectMI should have a kill flag on EFLAGS.
12616   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12617   return true;
12618 }
12619
12620 MachineBasicBlock *
12621 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12622                                      MachineBasicBlock *BB) const {
12623   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12624   DebugLoc DL = MI->getDebugLoc();
12625
12626   // To "insert" a SELECT_CC instruction, we actually have to insert the
12627   // diamond control-flow pattern.  The incoming instruction knows the
12628   // destination vreg to set, the condition code register to branch on, the
12629   // true/false values to select between, and a branch opcode to use.
12630   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12631   MachineFunction::iterator It = BB;
12632   ++It;
12633
12634   //  thisMBB:
12635   //  ...
12636   //   TrueVal = ...
12637   //   cmpTY ccX, r1, r2
12638   //   bCC copy1MBB
12639   //   fallthrough --> copy0MBB
12640   MachineBasicBlock *thisMBB = BB;
12641   MachineFunction *F = BB->getParent();
12642   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12643   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12644   F->insert(It, copy0MBB);
12645   F->insert(It, sinkMBB);
12646
12647   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12648   // live into the sink and copy blocks.
12649   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12650   if (!MI->killsRegister(X86::EFLAGS) &&
12651       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12652     copy0MBB->addLiveIn(X86::EFLAGS);
12653     sinkMBB->addLiveIn(X86::EFLAGS);
12654   }
12655
12656   // Transfer the remainder of BB and its successor edges to sinkMBB.
12657   sinkMBB->splice(sinkMBB->begin(), BB,
12658                   llvm::next(MachineBasicBlock::iterator(MI)),
12659                   BB->end());
12660   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12661
12662   // Add the true and fallthrough blocks as its successors.
12663   BB->addSuccessor(copy0MBB);
12664   BB->addSuccessor(sinkMBB);
12665
12666   // Create the conditional branch instruction.
12667   unsigned Opc =
12668     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12669   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12670
12671   //  copy0MBB:
12672   //   %FalseValue = ...
12673   //   # fallthrough to sinkMBB
12674   copy0MBB->addSuccessor(sinkMBB);
12675
12676   //  sinkMBB:
12677   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12678   //  ...
12679   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12680           TII->get(X86::PHI), MI->getOperand(0).getReg())
12681     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12682     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12683
12684   MI->eraseFromParent();   // The pseudo instruction is gone now.
12685   return sinkMBB;
12686 }
12687
12688 MachineBasicBlock *
12689 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12690                                         bool Is64Bit) const {
12691   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12692   DebugLoc DL = MI->getDebugLoc();
12693   MachineFunction *MF = BB->getParent();
12694   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12695
12696   assert(getTargetMachine().Options.EnableSegmentedStacks);
12697
12698   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12699   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12700
12701   // BB:
12702   //  ... [Till the alloca]
12703   // If stacklet is not large enough, jump to mallocMBB
12704   //
12705   // bumpMBB:
12706   //  Allocate by subtracting from RSP
12707   //  Jump to continueMBB
12708   //
12709   // mallocMBB:
12710   //  Allocate by call to runtime
12711   //
12712   // continueMBB:
12713   //  ...
12714   //  [rest of original BB]
12715   //
12716
12717   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12718   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12719   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12720
12721   MachineRegisterInfo &MRI = MF->getRegInfo();
12722   const TargetRegisterClass *AddrRegClass =
12723     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12724
12725   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12726     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12727     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12728     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12729     sizeVReg = MI->getOperand(1).getReg(),
12730     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12731
12732   MachineFunction::iterator MBBIter = BB;
12733   ++MBBIter;
12734
12735   MF->insert(MBBIter, bumpMBB);
12736   MF->insert(MBBIter, mallocMBB);
12737   MF->insert(MBBIter, continueMBB);
12738
12739   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12740                       (MachineBasicBlock::iterator(MI)), BB->end());
12741   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12742
12743   // Add code to the main basic block to check if the stack limit has been hit,
12744   // and if so, jump to mallocMBB otherwise to bumpMBB.
12745   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12746   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12747     .addReg(tmpSPVReg).addReg(sizeVReg);
12748   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12749     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12750     .addReg(SPLimitVReg);
12751   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12752
12753   // bumpMBB simply decreases the stack pointer, since we know the current
12754   // stacklet has enough space.
12755   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12756     .addReg(SPLimitVReg);
12757   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12758     .addReg(SPLimitVReg);
12759   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12760
12761   // Calls into a routine in libgcc to allocate more space from the heap.
12762   const uint32_t *RegMask =
12763     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12764   if (Is64Bit) {
12765     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12766       .addReg(sizeVReg);
12767     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12768       .addExternalSymbol("__morestack_allocate_stack_space")
12769       .addRegMask(RegMask)
12770       .addReg(X86::RDI, RegState::Implicit)
12771       .addReg(X86::RAX, RegState::ImplicitDefine);
12772   } else {
12773     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12774       .addImm(12);
12775     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12776     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12777       .addExternalSymbol("__morestack_allocate_stack_space")
12778       .addRegMask(RegMask)
12779       .addReg(X86::EAX, RegState::ImplicitDefine);
12780   }
12781
12782   if (!Is64Bit)
12783     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12784       .addImm(16);
12785
12786   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12787     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12788   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12789
12790   // Set up the CFG correctly.
12791   BB->addSuccessor(bumpMBB);
12792   BB->addSuccessor(mallocMBB);
12793   mallocMBB->addSuccessor(continueMBB);
12794   bumpMBB->addSuccessor(continueMBB);
12795
12796   // Take care of the PHI nodes.
12797   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12798           MI->getOperand(0).getReg())
12799     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12800     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12801
12802   // Delete the original pseudo instruction.
12803   MI->eraseFromParent();
12804
12805   // And we're done.
12806   return continueMBB;
12807 }
12808
12809 MachineBasicBlock *
12810 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12811                                           MachineBasicBlock *BB) const {
12812   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12813   DebugLoc DL = MI->getDebugLoc();
12814
12815   assert(!Subtarget->isTargetEnvMacho());
12816
12817   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12818   // non-trivial part is impdef of ESP.
12819
12820   if (Subtarget->isTargetWin64()) {
12821     if (Subtarget->isTargetCygMing()) {
12822       // ___chkstk(Mingw64):
12823       // Clobbers R10, R11, RAX and EFLAGS.
12824       // Updates RSP.
12825       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12826         .addExternalSymbol("___chkstk")
12827         .addReg(X86::RAX, RegState::Implicit)
12828         .addReg(X86::RSP, RegState::Implicit)
12829         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12830         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12831         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12832     } else {
12833       // __chkstk(MSVCRT): does not update stack pointer.
12834       // Clobbers R10, R11 and EFLAGS.
12835       // FIXME: RAX(allocated size) might be reused and not killed.
12836       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12837         .addExternalSymbol("__chkstk")
12838         .addReg(X86::RAX, RegState::Implicit)
12839         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12840       // RAX has the offset to subtracted from RSP.
12841       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12842         .addReg(X86::RSP)
12843         .addReg(X86::RAX);
12844     }
12845   } else {
12846     const char *StackProbeSymbol =
12847       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12848
12849     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12850       .addExternalSymbol(StackProbeSymbol)
12851       .addReg(X86::EAX, RegState::Implicit)
12852       .addReg(X86::ESP, RegState::Implicit)
12853       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12854       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12855       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12856   }
12857
12858   MI->eraseFromParent();   // The pseudo instruction is gone now.
12859   return BB;
12860 }
12861
12862 MachineBasicBlock *
12863 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12864                                       MachineBasicBlock *BB) const {
12865   // This is pretty easy.  We're taking the value that we received from
12866   // our load from the relocation, sticking it in either RDI (x86-64)
12867   // or EAX and doing an indirect call.  The return value will then
12868   // be in the normal return register.
12869   const X86InstrInfo *TII
12870     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12871   DebugLoc DL = MI->getDebugLoc();
12872   MachineFunction *F = BB->getParent();
12873
12874   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12875   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12876
12877   // Get a register mask for the lowered call.
12878   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12879   // proper register mask.
12880   const uint32_t *RegMask =
12881     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12882   if (Subtarget->is64Bit()) {
12883     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12884                                       TII->get(X86::MOV64rm), X86::RDI)
12885     .addReg(X86::RIP)
12886     .addImm(0).addReg(0)
12887     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12888                       MI->getOperand(3).getTargetFlags())
12889     .addReg(0);
12890     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12891     addDirectMem(MIB, X86::RDI);
12892     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12893   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12894     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12895                                       TII->get(X86::MOV32rm), X86::EAX)
12896     .addReg(0)
12897     .addImm(0).addReg(0)
12898     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12899                       MI->getOperand(3).getTargetFlags())
12900     .addReg(0);
12901     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12902     addDirectMem(MIB, X86::EAX);
12903     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12904   } else {
12905     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12906                                       TII->get(X86::MOV32rm), X86::EAX)
12907     .addReg(TII->getGlobalBaseReg(F))
12908     .addImm(0).addReg(0)
12909     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12910                       MI->getOperand(3).getTargetFlags())
12911     .addReg(0);
12912     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12913     addDirectMem(MIB, X86::EAX);
12914     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12915   }
12916
12917   MI->eraseFromParent(); // The pseudo instruction is gone now.
12918   return BB;
12919 }
12920
12921 MachineBasicBlock *
12922 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12923                                                MachineBasicBlock *BB) const {
12924   switch (MI->getOpcode()) {
12925   default: llvm_unreachable("Unexpected instr type to insert");
12926   case X86::TAILJMPd64:
12927   case X86::TAILJMPr64:
12928   case X86::TAILJMPm64:
12929     llvm_unreachable("TAILJMP64 would not be touched here.");
12930   case X86::TCRETURNdi64:
12931   case X86::TCRETURNri64:
12932   case X86::TCRETURNmi64:
12933     return BB;
12934   case X86::WIN_ALLOCA:
12935     return EmitLoweredWinAlloca(MI, BB);
12936   case X86::SEG_ALLOCA_32:
12937     return EmitLoweredSegAlloca(MI, BB, false);
12938   case X86::SEG_ALLOCA_64:
12939     return EmitLoweredSegAlloca(MI, BB, true);
12940   case X86::TLSCall_32:
12941   case X86::TLSCall_64:
12942     return EmitLoweredTLSCall(MI, BB);
12943   case X86::CMOV_GR8:
12944   case X86::CMOV_FR32:
12945   case X86::CMOV_FR64:
12946   case X86::CMOV_V4F32:
12947   case X86::CMOV_V2F64:
12948   case X86::CMOV_V2I64:
12949   case X86::CMOV_V8F32:
12950   case X86::CMOV_V4F64:
12951   case X86::CMOV_V4I64:
12952   case X86::CMOV_GR16:
12953   case X86::CMOV_GR32:
12954   case X86::CMOV_RFP32:
12955   case X86::CMOV_RFP64:
12956   case X86::CMOV_RFP80:
12957     return EmitLoweredSelect(MI, BB);
12958
12959   case X86::FP32_TO_INT16_IN_MEM:
12960   case X86::FP32_TO_INT32_IN_MEM:
12961   case X86::FP32_TO_INT64_IN_MEM:
12962   case X86::FP64_TO_INT16_IN_MEM:
12963   case X86::FP64_TO_INT32_IN_MEM:
12964   case X86::FP64_TO_INT64_IN_MEM:
12965   case X86::FP80_TO_INT16_IN_MEM:
12966   case X86::FP80_TO_INT32_IN_MEM:
12967   case X86::FP80_TO_INT64_IN_MEM: {
12968     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12969     DebugLoc DL = MI->getDebugLoc();
12970
12971     // Change the floating point control register to use "round towards zero"
12972     // mode when truncating to an integer value.
12973     MachineFunction *F = BB->getParent();
12974     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12975     addFrameReference(BuildMI(*BB, MI, DL,
12976                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12977
12978     // Load the old value of the high byte of the control word...
12979     unsigned OldCW =
12980       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12981     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12982                       CWFrameIdx);
12983
12984     // Set the high part to be round to zero...
12985     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12986       .addImm(0xC7F);
12987
12988     // Reload the modified control word now...
12989     addFrameReference(BuildMI(*BB, MI, DL,
12990                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12991
12992     // Restore the memory image of control word to original value
12993     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12994       .addReg(OldCW);
12995
12996     // Get the X86 opcode to use.
12997     unsigned Opc;
12998     switch (MI->getOpcode()) {
12999     default: llvm_unreachable("illegal opcode!");
13000     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13001     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13002     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13003     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13004     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13005     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13006     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13007     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13008     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13009     }
13010
13011     X86AddressMode AM;
13012     MachineOperand &Op = MI->getOperand(0);
13013     if (Op.isReg()) {
13014       AM.BaseType = X86AddressMode::RegBase;
13015       AM.Base.Reg = Op.getReg();
13016     } else {
13017       AM.BaseType = X86AddressMode::FrameIndexBase;
13018       AM.Base.FrameIndex = Op.getIndex();
13019     }
13020     Op = MI->getOperand(1);
13021     if (Op.isImm())
13022       AM.Scale = Op.getImm();
13023     Op = MI->getOperand(2);
13024     if (Op.isImm())
13025       AM.IndexReg = Op.getImm();
13026     Op = MI->getOperand(3);
13027     if (Op.isGlobal()) {
13028       AM.GV = Op.getGlobal();
13029     } else {
13030       AM.Disp = Op.getImm();
13031     }
13032     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13033                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13034
13035     // Reload the original control word now.
13036     addFrameReference(BuildMI(*BB, MI, DL,
13037                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13038
13039     MI->eraseFromParent();   // The pseudo instruction is gone now.
13040     return BB;
13041   }
13042     // String/text processing lowering.
13043   case X86::PCMPISTRM128REG:
13044   case X86::VPCMPISTRM128REG:
13045   case X86::PCMPISTRM128MEM:
13046   case X86::VPCMPISTRM128MEM:
13047   case X86::PCMPESTRM128REG:
13048   case X86::VPCMPESTRM128REG:
13049   case X86::PCMPESTRM128MEM:
13050   case X86::VPCMPESTRM128MEM: {
13051     unsigned NumArgs;
13052     bool MemArg;
13053     switch (MI->getOpcode()) {
13054     default: llvm_unreachable("illegal opcode!");
13055     case X86::PCMPISTRM128REG:
13056     case X86::VPCMPISTRM128REG:
13057       NumArgs = 3; MemArg = false; break;
13058     case X86::PCMPISTRM128MEM:
13059     case X86::VPCMPISTRM128MEM:
13060       NumArgs = 3; MemArg = true; break;
13061     case X86::PCMPESTRM128REG:
13062     case X86::VPCMPESTRM128REG:
13063       NumArgs = 5; MemArg = false; break;
13064     case X86::PCMPESTRM128MEM:
13065     case X86::VPCMPESTRM128MEM:
13066       NumArgs = 5; MemArg = true; break;
13067     }
13068     return EmitPCMP(MI, BB, NumArgs, MemArg);
13069   }
13070
13071     // Thread synchronization.
13072   case X86::MONITOR:
13073     return EmitMonitor(MI, BB);
13074
13075     // Atomic Lowering.
13076   case X86::ATOMMIN32:
13077   case X86::ATOMMAX32:
13078   case X86::ATOMUMIN32:
13079   case X86::ATOMUMAX32:
13080   case X86::ATOMMIN16:
13081   case X86::ATOMMAX16:
13082   case X86::ATOMUMIN16:
13083   case X86::ATOMUMAX16:
13084   case X86::ATOMMIN64:
13085   case X86::ATOMMAX64:
13086   case X86::ATOMUMIN64:
13087   case X86::ATOMUMAX64: {
13088     unsigned Opc;
13089     switch (MI->getOpcode()) {
13090     default: llvm_unreachable("illegal opcode!");
13091     case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13092     case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13093     case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13094     case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13095     case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13096     case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13097     case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13098     case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13099     case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13100     case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13101     case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13102     case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13103     // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13104     }
13105     return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13106   }
13107
13108   case X86::ATOMAND32:
13109   case X86::ATOMOR32:
13110   case X86::ATOMXOR32:
13111   case X86::ATOMNAND32: {
13112     bool Invert = false;
13113     unsigned RegOpc, ImmOpc;
13114     switch (MI->getOpcode()) {
13115     default: llvm_unreachable("illegal opcode!");
13116     case X86::ATOMAND32:
13117       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13118     case X86::ATOMOR32:
13119       RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13120     case X86::ATOMXOR32:
13121       RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13122     case X86::ATOMNAND32:
13123       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13124     }
13125     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13126                                                X86::MOV32rm, X86::LCMPXCHG32,
13127                                                X86::NOT32r, X86::EAX,
13128                                                &X86::GR32RegClass, Invert);
13129   }
13130
13131   case X86::ATOMAND16:
13132   case X86::ATOMOR16:
13133   case X86::ATOMXOR16:
13134   case X86::ATOMNAND16: {
13135     bool Invert = false;
13136     unsigned RegOpc, ImmOpc;
13137     switch (MI->getOpcode()) {
13138     default: llvm_unreachable("illegal opcode!");
13139     case X86::ATOMAND16:
13140       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13141     case X86::ATOMOR16:
13142       RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13143     case X86::ATOMXOR16:
13144       RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13145     case X86::ATOMNAND16:
13146       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13147     }
13148     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13149                                                X86::MOV16rm, X86::LCMPXCHG16,
13150                                                X86::NOT16r, X86::AX,
13151                                                &X86::GR16RegClass, Invert);
13152   }
13153
13154   case X86::ATOMAND8:
13155   case X86::ATOMOR8:
13156   case X86::ATOMXOR8:
13157   case X86::ATOMNAND8: {
13158     bool Invert = false;
13159     unsigned RegOpc, ImmOpc;
13160     switch (MI->getOpcode()) {
13161     default: llvm_unreachable("illegal opcode!");
13162     case X86::ATOMAND8:
13163       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13164     case X86::ATOMOR8:
13165       RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13166     case X86::ATOMXOR8:
13167       RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13168     case X86::ATOMNAND8:
13169       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13170     }
13171     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13172                                                X86::MOV8rm, X86::LCMPXCHG8,
13173                                                X86::NOT8r, X86::AL,
13174                                                &X86::GR8RegClass, Invert);
13175   }
13176
13177   // This group is for 64-bit host.
13178   case X86::ATOMAND64:
13179   case X86::ATOMOR64:
13180   case X86::ATOMXOR64:
13181   case X86::ATOMNAND64: {
13182     bool Invert = false;
13183     unsigned RegOpc, ImmOpc;
13184     switch (MI->getOpcode()) {
13185     default: llvm_unreachable("illegal opcode!");
13186     case X86::ATOMAND64:
13187       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13188     case X86::ATOMOR64:
13189       RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13190     case X86::ATOMXOR64:
13191       RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13192     case X86::ATOMNAND64:
13193       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13194     }
13195     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13196                                                X86::MOV64rm, X86::LCMPXCHG64,
13197                                                X86::NOT64r, X86::RAX,
13198                                                &X86::GR64RegClass, Invert);
13199   }
13200
13201   // This group does 64-bit operations on a 32-bit host.
13202   case X86::ATOMAND6432:
13203   case X86::ATOMOR6432:
13204   case X86::ATOMXOR6432:
13205   case X86::ATOMNAND6432:
13206   case X86::ATOMADD6432:
13207   case X86::ATOMSUB6432:
13208   case X86::ATOMSWAP6432: {
13209     bool Invert = false;
13210     unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13211     switch (MI->getOpcode()) {
13212     default: llvm_unreachable("illegal opcode!");
13213     case X86::ATOMAND6432:
13214       RegOpcL = RegOpcH = X86::AND32rr;
13215       ImmOpcL = ImmOpcH = X86::AND32ri;
13216       break;
13217     case X86::ATOMOR6432:
13218       RegOpcL = RegOpcH = X86::OR32rr;
13219       ImmOpcL = ImmOpcH = X86::OR32ri;
13220       break;
13221     case X86::ATOMXOR6432:
13222       RegOpcL = RegOpcH = X86::XOR32rr;
13223       ImmOpcL = ImmOpcH = X86::XOR32ri;
13224       break;
13225     case X86::ATOMNAND6432:
13226       RegOpcL = RegOpcH = X86::AND32rr;
13227       ImmOpcL = ImmOpcH = X86::AND32ri;
13228       Invert = true;
13229       break;
13230     case X86::ATOMADD6432:
13231       RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13232       ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13233       break;
13234     case X86::ATOMSUB6432:
13235       RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13236       ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13237       break;
13238     case X86::ATOMSWAP6432:
13239       RegOpcL = RegOpcH = X86::MOV32rr;
13240       ImmOpcL = ImmOpcH = X86::MOV32ri;
13241       break;
13242     }
13243     return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13244                                                ImmOpcL, ImmOpcH, Invert);
13245   }
13246
13247   case X86::VASTART_SAVE_XMM_REGS:
13248     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13249
13250   case X86::VAARG_64:
13251     return EmitVAARG64WithCustomInserter(MI, BB);
13252   }
13253 }
13254
13255 //===----------------------------------------------------------------------===//
13256 //                           X86 Optimization Hooks
13257 //===----------------------------------------------------------------------===//
13258
13259 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13260                                                        APInt &KnownZero,
13261                                                        APInt &KnownOne,
13262                                                        const SelectionDAG &DAG,
13263                                                        unsigned Depth) const {
13264   unsigned BitWidth = KnownZero.getBitWidth();
13265   unsigned Opc = Op.getOpcode();
13266   assert((Opc >= ISD::BUILTIN_OP_END ||
13267           Opc == ISD::INTRINSIC_WO_CHAIN ||
13268           Opc == ISD::INTRINSIC_W_CHAIN ||
13269           Opc == ISD::INTRINSIC_VOID) &&
13270          "Should use MaskedValueIsZero if you don't know whether Op"
13271          " is a target node!");
13272
13273   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13274   switch (Opc) {
13275   default: break;
13276   case X86ISD::ADD:
13277   case X86ISD::SUB:
13278   case X86ISD::ADC:
13279   case X86ISD::SBB:
13280   case X86ISD::SMUL:
13281   case X86ISD::UMUL:
13282   case X86ISD::INC:
13283   case X86ISD::DEC:
13284   case X86ISD::OR:
13285   case X86ISD::XOR:
13286   case X86ISD::AND:
13287     // These nodes' second result is a boolean.
13288     if (Op.getResNo() == 0)
13289       break;
13290     // Fallthrough
13291   case X86ISD::SETCC:
13292     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13293     break;
13294   case ISD::INTRINSIC_WO_CHAIN: {
13295     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13296     unsigned NumLoBits = 0;
13297     switch (IntId) {
13298     default: break;
13299     case Intrinsic::x86_sse_movmsk_ps:
13300     case Intrinsic::x86_avx_movmsk_ps_256:
13301     case Intrinsic::x86_sse2_movmsk_pd:
13302     case Intrinsic::x86_avx_movmsk_pd_256:
13303     case Intrinsic::x86_mmx_pmovmskb:
13304     case Intrinsic::x86_sse2_pmovmskb_128:
13305     case Intrinsic::x86_avx2_pmovmskb: {
13306       // High bits of movmskp{s|d}, pmovmskb are known zero.
13307       switch (IntId) {
13308         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13309         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13310         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13311         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13312         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13313         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13314         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13315         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13316       }
13317       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13318       break;
13319     }
13320     }
13321     break;
13322   }
13323   }
13324 }
13325
13326 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13327                                                          unsigned Depth) const {
13328   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13329   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13330     return Op.getValueType().getScalarType().getSizeInBits();
13331
13332   // Fallback case.
13333   return 1;
13334 }
13335
13336 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13337 /// node is a GlobalAddress + offset.
13338 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13339                                        const GlobalValue* &GA,
13340                                        int64_t &Offset) const {
13341   if (N->getOpcode() == X86ISD::Wrapper) {
13342     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13343       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13344       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13345       return true;
13346     }
13347   }
13348   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13349 }
13350
13351 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13352 /// same as extracting the high 128-bit part of 256-bit vector and then
13353 /// inserting the result into the low part of a new 256-bit vector
13354 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13355   EVT VT = SVOp->getValueType(0);
13356   unsigned NumElems = VT.getVectorNumElements();
13357
13358   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13359   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13360     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13361         SVOp->getMaskElt(j) >= 0)
13362       return false;
13363
13364   return true;
13365 }
13366
13367 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13368 /// same as extracting the low 128-bit part of 256-bit vector and then
13369 /// inserting the result into the high part of a new 256-bit vector
13370 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13371   EVT VT = SVOp->getValueType(0);
13372   unsigned NumElems = VT.getVectorNumElements();
13373
13374   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13375   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13376     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13377         SVOp->getMaskElt(j) >= 0)
13378       return false;
13379
13380   return true;
13381 }
13382
13383 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13384 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13385                                         TargetLowering::DAGCombinerInfo &DCI,
13386                                         const X86Subtarget* Subtarget) {
13387   DebugLoc dl = N->getDebugLoc();
13388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13389   SDValue V1 = SVOp->getOperand(0);
13390   SDValue V2 = SVOp->getOperand(1);
13391   EVT VT = SVOp->getValueType(0);
13392   unsigned NumElems = VT.getVectorNumElements();
13393
13394   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13395       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13396     //
13397     //                   0,0,0,...
13398     //                      |
13399     //    V      UNDEF    BUILD_VECTOR    UNDEF
13400     //     \      /           \           /
13401     //  CONCAT_VECTOR         CONCAT_VECTOR
13402     //         \                  /
13403     //          \                /
13404     //          RESULT: V + zero extended
13405     //
13406     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13407         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13408         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13409       return SDValue();
13410
13411     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13412       return SDValue();
13413
13414     // To match the shuffle mask, the first half of the mask should
13415     // be exactly the first vector, and all the rest a splat with the
13416     // first element of the second one.
13417     for (unsigned i = 0; i != NumElems/2; ++i)
13418       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13419           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13420         return SDValue();
13421
13422     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13423     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13424       if (Ld->hasNUsesOfValue(1, 0)) {
13425         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13426         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13427         SDValue ResNode =
13428           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13429                                   Ld->getMemoryVT(),
13430                                   Ld->getPointerInfo(),
13431                                   Ld->getAlignment(),
13432                                   false/*isVolatile*/, true/*ReadMem*/,
13433                                   false/*WriteMem*/);
13434         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13435       }
13436     }
13437
13438     // Emit a zeroed vector and insert the desired subvector on its
13439     // first half.
13440     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13441     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13442     return DCI.CombineTo(N, InsV);
13443   }
13444
13445   //===--------------------------------------------------------------------===//
13446   // Combine some shuffles into subvector extracts and inserts:
13447   //
13448
13449   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13450   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13451     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13452     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13453     return DCI.CombineTo(N, InsV);
13454   }
13455
13456   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13457   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13458     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13459     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13460     return DCI.CombineTo(N, InsV);
13461   }
13462
13463   return SDValue();
13464 }
13465
13466 /// PerformShuffleCombine - Performs several different shuffle combines.
13467 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13468                                      TargetLowering::DAGCombinerInfo &DCI,
13469                                      const X86Subtarget *Subtarget) {
13470   DebugLoc dl = N->getDebugLoc();
13471   EVT VT = N->getValueType(0);
13472
13473   // Don't create instructions with illegal types after legalize types has run.
13474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13475   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13476     return SDValue();
13477
13478   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13479   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13480       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13481     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13482
13483   // Only handle 128 wide vector from here on.
13484   if (!VT.is128BitVector())
13485     return SDValue();
13486
13487   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13488   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13489   // consecutive, non-overlapping, and in the right order.
13490   SmallVector<SDValue, 16> Elts;
13491   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13492     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13493
13494   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13495 }
13496
13497
13498 /// PerformTruncateCombine - Converts truncate operation to
13499 /// a sequence of vector shuffle operations.
13500 /// It is possible when we truncate 256-bit vector to 128-bit vector
13501 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13502                                       TargetLowering::DAGCombinerInfo &DCI,
13503                                       const X86Subtarget *Subtarget)  {
13504   if (!DCI.isBeforeLegalizeOps())
13505     return SDValue();
13506
13507   if (!Subtarget->hasAVX())
13508     return SDValue();
13509
13510   EVT VT = N->getValueType(0);
13511   SDValue Op = N->getOperand(0);
13512   EVT OpVT = Op.getValueType();
13513   DebugLoc dl = N->getDebugLoc();
13514
13515   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13516
13517     if (Subtarget->hasAVX2()) {
13518       // AVX2: v4i64 -> v4i32
13519
13520       // VPERMD
13521       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13522
13523       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13524       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13525                                 ShufMask);
13526
13527       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13528                          DAG.getIntPtrConstant(0));
13529     }
13530
13531     // AVX: v4i64 -> v4i32
13532     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13533                                DAG.getIntPtrConstant(0));
13534
13535     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13536                                DAG.getIntPtrConstant(2));
13537
13538     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13539     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13540
13541     // PSHUFD
13542     static const int ShufMask1[] = {0, 2, 0, 0};
13543
13544     SDValue Undef = DAG.getUNDEF(VT);
13545     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13546     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13547
13548     // MOVLHPS
13549     static const int ShufMask2[] = {0, 1, 4, 5};
13550
13551     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13552   }
13553
13554   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13555
13556     if (Subtarget->hasAVX2()) {
13557       // AVX2: v8i32 -> v8i16
13558
13559       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13560
13561       // PSHUFB
13562       SmallVector<SDValue,32> pshufbMask;
13563       for (unsigned i = 0; i < 2; ++i) {
13564         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13565         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13566         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13567         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13568         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13569         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13570         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13571         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13572         for (unsigned j = 0; j < 8; ++j)
13573           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13574       }
13575       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13576                                &pshufbMask[0], 32);
13577       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13578
13579       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13580
13581       static const int ShufMask[] = {0,  2,  -1,  -1};
13582       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13583                                 &ShufMask[0]);
13584
13585       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13586                        DAG.getIntPtrConstant(0));
13587
13588       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13589     }
13590
13591     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13592                                DAG.getIntPtrConstant(0));
13593
13594     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13595                                DAG.getIntPtrConstant(4));
13596
13597     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13598     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13599
13600     // PSHUFB
13601     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13602                                    -1, -1, -1, -1, -1, -1, -1, -1};
13603
13604     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13605     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13606     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13607
13608     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13609     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13610
13611     // MOVLHPS
13612     static const int ShufMask2[] = {0, 1, 4, 5};
13613
13614     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13615     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13616   }
13617
13618   return SDValue();
13619 }
13620
13621 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13622 /// specific shuffle of a load can be folded into a single element load.
13623 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13624 /// shuffles have been customed lowered so we need to handle those here.
13625 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13626                                          TargetLowering::DAGCombinerInfo &DCI) {
13627   if (DCI.isBeforeLegalizeOps())
13628     return SDValue();
13629
13630   SDValue InVec = N->getOperand(0);
13631   SDValue EltNo = N->getOperand(1);
13632
13633   if (!isa<ConstantSDNode>(EltNo))
13634     return SDValue();
13635
13636   EVT VT = InVec.getValueType();
13637
13638   bool HasShuffleIntoBitcast = false;
13639   if (InVec.getOpcode() == ISD::BITCAST) {
13640     // Don't duplicate a load with other uses.
13641     if (!InVec.hasOneUse())
13642       return SDValue();
13643     EVT BCVT = InVec.getOperand(0).getValueType();
13644     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13645       return SDValue();
13646     InVec = InVec.getOperand(0);
13647     HasShuffleIntoBitcast = true;
13648   }
13649
13650   if (!isTargetShuffle(InVec.getOpcode()))
13651     return SDValue();
13652
13653   // Don't duplicate a load with other uses.
13654   if (!InVec.hasOneUse())
13655     return SDValue();
13656
13657   SmallVector<int, 16> ShuffleMask;
13658   bool UnaryShuffle;
13659   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13660                             UnaryShuffle))
13661     return SDValue();
13662
13663   // Select the input vector, guarding against out of range extract vector.
13664   unsigned NumElems = VT.getVectorNumElements();
13665   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13666   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13667   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13668                                          : InVec.getOperand(1);
13669
13670   // If inputs to shuffle are the same for both ops, then allow 2 uses
13671   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13672
13673   if (LdNode.getOpcode() == ISD::BITCAST) {
13674     // Don't duplicate a load with other uses.
13675     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13676       return SDValue();
13677
13678     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13679     LdNode = LdNode.getOperand(0);
13680   }
13681
13682   if (!ISD::isNormalLoad(LdNode.getNode()))
13683     return SDValue();
13684
13685   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13686
13687   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13688     return SDValue();
13689
13690   if (HasShuffleIntoBitcast) {
13691     // If there's a bitcast before the shuffle, check if the load type and
13692     // alignment is valid.
13693     unsigned Align = LN0->getAlignment();
13694     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13695     unsigned NewAlign = TLI.getTargetData()->
13696       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13697
13698     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13699       return SDValue();
13700   }
13701
13702   // All checks match so transform back to vector_shuffle so that DAG combiner
13703   // can finish the job
13704   DebugLoc dl = N->getDebugLoc();
13705
13706   // Create shuffle node taking into account the case that its a unary shuffle
13707   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13708   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13709                                  InVec.getOperand(0), Shuffle,
13710                                  &ShuffleMask[0]);
13711   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13712   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13713                      EltNo);
13714 }
13715
13716 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13717 /// generation and convert it from being a bunch of shuffles and extracts
13718 /// to a simple store and scalar loads to extract the elements.
13719 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13720                                          TargetLowering::DAGCombinerInfo &DCI) {
13721   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13722   if (NewOp.getNode())
13723     return NewOp;
13724
13725   SDValue InputVector = N->getOperand(0);
13726
13727   // Only operate on vectors of 4 elements, where the alternative shuffling
13728   // gets to be more expensive.
13729   if (InputVector.getValueType() != MVT::v4i32)
13730     return SDValue();
13731
13732   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13733   // single use which is a sign-extend or zero-extend, and all elements are
13734   // used.
13735   SmallVector<SDNode *, 4> Uses;
13736   unsigned ExtractedElements = 0;
13737   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13738        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13739     if (UI.getUse().getResNo() != InputVector.getResNo())
13740       return SDValue();
13741
13742     SDNode *Extract = *UI;
13743     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13744       return SDValue();
13745
13746     if (Extract->getValueType(0) != MVT::i32)
13747       return SDValue();
13748     if (!Extract->hasOneUse())
13749       return SDValue();
13750     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13751         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13752       return SDValue();
13753     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13754       return SDValue();
13755
13756     // Record which element was extracted.
13757     ExtractedElements |=
13758       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13759
13760     Uses.push_back(Extract);
13761   }
13762
13763   // If not all the elements were used, this may not be worthwhile.
13764   if (ExtractedElements != 15)
13765     return SDValue();
13766
13767   // Ok, we've now decided to do the transformation.
13768   DebugLoc dl = InputVector.getDebugLoc();
13769
13770   // Store the value to a temporary stack slot.
13771   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13772   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13773                             MachinePointerInfo(), false, false, 0);
13774
13775   // Replace each use (extract) with a load of the appropriate element.
13776   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13777        UE = Uses.end(); UI != UE; ++UI) {
13778     SDNode *Extract = *UI;
13779
13780     // cOMpute the element's address.
13781     SDValue Idx = Extract->getOperand(1);
13782     unsigned EltSize =
13783         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13784     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13785     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13786     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13787
13788     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13789                                      StackPtr, OffsetVal);
13790
13791     // Load the scalar.
13792     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13793                                      ScalarAddr, MachinePointerInfo(),
13794                                      false, false, false, 0);
13795
13796     // Replace the exact with the load.
13797     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13798   }
13799
13800   // The replacement was made in place; don't return anything.
13801   return SDValue();
13802 }
13803
13804 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13805 /// nodes.
13806 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13807                                     TargetLowering::DAGCombinerInfo &DCI,
13808                                     const X86Subtarget *Subtarget) {
13809   DebugLoc DL = N->getDebugLoc();
13810   SDValue Cond = N->getOperand(0);
13811   // Get the LHS/RHS of the select.
13812   SDValue LHS = N->getOperand(1);
13813   SDValue RHS = N->getOperand(2);
13814   EVT VT = LHS.getValueType();
13815
13816   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13817   // instructions match the semantics of the common C idiom x<y?x:y but not
13818   // x<=y?x:y, because of how they handle negative zero (which can be
13819   // ignored in unsafe-math mode).
13820   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13821       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13822       (Subtarget->hasSSE2() ||
13823        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13824     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13825
13826     unsigned Opcode = 0;
13827     // Check for x CC y ? x : y.
13828     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13829         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13830       switch (CC) {
13831       default: break;
13832       case ISD::SETULT:
13833         // Converting this to a min would handle NaNs incorrectly, and swapping
13834         // the operands would cause it to handle comparisons between positive
13835         // and negative zero incorrectly.
13836         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13837           if (!DAG.getTarget().Options.UnsafeFPMath &&
13838               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13839             break;
13840           std::swap(LHS, RHS);
13841         }
13842         Opcode = X86ISD::FMIN;
13843         break;
13844       case ISD::SETOLE:
13845         // Converting this to a min would handle comparisons between positive
13846         // and negative zero incorrectly.
13847         if (!DAG.getTarget().Options.UnsafeFPMath &&
13848             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13849           break;
13850         Opcode = X86ISD::FMIN;
13851         break;
13852       case ISD::SETULE:
13853         // Converting this to a min would handle both negative zeros and NaNs
13854         // incorrectly, but we can swap the operands to fix both.
13855         std::swap(LHS, RHS);
13856       case ISD::SETOLT:
13857       case ISD::SETLT:
13858       case ISD::SETLE:
13859         Opcode = X86ISD::FMIN;
13860         break;
13861
13862       case ISD::SETOGE:
13863         // Converting this to a max would handle comparisons between positive
13864         // and negative zero incorrectly.
13865         if (!DAG.getTarget().Options.UnsafeFPMath &&
13866             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13867           break;
13868         Opcode = X86ISD::FMAX;
13869         break;
13870       case ISD::SETUGT:
13871         // Converting this to a max would handle NaNs incorrectly, and swapping
13872         // the operands would cause it to handle comparisons between positive
13873         // and negative zero incorrectly.
13874         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13875           if (!DAG.getTarget().Options.UnsafeFPMath &&
13876               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13877             break;
13878           std::swap(LHS, RHS);
13879         }
13880         Opcode = X86ISD::FMAX;
13881         break;
13882       case ISD::SETUGE:
13883         // Converting this to a max would handle both negative zeros and NaNs
13884         // incorrectly, but we can swap the operands to fix both.
13885         std::swap(LHS, RHS);
13886       case ISD::SETOGT:
13887       case ISD::SETGT:
13888       case ISD::SETGE:
13889         Opcode = X86ISD::FMAX;
13890         break;
13891       }
13892     // Check for x CC y ? y : x -- a min/max with reversed arms.
13893     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13894                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13895       switch (CC) {
13896       default: break;
13897       case ISD::SETOGE:
13898         // Converting this to a min would handle comparisons between positive
13899         // and negative zero incorrectly, and swapping the operands would
13900         // cause it to handle NaNs incorrectly.
13901         if (!DAG.getTarget().Options.UnsafeFPMath &&
13902             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13903           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13904             break;
13905           std::swap(LHS, RHS);
13906         }
13907         Opcode = X86ISD::FMIN;
13908         break;
13909       case ISD::SETUGT:
13910         // Converting this to a min would handle NaNs incorrectly.
13911         if (!DAG.getTarget().Options.UnsafeFPMath &&
13912             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13913           break;
13914         Opcode = X86ISD::FMIN;
13915         break;
13916       case ISD::SETUGE:
13917         // Converting this to a min would handle both negative zeros and NaNs
13918         // incorrectly, but we can swap the operands to fix both.
13919         std::swap(LHS, RHS);
13920       case ISD::SETOGT:
13921       case ISD::SETGT:
13922       case ISD::SETGE:
13923         Opcode = X86ISD::FMIN;
13924         break;
13925
13926       case ISD::SETULT:
13927         // Converting this to a max would handle NaNs incorrectly.
13928         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13929           break;
13930         Opcode = X86ISD::FMAX;
13931         break;
13932       case ISD::SETOLE:
13933         // Converting this to a max would handle comparisons between positive
13934         // and negative zero incorrectly, and swapping the operands would
13935         // cause it to handle NaNs incorrectly.
13936         if (!DAG.getTarget().Options.UnsafeFPMath &&
13937             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13938           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13939             break;
13940           std::swap(LHS, RHS);
13941         }
13942         Opcode = X86ISD::FMAX;
13943         break;
13944       case ISD::SETULE:
13945         // Converting this to a max would handle both negative zeros and NaNs
13946         // incorrectly, but we can swap the operands to fix both.
13947         std::swap(LHS, RHS);
13948       case ISD::SETOLT:
13949       case ISD::SETLT:
13950       case ISD::SETLE:
13951         Opcode = X86ISD::FMAX;
13952         break;
13953       }
13954     }
13955
13956     if (Opcode)
13957       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13958   }
13959
13960   // If this is a select between two integer constants, try to do some
13961   // optimizations.
13962   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13963     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13964       // Don't do this for crazy integer types.
13965       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13966         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13967         // so that TrueC (the true value) is larger than FalseC.
13968         bool NeedsCondInvert = false;
13969
13970         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13971             // Efficiently invertible.
13972             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13973              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13974               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13975           NeedsCondInvert = true;
13976           std::swap(TrueC, FalseC);
13977         }
13978
13979         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13980         if (FalseC->getAPIntValue() == 0 &&
13981             TrueC->getAPIntValue().isPowerOf2()) {
13982           if (NeedsCondInvert) // Invert the condition if needed.
13983             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13984                                DAG.getConstant(1, Cond.getValueType()));
13985
13986           // Zero extend the condition if needed.
13987           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13988
13989           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13990           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13991                              DAG.getConstant(ShAmt, MVT::i8));
13992         }
13993
13994         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13995         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13996           if (NeedsCondInvert) // Invert the condition if needed.
13997             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13998                                DAG.getConstant(1, Cond.getValueType()));
13999
14000           // Zero extend the condition if needed.
14001           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14002                              FalseC->getValueType(0), Cond);
14003           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14004                              SDValue(FalseC, 0));
14005         }
14006
14007         // Optimize cases that will turn into an LEA instruction.  This requires
14008         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14009         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14010           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14011           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14012
14013           bool isFastMultiplier = false;
14014           if (Diff < 10) {
14015             switch ((unsigned char)Diff) {
14016               default: break;
14017               case 1:  // result = add base, cond
14018               case 2:  // result = lea base(    , cond*2)
14019               case 3:  // result = lea base(cond, cond*2)
14020               case 4:  // result = lea base(    , cond*4)
14021               case 5:  // result = lea base(cond, cond*4)
14022               case 8:  // result = lea base(    , cond*8)
14023               case 9:  // result = lea base(cond, cond*8)
14024                 isFastMultiplier = true;
14025                 break;
14026             }
14027           }
14028
14029           if (isFastMultiplier) {
14030             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14031             if (NeedsCondInvert) // Invert the condition if needed.
14032               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14033                                  DAG.getConstant(1, Cond.getValueType()));
14034
14035             // Zero extend the condition if needed.
14036             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14037                                Cond);
14038             // Scale the condition by the difference.
14039             if (Diff != 1)
14040               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14041                                  DAG.getConstant(Diff, Cond.getValueType()));
14042
14043             // Add the base if non-zero.
14044             if (FalseC->getAPIntValue() != 0)
14045               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14046                                  SDValue(FalseC, 0));
14047             return Cond;
14048           }
14049         }
14050       }
14051   }
14052
14053   // Canonicalize max and min:
14054   // (x > y) ? x : y -> (x >= y) ? x : y
14055   // (x < y) ? x : y -> (x <= y) ? x : y
14056   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14057   // the need for an extra compare
14058   // against zero. e.g.
14059   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14060   // subl   %esi, %edi
14061   // testl  %edi, %edi
14062   // movl   $0, %eax
14063   // cmovgl %edi, %eax
14064   // =>
14065   // xorl   %eax, %eax
14066   // subl   %esi, $edi
14067   // cmovsl %eax, %edi
14068   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14069       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14070       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14071     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14072     switch (CC) {
14073     default: break;
14074     case ISD::SETLT:
14075     case ISD::SETGT: {
14076       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14077       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14078                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14079       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14080     }
14081     }
14082   }
14083
14084   // If we know that this node is legal then we know that it is going to be
14085   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14086   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14087   // to simplify previous instructions.
14088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14089   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14090       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14091     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14092
14093     // Don't optimize vector selects that map to mask-registers.
14094     if (BitWidth == 1)
14095       return SDValue();
14096
14097     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14098     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14099
14100     APInt KnownZero, KnownOne;
14101     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14102                                           DCI.isBeforeLegalizeOps());
14103     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14104         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14105       DCI.CommitTargetLoweringOpt(TLO);
14106   }
14107
14108   return SDValue();
14109 }
14110
14111 // Check whether a boolean test is testing a boolean value generated by
14112 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14113 // code.
14114 //
14115 // Simplify the following patterns:
14116 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14117 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14118 // to (Op EFLAGS Cond)
14119 //
14120 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14121 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14122 // to (Op EFLAGS !Cond)
14123 //
14124 // where Op could be BRCOND or CMOV.
14125 //
14126 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14127   // Quit if not CMP and SUB with its value result used.
14128   if (Cmp.getOpcode() != X86ISD::CMP &&
14129       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14130       return SDValue();
14131
14132   // Quit if not used as a boolean value.
14133   if (CC != X86::COND_E && CC != X86::COND_NE)
14134     return SDValue();
14135
14136   // Check CMP operands. One of them should be 0 or 1 and the other should be
14137   // an SetCC or extended from it.
14138   SDValue Op1 = Cmp.getOperand(0);
14139   SDValue Op2 = Cmp.getOperand(1);
14140
14141   SDValue SetCC;
14142   const ConstantSDNode* C = 0;
14143   bool needOppositeCond = (CC == X86::COND_E);
14144
14145   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14146     SetCC = Op2;
14147   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14148     SetCC = Op1;
14149   else // Quit if all operands are not constants.
14150     return SDValue();
14151
14152   if (C->getZExtValue() == 1)
14153     needOppositeCond = !needOppositeCond;
14154   else if (C->getZExtValue() != 0)
14155     // Quit if the constant is neither 0 or 1.
14156     return SDValue();
14157
14158   // Skip 'zext' node.
14159   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14160     SetCC = SetCC.getOperand(0);
14161
14162   switch (SetCC.getOpcode()) {
14163   case X86ISD::SETCC:
14164     // Set the condition code or opposite one if necessary.
14165     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14166     if (needOppositeCond)
14167       CC = X86::GetOppositeBranchCondition(CC);
14168     return SetCC.getOperand(1);
14169   case X86ISD::CMOV: {
14170     // Check whether false/true value has canonical one, i.e. 0 or 1.
14171     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14172     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14173     // Quit if true value is not a constant.
14174     if (!TVal)
14175       return SDValue();
14176     // Quit if false value is not a constant.
14177     if (!FVal) {
14178       // A special case for rdrand, where 0 is set if false cond is found.
14179       SDValue Op = SetCC.getOperand(0);
14180       if (Op.getOpcode() != X86ISD::RDRAND)
14181         return SDValue();
14182     }
14183     // Quit if false value is not the constant 0 or 1.
14184     bool FValIsFalse = true;
14185     if (FVal && FVal->getZExtValue() != 0) {
14186       if (FVal->getZExtValue() != 1)
14187         return SDValue();
14188       // If FVal is 1, opposite cond is needed.
14189       needOppositeCond = !needOppositeCond;
14190       FValIsFalse = false;
14191     }
14192     // Quit if TVal is not the constant opposite of FVal.
14193     if (FValIsFalse && TVal->getZExtValue() != 1)
14194       return SDValue();
14195     if (!FValIsFalse && TVal->getZExtValue() != 0)
14196       return SDValue();
14197     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14198     if (needOppositeCond)
14199       CC = X86::GetOppositeBranchCondition(CC);
14200     return SetCC.getOperand(3);
14201   }
14202   }
14203
14204   return SDValue();
14205 }
14206
14207 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14208 /// updated. If only flag result is used and the result is evaluated from a
14209 /// series of element extraction, try to combine it into a PTEST.
14210 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14211                                      SelectionDAG &DAG,
14212                                      const X86Subtarget *Subtarget) {
14213   SDNode *N = Or.getNode();
14214   DebugLoc DL = N->getDebugLoc();
14215
14216   // Only SSE4.1 and beyond supports PTEST or like.
14217   if (!Subtarget->hasSSE41())
14218     return SDValue();
14219
14220   if (N->getOpcode() != X86ISD::OR)
14221     return SDValue();
14222
14223   // Quit if the value result of OR is used.
14224   if (N->hasAnyUseOfValue(0))
14225     return SDValue();
14226
14227   // Quit if not used as a boolean value.
14228   if (CC != X86::COND_E && CC != X86::COND_NE)
14229     return SDValue();
14230
14231   SmallVector<SDValue, 8> Opnds;
14232   SDValue VecIn;
14233   EVT VT = MVT::Other;
14234   unsigned Mask = 0;
14235
14236   // Recognize a special case where a vector is casted into wide integer to
14237   // test all 0s.
14238   Opnds.push_back(N->getOperand(0));
14239   Opnds.push_back(N->getOperand(1));
14240
14241   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14242     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14243     // BFS traverse all OR'd operands.
14244     if (I->getOpcode() == ISD::OR) {
14245       Opnds.push_back(I->getOperand(0));
14246       Opnds.push_back(I->getOperand(1));
14247       // Re-evaluate the number of nodes to be traversed.
14248       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14249       continue;
14250     }
14251
14252     // Quit if a non-EXTRACT_VECTOR_ELT
14253     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14254       return SDValue();
14255
14256     // Quit if without a constant index.
14257     SDValue Idx = I->getOperand(1);
14258     if (!isa<ConstantSDNode>(Idx))
14259       return SDValue();
14260
14261     // Check if all elements are extracted from the same vector.
14262     SDValue ExtractedFromVec = I->getOperand(0);
14263     if (VecIn.getNode() == 0) {
14264       VT = ExtractedFromVec.getValueType();
14265       // FIXME: only 128-bit vector is supported so far.
14266       if (!VT.is128BitVector())
14267         return SDValue();
14268       VecIn = ExtractedFromVec;
14269     } else if (VecIn != ExtractedFromVec)
14270       return SDValue();
14271
14272     // Record the constant index.
14273     Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14274   }
14275
14276   assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14277
14278   // Quit if not all elements are used.
14279   if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14280     return SDValue();
14281
14282   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14283 }
14284
14285 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14286 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14287                                   TargetLowering::DAGCombinerInfo &DCI,
14288                                   const X86Subtarget *Subtarget) {
14289   DebugLoc DL = N->getDebugLoc();
14290
14291   // If the flag operand isn't dead, don't touch this CMOV.
14292   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14293     return SDValue();
14294
14295   SDValue FalseOp = N->getOperand(0);
14296   SDValue TrueOp = N->getOperand(1);
14297   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14298   SDValue Cond = N->getOperand(3);
14299
14300   if (CC == X86::COND_E || CC == X86::COND_NE) {
14301     switch (Cond.getOpcode()) {
14302     default: break;
14303     case X86ISD::BSR:
14304     case X86ISD::BSF:
14305       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14306       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14307         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14308     }
14309   }
14310
14311   SDValue Flags;
14312
14313   Flags = checkBoolTestSetCCCombine(Cond, CC);
14314   if (Flags.getNode() &&
14315       // Extra check as FCMOV only supports a subset of X86 cond.
14316       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14317     SDValue Ops[] = { FalseOp, TrueOp,
14318                       DAG.getConstant(CC, MVT::i8), Flags };
14319     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14320                        Ops, array_lengthof(Ops));
14321   }
14322
14323   Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14324   if (Flags.getNode()) {
14325     SDValue Ops[] = { FalseOp, TrueOp,
14326                       DAG.getConstant(CC, MVT::i8), Flags };
14327     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14328                        Ops, array_lengthof(Ops));
14329   }
14330
14331   // If this is a select between two integer constants, try to do some
14332   // optimizations.  Note that the operands are ordered the opposite of SELECT
14333   // operands.
14334   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14335     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14336       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14337       // larger than FalseC (the false value).
14338       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14339         CC = X86::GetOppositeBranchCondition(CC);
14340         std::swap(TrueC, FalseC);
14341       }
14342
14343       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14344       // This is efficient for any integer data type (including i8/i16) and
14345       // shift amount.
14346       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14347         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14348                            DAG.getConstant(CC, MVT::i8), Cond);
14349
14350         // Zero extend the condition if needed.
14351         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14352
14353         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14354         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14355                            DAG.getConstant(ShAmt, MVT::i8));
14356         if (N->getNumValues() == 2)  // Dead flag value?
14357           return DCI.CombineTo(N, Cond, SDValue());
14358         return Cond;
14359       }
14360
14361       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14362       // for any integer data type, including i8/i16.
14363       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14364         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14365                            DAG.getConstant(CC, MVT::i8), Cond);
14366
14367         // Zero extend the condition if needed.
14368         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14369                            FalseC->getValueType(0), Cond);
14370         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14371                            SDValue(FalseC, 0));
14372
14373         if (N->getNumValues() == 2)  // Dead flag value?
14374           return DCI.CombineTo(N, Cond, SDValue());
14375         return Cond;
14376       }
14377
14378       // Optimize cases that will turn into an LEA instruction.  This requires
14379       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14380       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14381         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14382         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14383
14384         bool isFastMultiplier = false;
14385         if (Diff < 10) {
14386           switch ((unsigned char)Diff) {
14387           default: break;
14388           case 1:  // result = add base, cond
14389           case 2:  // result = lea base(    , cond*2)
14390           case 3:  // result = lea base(cond, cond*2)
14391           case 4:  // result = lea base(    , cond*4)
14392           case 5:  // result = lea base(cond, cond*4)
14393           case 8:  // result = lea base(    , cond*8)
14394           case 9:  // result = lea base(cond, cond*8)
14395             isFastMultiplier = true;
14396             break;
14397           }
14398         }
14399
14400         if (isFastMultiplier) {
14401           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14402           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14403                              DAG.getConstant(CC, MVT::i8), Cond);
14404           // Zero extend the condition if needed.
14405           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14406                              Cond);
14407           // Scale the condition by the difference.
14408           if (Diff != 1)
14409             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14410                                DAG.getConstant(Diff, Cond.getValueType()));
14411
14412           // Add the base if non-zero.
14413           if (FalseC->getAPIntValue() != 0)
14414             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14415                                SDValue(FalseC, 0));
14416           if (N->getNumValues() == 2)  // Dead flag value?
14417             return DCI.CombineTo(N, Cond, SDValue());
14418           return Cond;
14419         }
14420       }
14421     }
14422   }
14423   return SDValue();
14424 }
14425
14426
14427 /// PerformMulCombine - Optimize a single multiply with constant into two
14428 /// in order to implement it with two cheaper instructions, e.g.
14429 /// LEA + SHL, LEA + LEA.
14430 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14431                                  TargetLowering::DAGCombinerInfo &DCI) {
14432   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14433     return SDValue();
14434
14435   EVT VT = N->getValueType(0);
14436   if (VT != MVT::i64)
14437     return SDValue();
14438
14439   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14440   if (!C)
14441     return SDValue();
14442   uint64_t MulAmt = C->getZExtValue();
14443   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14444     return SDValue();
14445
14446   uint64_t MulAmt1 = 0;
14447   uint64_t MulAmt2 = 0;
14448   if ((MulAmt % 9) == 0) {
14449     MulAmt1 = 9;
14450     MulAmt2 = MulAmt / 9;
14451   } else if ((MulAmt % 5) == 0) {
14452     MulAmt1 = 5;
14453     MulAmt2 = MulAmt / 5;
14454   } else if ((MulAmt % 3) == 0) {
14455     MulAmt1 = 3;
14456     MulAmt2 = MulAmt / 3;
14457   }
14458   if (MulAmt2 &&
14459       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14460     DebugLoc DL = N->getDebugLoc();
14461
14462     if (isPowerOf2_64(MulAmt2) &&
14463         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14464       // If second multiplifer is pow2, issue it first. We want the multiply by
14465       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14466       // is an add.
14467       std::swap(MulAmt1, MulAmt2);
14468
14469     SDValue NewMul;
14470     if (isPowerOf2_64(MulAmt1))
14471       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14472                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14473     else
14474       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14475                            DAG.getConstant(MulAmt1, VT));
14476
14477     if (isPowerOf2_64(MulAmt2))
14478       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14479                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14480     else
14481       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14482                            DAG.getConstant(MulAmt2, VT));
14483
14484     // Do not add new nodes to DAG combiner worklist.
14485     DCI.CombineTo(N, NewMul, false);
14486   }
14487   return SDValue();
14488 }
14489
14490 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14491   SDValue N0 = N->getOperand(0);
14492   SDValue N1 = N->getOperand(1);
14493   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14494   EVT VT = N0.getValueType();
14495
14496   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14497   // since the result of setcc_c is all zero's or all ones.
14498   if (VT.isInteger() && !VT.isVector() &&
14499       N1C && N0.getOpcode() == ISD::AND &&
14500       N0.getOperand(1).getOpcode() == ISD::Constant) {
14501     SDValue N00 = N0.getOperand(0);
14502     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14503         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14504           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14505          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14506       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14507       APInt ShAmt = N1C->getAPIntValue();
14508       Mask = Mask.shl(ShAmt);
14509       if (Mask != 0)
14510         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14511                            N00, DAG.getConstant(Mask, VT));
14512     }
14513   }
14514
14515
14516   // Hardware support for vector shifts is sparse which makes us scalarize the
14517   // vector operations in many cases. Also, on sandybridge ADD is faster than
14518   // shl.
14519   // (shl V, 1) -> add V,V
14520   if (isSplatVector(N1.getNode())) {
14521     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14522     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14523     // We shift all of the values by one. In many cases we do not have
14524     // hardware support for this operation. This is better expressed as an ADD
14525     // of two values.
14526     if (N1C && (1 == N1C->getZExtValue())) {
14527       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14528     }
14529   }
14530
14531   return SDValue();
14532 }
14533
14534 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14535 ///                       when possible.
14536 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14537                                    TargetLowering::DAGCombinerInfo &DCI,
14538                                    const X86Subtarget *Subtarget) {
14539   EVT VT = N->getValueType(0);
14540   if (N->getOpcode() == ISD::SHL) {
14541     SDValue V = PerformSHLCombine(N, DAG);
14542     if (V.getNode()) return V;
14543   }
14544
14545   // On X86 with SSE2 support, we can transform this to a vector shift if
14546   // all elements are shifted by the same amount.  We can't do this in legalize
14547   // because the a constant vector is typically transformed to a constant pool
14548   // so we have no knowledge of the shift amount.
14549   if (!Subtarget->hasSSE2())
14550     return SDValue();
14551
14552   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14553       (!Subtarget->hasAVX2() ||
14554        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14555     return SDValue();
14556
14557   SDValue ShAmtOp = N->getOperand(1);
14558   EVT EltVT = VT.getVectorElementType();
14559   DebugLoc DL = N->getDebugLoc();
14560   SDValue BaseShAmt = SDValue();
14561   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14562     unsigned NumElts = VT.getVectorNumElements();
14563     unsigned i = 0;
14564     for (; i != NumElts; ++i) {
14565       SDValue Arg = ShAmtOp.getOperand(i);
14566       if (Arg.getOpcode() == ISD::UNDEF) continue;
14567       BaseShAmt = Arg;
14568       break;
14569     }
14570     // Handle the case where the build_vector is all undef
14571     // FIXME: Should DAG allow this?
14572     if (i == NumElts)
14573       return SDValue();
14574
14575     for (; i != NumElts; ++i) {
14576       SDValue Arg = ShAmtOp.getOperand(i);
14577       if (Arg.getOpcode() == ISD::UNDEF) continue;
14578       if (Arg != BaseShAmt) {
14579         return SDValue();
14580       }
14581     }
14582   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14583              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14584     SDValue InVec = ShAmtOp.getOperand(0);
14585     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14586       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14587       unsigned i = 0;
14588       for (; i != NumElts; ++i) {
14589         SDValue Arg = InVec.getOperand(i);
14590         if (Arg.getOpcode() == ISD::UNDEF) continue;
14591         BaseShAmt = Arg;
14592         break;
14593       }
14594     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14595        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14596          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14597          if (C->getZExtValue() == SplatIdx)
14598            BaseShAmt = InVec.getOperand(1);
14599        }
14600     }
14601     if (BaseShAmt.getNode() == 0) {
14602       // Don't create instructions with illegal types after legalize
14603       // types has run.
14604       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14605           !DCI.isBeforeLegalize())
14606         return SDValue();
14607
14608       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14609                               DAG.getIntPtrConstant(0));
14610     }
14611   } else
14612     return SDValue();
14613
14614   // The shift amount is an i32.
14615   if (EltVT.bitsGT(MVT::i32))
14616     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14617   else if (EltVT.bitsLT(MVT::i32))
14618     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14619
14620   // The shift amount is identical so we can do a vector shift.
14621   SDValue  ValOp = N->getOperand(0);
14622   switch (N->getOpcode()) {
14623   default:
14624     llvm_unreachable("Unknown shift opcode!");
14625   case ISD::SHL:
14626     switch (VT.getSimpleVT().SimpleTy) {
14627     default: return SDValue();
14628     case MVT::v2i64:
14629     case MVT::v4i32:
14630     case MVT::v8i16:
14631     case MVT::v4i64:
14632     case MVT::v8i32:
14633     case MVT::v16i16:
14634       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14635     }
14636   case ISD::SRA:
14637     switch (VT.getSimpleVT().SimpleTy) {
14638     default: return SDValue();
14639     case MVT::v4i32:
14640     case MVT::v8i16:
14641     case MVT::v8i32:
14642     case MVT::v16i16:
14643       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14644     }
14645   case ISD::SRL:
14646     switch (VT.getSimpleVT().SimpleTy) {
14647     default: return SDValue();
14648     case MVT::v2i64:
14649     case MVT::v4i32:
14650     case MVT::v8i16:
14651     case MVT::v4i64:
14652     case MVT::v8i32:
14653     case MVT::v16i16:
14654       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14655     }
14656   }
14657 }
14658
14659
14660 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14661 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14662 // and friends.  Likewise for OR -> CMPNEQSS.
14663 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14664                             TargetLowering::DAGCombinerInfo &DCI,
14665                             const X86Subtarget *Subtarget) {
14666   unsigned opcode;
14667
14668   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14669   // we're requiring SSE2 for both.
14670   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14671     SDValue N0 = N->getOperand(0);
14672     SDValue N1 = N->getOperand(1);
14673     SDValue CMP0 = N0->getOperand(1);
14674     SDValue CMP1 = N1->getOperand(1);
14675     DebugLoc DL = N->getDebugLoc();
14676
14677     // The SETCCs should both refer to the same CMP.
14678     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14679       return SDValue();
14680
14681     SDValue CMP00 = CMP0->getOperand(0);
14682     SDValue CMP01 = CMP0->getOperand(1);
14683     EVT     VT    = CMP00.getValueType();
14684
14685     if (VT == MVT::f32 || VT == MVT::f64) {
14686       bool ExpectingFlags = false;
14687       // Check for any users that want flags:
14688       for (SDNode::use_iterator UI = N->use_begin(),
14689              UE = N->use_end();
14690            !ExpectingFlags && UI != UE; ++UI)
14691         switch (UI->getOpcode()) {
14692         default:
14693         case ISD::BR_CC:
14694         case ISD::BRCOND:
14695         case ISD::SELECT:
14696           ExpectingFlags = true;
14697           break;
14698         case ISD::CopyToReg:
14699         case ISD::SIGN_EXTEND:
14700         case ISD::ZERO_EXTEND:
14701         case ISD::ANY_EXTEND:
14702           break;
14703         }
14704
14705       if (!ExpectingFlags) {
14706         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14707         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14708
14709         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14710           X86::CondCode tmp = cc0;
14711           cc0 = cc1;
14712           cc1 = tmp;
14713         }
14714
14715         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14716             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14717           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14718           X86ISD::NodeType NTOperator = is64BitFP ?
14719             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14720           // FIXME: need symbolic constants for these magic numbers.
14721           // See X86ATTInstPrinter.cpp:printSSECC().
14722           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14723           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14724                                               DAG.getConstant(x86cc, MVT::i8));
14725           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14726                                               OnesOrZeroesF);
14727           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14728                                       DAG.getConstant(1, MVT::i32));
14729           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14730           return OneBitOfTruth;
14731         }
14732       }
14733     }
14734   }
14735   return SDValue();
14736 }
14737
14738 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14739 /// so it can be folded inside ANDNP.
14740 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14741   EVT VT = N->getValueType(0);
14742
14743   // Match direct AllOnes for 128 and 256-bit vectors
14744   if (ISD::isBuildVectorAllOnes(N))
14745     return true;
14746
14747   // Look through a bit convert.
14748   if (N->getOpcode() == ISD::BITCAST)
14749     N = N->getOperand(0).getNode();
14750
14751   // Sometimes the operand may come from a insert_subvector building a 256-bit
14752   // allones vector
14753   if (VT.is256BitVector() &&
14754       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14755     SDValue V1 = N->getOperand(0);
14756     SDValue V2 = N->getOperand(1);
14757
14758     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14759         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14760         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14761         ISD::isBuildVectorAllOnes(V2.getNode()))
14762       return true;
14763   }
14764
14765   return false;
14766 }
14767
14768 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14769                                  TargetLowering::DAGCombinerInfo &DCI,
14770                                  const X86Subtarget *Subtarget) {
14771   if (DCI.isBeforeLegalizeOps())
14772     return SDValue();
14773
14774   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14775   if (R.getNode())
14776     return R;
14777
14778   EVT VT = N->getValueType(0);
14779
14780   // Create ANDN, BLSI, and BLSR instructions
14781   // BLSI is X & (-X)
14782   // BLSR is X & (X-1)
14783   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14784     SDValue N0 = N->getOperand(0);
14785     SDValue N1 = N->getOperand(1);
14786     DebugLoc DL = N->getDebugLoc();
14787
14788     // Check LHS for not
14789     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14790       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14791     // Check RHS for not
14792     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14793       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14794
14795     // Check LHS for neg
14796     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14797         isZero(N0.getOperand(0)))
14798       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14799
14800     // Check RHS for neg
14801     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14802         isZero(N1.getOperand(0)))
14803       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14804
14805     // Check LHS for X-1
14806     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14807         isAllOnes(N0.getOperand(1)))
14808       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14809
14810     // Check RHS for X-1
14811     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14812         isAllOnes(N1.getOperand(1)))
14813       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14814
14815     return SDValue();
14816   }
14817
14818   // Want to form ANDNP nodes:
14819   // 1) In the hopes of then easily combining them with OR and AND nodes
14820   //    to form PBLEND/PSIGN.
14821   // 2) To match ANDN packed intrinsics
14822   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14823     return SDValue();
14824
14825   SDValue N0 = N->getOperand(0);
14826   SDValue N1 = N->getOperand(1);
14827   DebugLoc DL = N->getDebugLoc();
14828
14829   // Check LHS for vnot
14830   if (N0.getOpcode() == ISD::XOR &&
14831       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14832       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14833     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14834
14835   // Check RHS for vnot
14836   if (N1.getOpcode() == ISD::XOR &&
14837       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14838       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14839     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14840
14841   return SDValue();
14842 }
14843
14844 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14845                                 TargetLowering::DAGCombinerInfo &DCI,
14846                                 const X86Subtarget *Subtarget) {
14847   if (DCI.isBeforeLegalizeOps())
14848     return SDValue();
14849
14850   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14851   if (R.getNode())
14852     return R;
14853
14854   EVT VT = N->getValueType(0);
14855
14856   SDValue N0 = N->getOperand(0);
14857   SDValue N1 = N->getOperand(1);
14858
14859   // look for psign/blend
14860   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14861     if (!Subtarget->hasSSSE3() ||
14862         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14863       return SDValue();
14864
14865     // Canonicalize pandn to RHS
14866     if (N0.getOpcode() == X86ISD::ANDNP)
14867       std::swap(N0, N1);
14868     // or (and (m, y), (pandn m, x))
14869     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14870       SDValue Mask = N1.getOperand(0);
14871       SDValue X    = N1.getOperand(1);
14872       SDValue Y;
14873       if (N0.getOperand(0) == Mask)
14874         Y = N0.getOperand(1);
14875       if (N0.getOperand(1) == Mask)
14876         Y = N0.getOperand(0);
14877
14878       // Check to see if the mask appeared in both the AND and ANDNP and
14879       if (!Y.getNode())
14880         return SDValue();
14881
14882       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14883       // Look through mask bitcast.
14884       if (Mask.getOpcode() == ISD::BITCAST)
14885         Mask = Mask.getOperand(0);
14886       if (X.getOpcode() == ISD::BITCAST)
14887         X = X.getOperand(0);
14888       if (Y.getOpcode() == ISD::BITCAST)
14889         Y = Y.getOperand(0);
14890
14891       EVT MaskVT = Mask.getValueType();
14892
14893       // Validate that the Mask operand is a vector sra node.
14894       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14895       // there is no psrai.b
14896       if (Mask.getOpcode() != X86ISD::VSRAI)
14897         return SDValue();
14898
14899       // Check that the SRA is all signbits.
14900       SDValue SraC = Mask.getOperand(1);
14901       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14902       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14903       if ((SraAmt + 1) != EltBits)
14904         return SDValue();
14905
14906       DebugLoc DL = N->getDebugLoc();
14907
14908       // Now we know we at least have a plendvb with the mask val.  See if
14909       // we can form a psignb/w/d.
14910       // psign = x.type == y.type == mask.type && y = sub(0, x);
14911       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14912           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14913           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14914         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14915                "Unsupported VT for PSIGN");
14916         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14917         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14918       }
14919       // PBLENDVB only available on SSE 4.1
14920       if (!Subtarget->hasSSE41())
14921         return SDValue();
14922
14923       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14924
14925       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14926       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14927       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14928       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14929       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14930     }
14931   }
14932
14933   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14934     return SDValue();
14935
14936   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14937   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14938     std::swap(N0, N1);
14939   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14940     return SDValue();
14941   if (!N0.hasOneUse() || !N1.hasOneUse())
14942     return SDValue();
14943
14944   SDValue ShAmt0 = N0.getOperand(1);
14945   if (ShAmt0.getValueType() != MVT::i8)
14946     return SDValue();
14947   SDValue ShAmt1 = N1.getOperand(1);
14948   if (ShAmt1.getValueType() != MVT::i8)
14949     return SDValue();
14950   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14951     ShAmt0 = ShAmt0.getOperand(0);
14952   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14953     ShAmt1 = ShAmt1.getOperand(0);
14954
14955   DebugLoc DL = N->getDebugLoc();
14956   unsigned Opc = X86ISD::SHLD;
14957   SDValue Op0 = N0.getOperand(0);
14958   SDValue Op1 = N1.getOperand(0);
14959   if (ShAmt0.getOpcode() == ISD::SUB) {
14960     Opc = X86ISD::SHRD;
14961     std::swap(Op0, Op1);
14962     std::swap(ShAmt0, ShAmt1);
14963   }
14964
14965   unsigned Bits = VT.getSizeInBits();
14966   if (ShAmt1.getOpcode() == ISD::SUB) {
14967     SDValue Sum = ShAmt1.getOperand(0);
14968     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14969       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14970       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14971         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14972       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14973         return DAG.getNode(Opc, DL, VT,
14974                            Op0, Op1,
14975                            DAG.getNode(ISD::TRUNCATE, DL,
14976                                        MVT::i8, ShAmt0));
14977     }
14978   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14979     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14980     if (ShAmt0C &&
14981         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14982       return DAG.getNode(Opc, DL, VT,
14983                          N0.getOperand(0), N1.getOperand(0),
14984                          DAG.getNode(ISD::TRUNCATE, DL,
14985                                        MVT::i8, ShAmt0));
14986   }
14987
14988   return SDValue();
14989 }
14990
14991 // Generate NEG and CMOV for integer abs.
14992 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14993   EVT VT = N->getValueType(0);
14994
14995   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14996   // 8-bit integer abs to NEG and CMOV.
14997   if (VT.isInteger() && VT.getSizeInBits() == 8)
14998     return SDValue();
14999
15000   SDValue N0 = N->getOperand(0);
15001   SDValue N1 = N->getOperand(1);
15002   DebugLoc DL = N->getDebugLoc();
15003
15004   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15005   // and change it to SUB and CMOV.
15006   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15007       N0.getOpcode() == ISD::ADD &&
15008       N0.getOperand(1) == N1 &&
15009       N1.getOpcode() == ISD::SRA &&
15010       N1.getOperand(0) == N0.getOperand(0))
15011     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15012       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15013         // Generate SUB & CMOV.
15014         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15015                                   DAG.getConstant(0, VT), N0.getOperand(0));
15016
15017         SDValue Ops[] = { N0.getOperand(0), Neg,
15018                           DAG.getConstant(X86::COND_GE, MVT::i8),
15019                           SDValue(Neg.getNode(), 1) };
15020         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15021                            Ops, array_lengthof(Ops));
15022       }
15023   return SDValue();
15024 }
15025
15026 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15027 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15028                                  TargetLowering::DAGCombinerInfo &DCI,
15029                                  const X86Subtarget *Subtarget) {
15030   if (DCI.isBeforeLegalizeOps())
15031     return SDValue();
15032
15033   if (Subtarget->hasCMov()) {
15034     SDValue RV = performIntegerAbsCombine(N, DAG);
15035     if (RV.getNode())
15036       return RV;
15037   }
15038
15039   // Try forming BMI if it is available.
15040   if (!Subtarget->hasBMI())
15041     return SDValue();
15042
15043   EVT VT = N->getValueType(0);
15044
15045   if (VT != MVT::i32 && VT != MVT::i64)
15046     return SDValue();
15047
15048   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15049
15050   // Create BLSMSK instructions by finding X ^ (X-1)
15051   SDValue N0 = N->getOperand(0);
15052   SDValue N1 = N->getOperand(1);
15053   DebugLoc DL = N->getDebugLoc();
15054
15055   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15056       isAllOnes(N0.getOperand(1)))
15057     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15058
15059   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15060       isAllOnes(N1.getOperand(1)))
15061     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15062
15063   return SDValue();
15064 }
15065
15066 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15067 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15068                                   TargetLowering::DAGCombinerInfo &DCI,
15069                                   const X86Subtarget *Subtarget) {
15070   LoadSDNode *Ld = cast<LoadSDNode>(N);
15071   EVT RegVT = Ld->getValueType(0);
15072   EVT MemVT = Ld->getMemoryVT();
15073   DebugLoc dl = Ld->getDebugLoc();
15074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15075
15076   ISD::LoadExtType Ext = Ld->getExtensionType();
15077
15078   // If this is a vector EXT Load then attempt to optimize it using a
15079   // shuffle. We need SSE4 for the shuffles.
15080   // TODO: It is possible to support ZExt by zeroing the undef values
15081   // during the shuffle phase or after the shuffle.
15082   if (RegVT.isVector() && RegVT.isInteger() &&
15083       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15084     assert(MemVT != RegVT && "Cannot extend to the same type");
15085     assert(MemVT.isVector() && "Must load a vector from memory");
15086
15087     unsigned NumElems = RegVT.getVectorNumElements();
15088     unsigned RegSz = RegVT.getSizeInBits();
15089     unsigned MemSz = MemVT.getSizeInBits();
15090     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15091
15092     // All sizes must be a power of two.
15093     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15094       return SDValue();
15095
15096     // Attempt to load the original value using scalar loads.
15097     // Find the largest scalar type that divides the total loaded size.
15098     MVT SclrLoadTy = MVT::i8;
15099     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15100          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15101       MVT Tp = (MVT::SimpleValueType)tp;
15102       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15103         SclrLoadTy = Tp;
15104       }
15105     }
15106
15107     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15108     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15109         (64 <= MemSz))
15110       SclrLoadTy = MVT::f64;
15111
15112     // Calculate the number of scalar loads that we need to perform
15113     // in order to load our vector from memory.
15114     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15115
15116     // Represent our vector as a sequence of elements which are the
15117     // largest scalar that we can load.
15118     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15119       RegSz/SclrLoadTy.getSizeInBits());
15120
15121     // Represent the data using the same element type that is stored in
15122     // memory. In practice, we ''widen'' MemVT.
15123     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15124                                   RegSz/MemVT.getScalarType().getSizeInBits());
15125
15126     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15127       "Invalid vector type");
15128
15129     // We can't shuffle using an illegal type.
15130     if (!TLI.isTypeLegal(WideVecVT))
15131       return SDValue();
15132
15133     SmallVector<SDValue, 8> Chains;
15134     SDValue Ptr = Ld->getBasePtr();
15135     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15136                                         TLI.getPointerTy());
15137     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15138
15139     for (unsigned i = 0; i < NumLoads; ++i) {
15140       // Perform a single load.
15141       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15142                                        Ptr, Ld->getPointerInfo(),
15143                                        Ld->isVolatile(), Ld->isNonTemporal(),
15144                                        Ld->isInvariant(), Ld->getAlignment());
15145       Chains.push_back(ScalarLoad.getValue(1));
15146       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15147       // another round of DAGCombining.
15148       if (i == 0)
15149         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15150       else
15151         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15152                           ScalarLoad, DAG.getIntPtrConstant(i));
15153
15154       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15155     }
15156
15157     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15158                                Chains.size());
15159
15160     // Bitcast the loaded value to a vector of the original element type, in
15161     // the size of the target vector type.
15162     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15163     unsigned SizeRatio = RegSz/MemSz;
15164
15165     // Redistribute the loaded elements into the different locations.
15166     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15167     for (unsigned i = 0; i != NumElems; ++i)
15168       ShuffleVec[i*SizeRatio] = i;
15169
15170     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15171                                          DAG.getUNDEF(WideVecVT),
15172                                          &ShuffleVec[0]);
15173
15174     // Bitcast to the requested type.
15175     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15176     // Replace the original load with the new sequence
15177     // and return the new chain.
15178     return DCI.CombineTo(N, Shuff, TF, true);
15179   }
15180
15181   return SDValue();
15182 }
15183
15184 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15185 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15186                                    const X86Subtarget *Subtarget) {
15187   StoreSDNode *St = cast<StoreSDNode>(N);
15188   EVT VT = St->getValue().getValueType();
15189   EVT StVT = St->getMemoryVT();
15190   DebugLoc dl = St->getDebugLoc();
15191   SDValue StoredVal = St->getOperand(1);
15192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15193
15194   // If we are saving a concatenation of two XMM registers, perform two stores.
15195   // On Sandy Bridge, 256-bit memory operations are executed by two
15196   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15197   // memory  operation.
15198   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15199       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15200       StoredVal.getNumOperands() == 2) {
15201     SDValue Value0 = StoredVal.getOperand(0);
15202     SDValue Value1 = StoredVal.getOperand(1);
15203
15204     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15205     SDValue Ptr0 = St->getBasePtr();
15206     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15207
15208     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15209                                 St->getPointerInfo(), St->isVolatile(),
15210                                 St->isNonTemporal(), St->getAlignment());
15211     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15212                                 St->getPointerInfo(), St->isVolatile(),
15213                                 St->isNonTemporal(), St->getAlignment());
15214     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15215   }
15216
15217   // Optimize trunc store (of multiple scalars) to shuffle and store.
15218   // First, pack all of the elements in one place. Next, store to memory
15219   // in fewer chunks.
15220   if (St->isTruncatingStore() && VT.isVector()) {
15221     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15222     unsigned NumElems = VT.getVectorNumElements();
15223     assert(StVT != VT && "Cannot truncate to the same type");
15224     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15225     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15226
15227     // From, To sizes and ElemCount must be pow of two
15228     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15229     // We are going to use the original vector elt for storing.
15230     // Accumulated smaller vector elements must be a multiple of the store size.
15231     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15232
15233     unsigned SizeRatio  = FromSz / ToSz;
15234
15235     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15236
15237     // Create a type on which we perform the shuffle
15238     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15239             StVT.getScalarType(), NumElems*SizeRatio);
15240
15241     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15242
15243     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15244     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15245     for (unsigned i = 0; i != NumElems; ++i)
15246       ShuffleVec[i] = i * SizeRatio;
15247
15248     // Can't shuffle using an illegal type.
15249     if (!TLI.isTypeLegal(WideVecVT))
15250       return SDValue();
15251
15252     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15253                                          DAG.getUNDEF(WideVecVT),
15254                                          &ShuffleVec[0]);
15255     // At this point all of the data is stored at the bottom of the
15256     // register. We now need to save it to mem.
15257
15258     // Find the largest store unit
15259     MVT StoreType = MVT::i8;
15260     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15261          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15262       MVT Tp = (MVT::SimpleValueType)tp;
15263       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15264         StoreType = Tp;
15265     }
15266
15267     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15268     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15269         (64 <= NumElems * ToSz))
15270       StoreType = MVT::f64;
15271
15272     // Bitcast the original vector into a vector of store-size units
15273     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15274             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15275     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15276     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15277     SmallVector<SDValue, 8> Chains;
15278     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15279                                         TLI.getPointerTy());
15280     SDValue Ptr = St->getBasePtr();
15281
15282     // Perform one or more big stores into memory.
15283     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15284       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15285                                    StoreType, ShuffWide,
15286                                    DAG.getIntPtrConstant(i));
15287       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15288                                 St->getPointerInfo(), St->isVolatile(),
15289                                 St->isNonTemporal(), St->getAlignment());
15290       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15291       Chains.push_back(Ch);
15292     }
15293
15294     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15295                                Chains.size());
15296   }
15297
15298
15299   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15300   // the FP state in cases where an emms may be missing.
15301   // A preferable solution to the general problem is to figure out the right
15302   // places to insert EMMS.  This qualifies as a quick hack.
15303
15304   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15305   if (VT.getSizeInBits() != 64)
15306     return SDValue();
15307
15308   const Function *F = DAG.getMachineFunction().getFunction();
15309   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15310   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15311                      && Subtarget->hasSSE2();
15312   if ((VT.isVector() ||
15313        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15314       isa<LoadSDNode>(St->getValue()) &&
15315       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15316       St->getChain().hasOneUse() && !St->isVolatile()) {
15317     SDNode* LdVal = St->getValue().getNode();
15318     LoadSDNode *Ld = 0;
15319     int TokenFactorIndex = -1;
15320     SmallVector<SDValue, 8> Ops;
15321     SDNode* ChainVal = St->getChain().getNode();
15322     // Must be a store of a load.  We currently handle two cases:  the load
15323     // is a direct child, and it's under an intervening TokenFactor.  It is
15324     // possible to dig deeper under nested TokenFactors.
15325     if (ChainVal == LdVal)
15326       Ld = cast<LoadSDNode>(St->getChain());
15327     else if (St->getValue().hasOneUse() &&
15328              ChainVal->getOpcode() == ISD::TokenFactor) {
15329       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15330         if (ChainVal->getOperand(i).getNode() == LdVal) {
15331           TokenFactorIndex = i;
15332           Ld = cast<LoadSDNode>(St->getValue());
15333         } else
15334           Ops.push_back(ChainVal->getOperand(i));
15335       }
15336     }
15337
15338     if (!Ld || !ISD::isNormalLoad(Ld))
15339       return SDValue();
15340
15341     // If this is not the MMX case, i.e. we are just turning i64 load/store
15342     // into f64 load/store, avoid the transformation if there are multiple
15343     // uses of the loaded value.
15344     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15345       return SDValue();
15346
15347     DebugLoc LdDL = Ld->getDebugLoc();
15348     DebugLoc StDL = N->getDebugLoc();
15349     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15350     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15351     // pair instead.
15352     if (Subtarget->is64Bit() || F64IsLegal) {
15353       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15354       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15355                                   Ld->getPointerInfo(), Ld->isVolatile(),
15356                                   Ld->isNonTemporal(), Ld->isInvariant(),
15357                                   Ld->getAlignment());
15358       SDValue NewChain = NewLd.getValue(1);
15359       if (TokenFactorIndex != -1) {
15360         Ops.push_back(NewChain);
15361         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15362                                Ops.size());
15363       }
15364       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15365                           St->getPointerInfo(),
15366                           St->isVolatile(), St->isNonTemporal(),
15367                           St->getAlignment());
15368     }
15369
15370     // Otherwise, lower to two pairs of 32-bit loads / stores.
15371     SDValue LoAddr = Ld->getBasePtr();
15372     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15373                                  DAG.getConstant(4, MVT::i32));
15374
15375     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15376                                Ld->getPointerInfo(),
15377                                Ld->isVolatile(), Ld->isNonTemporal(),
15378                                Ld->isInvariant(), Ld->getAlignment());
15379     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15380                                Ld->getPointerInfo().getWithOffset(4),
15381                                Ld->isVolatile(), Ld->isNonTemporal(),
15382                                Ld->isInvariant(),
15383                                MinAlign(Ld->getAlignment(), 4));
15384
15385     SDValue NewChain = LoLd.getValue(1);
15386     if (TokenFactorIndex != -1) {
15387       Ops.push_back(LoLd);
15388       Ops.push_back(HiLd);
15389       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15390                              Ops.size());
15391     }
15392
15393     LoAddr = St->getBasePtr();
15394     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15395                          DAG.getConstant(4, MVT::i32));
15396
15397     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15398                                 St->getPointerInfo(),
15399                                 St->isVolatile(), St->isNonTemporal(),
15400                                 St->getAlignment());
15401     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15402                                 St->getPointerInfo().getWithOffset(4),
15403                                 St->isVolatile(),
15404                                 St->isNonTemporal(),
15405                                 MinAlign(St->getAlignment(), 4));
15406     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15407   }
15408   return SDValue();
15409 }
15410
15411 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15412 /// and return the operands for the horizontal operation in LHS and RHS.  A
15413 /// horizontal operation performs the binary operation on successive elements
15414 /// of its first operand, then on successive elements of its second operand,
15415 /// returning the resulting values in a vector.  For example, if
15416 ///   A = < float a0, float a1, float a2, float a3 >
15417 /// and
15418 ///   B = < float b0, float b1, float b2, float b3 >
15419 /// then the result of doing a horizontal operation on A and B is
15420 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15421 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15422 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15423 /// set to A, RHS to B, and the routine returns 'true'.
15424 /// Note that the binary operation should have the property that if one of the
15425 /// operands is UNDEF then the result is UNDEF.
15426 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15427   // Look for the following pattern: if
15428   //   A = < float a0, float a1, float a2, float a3 >
15429   //   B = < float b0, float b1, float b2, float b3 >
15430   // and
15431   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15432   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15433   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15434   // which is A horizontal-op B.
15435
15436   // At least one of the operands should be a vector shuffle.
15437   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15438       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15439     return false;
15440
15441   EVT VT = LHS.getValueType();
15442
15443   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15444          "Unsupported vector type for horizontal add/sub");
15445
15446   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15447   // operate independently on 128-bit lanes.
15448   unsigned NumElts = VT.getVectorNumElements();
15449   unsigned NumLanes = VT.getSizeInBits()/128;
15450   unsigned NumLaneElts = NumElts / NumLanes;
15451   assert((NumLaneElts % 2 == 0) &&
15452          "Vector type should have an even number of elements in each lane");
15453   unsigned HalfLaneElts = NumLaneElts/2;
15454
15455   // View LHS in the form
15456   //   LHS = VECTOR_SHUFFLE A, B, LMask
15457   // If LHS is not a shuffle then pretend it is the shuffle
15458   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15459   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15460   // type VT.
15461   SDValue A, B;
15462   SmallVector<int, 16> LMask(NumElts);
15463   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15464     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15465       A = LHS.getOperand(0);
15466     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15467       B = LHS.getOperand(1);
15468     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15469     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15470   } else {
15471     if (LHS.getOpcode() != ISD::UNDEF)
15472       A = LHS;
15473     for (unsigned i = 0; i != NumElts; ++i)
15474       LMask[i] = i;
15475   }
15476
15477   // Likewise, view RHS in the form
15478   //   RHS = VECTOR_SHUFFLE C, D, RMask
15479   SDValue C, D;
15480   SmallVector<int, 16> RMask(NumElts);
15481   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15482     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15483       C = RHS.getOperand(0);
15484     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15485       D = RHS.getOperand(1);
15486     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15487     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15488   } else {
15489     if (RHS.getOpcode() != ISD::UNDEF)
15490       C = RHS;
15491     for (unsigned i = 0; i != NumElts; ++i)
15492       RMask[i] = i;
15493   }
15494
15495   // Check that the shuffles are both shuffling the same vectors.
15496   if (!(A == C && B == D) && !(A == D && B == C))
15497     return false;
15498
15499   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15500   if (!A.getNode() && !B.getNode())
15501     return false;
15502
15503   // If A and B occur in reverse order in RHS, then "swap" them (which means
15504   // rewriting the mask).
15505   if (A != C)
15506     CommuteVectorShuffleMask(RMask, NumElts);
15507
15508   // At this point LHS and RHS are equivalent to
15509   //   LHS = VECTOR_SHUFFLE A, B, LMask
15510   //   RHS = VECTOR_SHUFFLE A, B, RMask
15511   // Check that the masks correspond to performing a horizontal operation.
15512   for (unsigned i = 0; i != NumElts; ++i) {
15513     int LIdx = LMask[i], RIdx = RMask[i];
15514
15515     // Ignore any UNDEF components.
15516     if (LIdx < 0 || RIdx < 0 ||
15517         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15518         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15519       continue;
15520
15521     // Check that successive elements are being operated on.  If not, this is
15522     // not a horizontal operation.
15523     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15524     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15525     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15526     if (!(LIdx == Index && RIdx == Index + 1) &&
15527         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15528       return false;
15529   }
15530
15531   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15532   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15533   return true;
15534 }
15535
15536 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15537 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15538                                   const X86Subtarget *Subtarget) {
15539   EVT VT = N->getValueType(0);
15540   SDValue LHS = N->getOperand(0);
15541   SDValue RHS = N->getOperand(1);
15542
15543   // Try to synthesize horizontal adds from adds of shuffles.
15544   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15545        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15546       isHorizontalBinOp(LHS, RHS, true))
15547     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15548   return SDValue();
15549 }
15550
15551 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15552 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15553                                   const X86Subtarget *Subtarget) {
15554   EVT VT = N->getValueType(0);
15555   SDValue LHS = N->getOperand(0);
15556   SDValue RHS = N->getOperand(1);
15557
15558   // Try to synthesize horizontal subs from subs of shuffles.
15559   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15560        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15561       isHorizontalBinOp(LHS, RHS, false))
15562     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15563   return SDValue();
15564 }
15565
15566 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15567 /// X86ISD::FXOR nodes.
15568 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15569   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15570   // F[X]OR(0.0, x) -> x
15571   // F[X]OR(x, 0.0) -> x
15572   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15573     if (C->getValueAPF().isPosZero())
15574       return N->getOperand(1);
15575   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15576     if (C->getValueAPF().isPosZero())
15577       return N->getOperand(0);
15578   return SDValue();
15579 }
15580
15581 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15582 /// X86ISD::FMAX nodes.
15583 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15584   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15585
15586   // Only perform optimizations if UnsafeMath is used.
15587   if (!DAG.getTarget().Options.UnsafeFPMath)
15588     return SDValue();
15589
15590   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15591   // into FMINC and FMAXC, which are Commutative operations.
15592   unsigned NewOp = 0;
15593   switch (N->getOpcode()) {
15594     default: llvm_unreachable("unknown opcode");
15595     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15596     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15597   }
15598
15599   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15600                      N->getOperand(0), N->getOperand(1));
15601 }
15602
15603
15604 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15605 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15606   // FAND(0.0, x) -> 0.0
15607   // FAND(x, 0.0) -> 0.0
15608   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15609     if (C->getValueAPF().isPosZero())
15610       return N->getOperand(0);
15611   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15612     if (C->getValueAPF().isPosZero())
15613       return N->getOperand(1);
15614   return SDValue();
15615 }
15616
15617 static SDValue PerformBTCombine(SDNode *N,
15618                                 SelectionDAG &DAG,
15619                                 TargetLowering::DAGCombinerInfo &DCI) {
15620   // BT ignores high bits in the bit index operand.
15621   SDValue Op1 = N->getOperand(1);
15622   if (Op1.hasOneUse()) {
15623     unsigned BitWidth = Op1.getValueSizeInBits();
15624     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15625     APInt KnownZero, KnownOne;
15626     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15627                                           !DCI.isBeforeLegalizeOps());
15628     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15629     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15630         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15631       DCI.CommitTargetLoweringOpt(TLO);
15632   }
15633   return SDValue();
15634 }
15635
15636 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15637   SDValue Op = N->getOperand(0);
15638   if (Op.getOpcode() == ISD::BITCAST)
15639     Op = Op.getOperand(0);
15640   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15641   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15642       VT.getVectorElementType().getSizeInBits() ==
15643       OpVT.getVectorElementType().getSizeInBits()) {
15644     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15645   }
15646   return SDValue();
15647 }
15648
15649 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15650                                   TargetLowering::DAGCombinerInfo &DCI,
15651                                   const X86Subtarget *Subtarget) {
15652   if (!DCI.isBeforeLegalizeOps())
15653     return SDValue();
15654
15655   if (!Subtarget->hasAVX())
15656     return SDValue();
15657
15658   EVT VT = N->getValueType(0);
15659   SDValue Op = N->getOperand(0);
15660   EVT OpVT = Op.getValueType();
15661   DebugLoc dl = N->getDebugLoc();
15662
15663   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15664       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15665
15666     if (Subtarget->hasAVX2())
15667       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15668
15669     // Optimize vectors in AVX mode
15670     // Sign extend  v8i16 to v8i32 and
15671     //              v4i32 to v4i64
15672     //
15673     // Divide input vector into two parts
15674     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15675     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15676     // concat the vectors to original VT
15677
15678     unsigned NumElems = OpVT.getVectorNumElements();
15679     SDValue Undef = DAG.getUNDEF(OpVT);
15680
15681     SmallVector<int,8> ShufMask1(NumElems, -1);
15682     for (unsigned i = 0; i != NumElems/2; ++i)
15683       ShufMask1[i] = i;
15684
15685     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15686
15687     SmallVector<int,8> ShufMask2(NumElems, -1);
15688     for (unsigned i = 0; i != NumElems/2; ++i)
15689       ShufMask2[i] = i + NumElems/2;
15690
15691     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15692
15693     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15694                                   VT.getVectorNumElements()/2);
15695
15696     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15697     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15698
15699     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15700   }
15701   return SDValue();
15702 }
15703
15704 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15705                                  const X86Subtarget* Subtarget) {
15706   DebugLoc dl = N->getDebugLoc();
15707   EVT VT = N->getValueType(0);
15708
15709   // Let legalize expand this if it isn't a legal type yet.
15710   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15711     return SDValue();
15712
15713   EVT ScalarVT = VT.getScalarType();
15714   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15715       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15716     return SDValue();
15717
15718   SDValue A = N->getOperand(0);
15719   SDValue B = N->getOperand(1);
15720   SDValue C = N->getOperand(2);
15721
15722   bool NegA = (A.getOpcode() == ISD::FNEG);
15723   bool NegB = (B.getOpcode() == ISD::FNEG);
15724   bool NegC = (C.getOpcode() == ISD::FNEG);
15725
15726   // Negative multiplication when NegA xor NegB
15727   bool NegMul = (NegA != NegB);
15728   if (NegA)
15729     A = A.getOperand(0);
15730   if (NegB)
15731     B = B.getOperand(0);
15732   if (NegC)
15733     C = C.getOperand(0);
15734
15735   unsigned Opcode;
15736   if (!NegMul)
15737     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15738   else
15739     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15740
15741   return DAG.getNode(Opcode, dl, VT, A, B, C);
15742 }
15743
15744 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15745                                   TargetLowering::DAGCombinerInfo &DCI,
15746                                   const X86Subtarget *Subtarget) {
15747   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15748   //           (and (i32 x86isd::setcc_carry), 1)
15749   // This eliminates the zext. This transformation is necessary because
15750   // ISD::SETCC is always legalized to i8.
15751   DebugLoc dl = N->getDebugLoc();
15752   SDValue N0 = N->getOperand(0);
15753   EVT VT = N->getValueType(0);
15754   EVT OpVT = N0.getValueType();
15755
15756   if (N0.getOpcode() == ISD::AND &&
15757       N0.hasOneUse() &&
15758       N0.getOperand(0).hasOneUse()) {
15759     SDValue N00 = N0.getOperand(0);
15760     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15761       return SDValue();
15762     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15763     if (!C || C->getZExtValue() != 1)
15764       return SDValue();
15765     return DAG.getNode(ISD::AND, dl, VT,
15766                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15767                                    N00.getOperand(0), N00.getOperand(1)),
15768                        DAG.getConstant(1, VT));
15769   }
15770
15771   // Optimize vectors in AVX mode:
15772   //
15773   //   v8i16 -> v8i32
15774   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15775   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15776   //   Concat upper and lower parts.
15777   //
15778   //   v4i32 -> v4i64
15779   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15780   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15781   //   Concat upper and lower parts.
15782   //
15783   if (!DCI.isBeforeLegalizeOps())
15784     return SDValue();
15785
15786   if (!Subtarget->hasAVX())
15787     return SDValue();
15788
15789   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15790       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15791
15792     if (Subtarget->hasAVX2())
15793       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15794
15795     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15796     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15797     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15798
15799     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15800                                VT.getVectorNumElements()/2);
15801
15802     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15803     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15804
15805     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15806   }
15807
15808   return SDValue();
15809 }
15810
15811 // Optimize x == -y --> x+y == 0
15812 //          x != -y --> x+y != 0
15813 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15814   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15815   SDValue LHS = N->getOperand(0);
15816   SDValue RHS = N->getOperand(1);
15817
15818   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15819     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15820       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15821         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15822                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15823         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15824                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15825       }
15826   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15827     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15828       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15829         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15830                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15831         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15832                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15833       }
15834   return SDValue();
15835 }
15836
15837 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15838 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15839                                    TargetLowering::DAGCombinerInfo &DCI,
15840                                    const X86Subtarget *Subtarget) {
15841   DebugLoc DL = N->getDebugLoc();
15842   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15843   SDValue EFLAGS = N->getOperand(1);
15844
15845   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15846   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15847   // cases.
15848   if (CC == X86::COND_B)
15849     return DAG.getNode(ISD::AND, DL, MVT::i8,
15850                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15851                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15852                        DAG.getConstant(1, MVT::i8));
15853
15854   SDValue Flags;
15855
15856   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15857   if (Flags.getNode()) {
15858     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15859     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15860   }
15861
15862   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15863   if (Flags.getNode()) {
15864     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15865     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15866   }
15867
15868   return SDValue();
15869 }
15870
15871 // Optimize branch condition evaluation.
15872 //
15873 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15874                                     TargetLowering::DAGCombinerInfo &DCI,
15875                                     const X86Subtarget *Subtarget) {
15876   DebugLoc DL = N->getDebugLoc();
15877   SDValue Chain = N->getOperand(0);
15878   SDValue Dest = N->getOperand(1);
15879   SDValue EFLAGS = N->getOperand(3);
15880   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15881
15882   SDValue Flags;
15883
15884   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15885   if (Flags.getNode()) {
15886     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15887     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15888                        Flags);
15889   }
15890
15891   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15892   if (Flags.getNode()) {
15893     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15894     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15895                        Flags);
15896   }
15897
15898   return SDValue();
15899 }
15900
15901 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15902   SDValue Op0 = N->getOperand(0);
15903   EVT InVT = Op0->getValueType(0);
15904
15905   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15906   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15907     DebugLoc dl = N->getDebugLoc();
15908     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15909     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15910     // Notice that we use SINT_TO_FP because we know that the high bits
15911     // are zero and SINT_TO_FP is better supported by the hardware.
15912     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15913   }
15914
15915   return SDValue();
15916 }
15917
15918 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15919                                         const X86TargetLowering *XTLI) {
15920   SDValue Op0 = N->getOperand(0);
15921   EVT InVT = Op0->getValueType(0);
15922
15923   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15924   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15925     DebugLoc dl = N->getDebugLoc();
15926     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15927     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15928     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15929   }
15930
15931   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15932   // a 32-bit target where SSE doesn't support i64->FP operations.
15933   if (Op0.getOpcode() == ISD::LOAD) {
15934     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15935     EVT VT = Ld->getValueType(0);
15936     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15937         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15938         !XTLI->getSubtarget()->is64Bit() &&
15939         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15940       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15941                                           Ld->getChain(), Op0, DAG);
15942       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15943       return FILDChain;
15944     }
15945   }
15946   return SDValue();
15947 }
15948
15949 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15950   EVT VT = N->getValueType(0);
15951
15952   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15953   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15954     DebugLoc dl = N->getDebugLoc();
15955     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15956     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15957     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15958   }
15959
15960   return SDValue();
15961 }
15962
15963 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15964 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15965                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15966   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15967   // the result is either zero or one (depending on the input carry bit).
15968   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15969   if (X86::isZeroNode(N->getOperand(0)) &&
15970       X86::isZeroNode(N->getOperand(1)) &&
15971       // We don't have a good way to replace an EFLAGS use, so only do this when
15972       // dead right now.
15973       SDValue(N, 1).use_empty()) {
15974     DebugLoc DL = N->getDebugLoc();
15975     EVT VT = N->getValueType(0);
15976     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15977     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15978                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15979                                            DAG.getConstant(X86::COND_B,MVT::i8),
15980                                            N->getOperand(2)),
15981                                DAG.getConstant(1, VT));
15982     return DCI.CombineTo(N, Res1, CarryOut);
15983   }
15984
15985   return SDValue();
15986 }
15987
15988 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15989 //      (add Y, (setne X, 0)) -> sbb -1, Y
15990 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15991 //      (sub (setne X, 0), Y) -> adc -1, Y
15992 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15993   DebugLoc DL = N->getDebugLoc();
15994
15995   // Look through ZExts.
15996   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15997   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15998     return SDValue();
15999
16000   SDValue SetCC = Ext.getOperand(0);
16001   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16002     return SDValue();
16003
16004   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16005   if (CC != X86::COND_E && CC != X86::COND_NE)
16006     return SDValue();
16007
16008   SDValue Cmp = SetCC.getOperand(1);
16009   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16010       !X86::isZeroNode(Cmp.getOperand(1)) ||
16011       !Cmp.getOperand(0).getValueType().isInteger())
16012     return SDValue();
16013
16014   SDValue CmpOp0 = Cmp.getOperand(0);
16015   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16016                                DAG.getConstant(1, CmpOp0.getValueType()));
16017
16018   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16019   if (CC == X86::COND_NE)
16020     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16021                        DL, OtherVal.getValueType(), OtherVal,
16022                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16023   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16024                      DL, OtherVal.getValueType(), OtherVal,
16025                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16026 }
16027
16028 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16029 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16030                                  const X86Subtarget *Subtarget) {
16031   EVT VT = N->getValueType(0);
16032   SDValue Op0 = N->getOperand(0);
16033   SDValue Op1 = N->getOperand(1);
16034
16035   // Try to synthesize horizontal adds from adds of shuffles.
16036   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16037        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16038       isHorizontalBinOp(Op0, Op1, true))
16039     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16040
16041   return OptimizeConditionalInDecrement(N, DAG);
16042 }
16043
16044 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16045                                  const X86Subtarget *Subtarget) {
16046   SDValue Op0 = N->getOperand(0);
16047   SDValue Op1 = N->getOperand(1);
16048
16049   // X86 can't encode an immediate LHS of a sub. See if we can push the
16050   // negation into a preceding instruction.
16051   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16052     // If the RHS of the sub is a XOR with one use and a constant, invert the
16053     // immediate. Then add one to the LHS of the sub so we can turn
16054     // X-Y -> X+~Y+1, saving one register.
16055     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16056         isa<ConstantSDNode>(Op1.getOperand(1))) {
16057       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16058       EVT VT = Op0.getValueType();
16059       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16060                                    Op1.getOperand(0),
16061                                    DAG.getConstant(~XorC, VT));
16062       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16063                          DAG.getConstant(C->getAPIntValue()+1, VT));
16064     }
16065   }
16066
16067   // Try to synthesize horizontal adds from adds of shuffles.
16068   EVT VT = N->getValueType(0);
16069   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16070        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16071       isHorizontalBinOp(Op0, Op1, true))
16072     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16073
16074   return OptimizeConditionalInDecrement(N, DAG);
16075 }
16076
16077 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16078                                              DAGCombinerInfo &DCI) const {
16079   SelectionDAG &DAG = DCI.DAG;
16080   switch (N->getOpcode()) {
16081   default: break;
16082   case ISD::EXTRACT_VECTOR_ELT:
16083     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16084   case ISD::VSELECT:
16085   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16086   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16087   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16088   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16089   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16090   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16091   case ISD::SHL:
16092   case ISD::SRA:
16093   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16094   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16095   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16096   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16097   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16098   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16099   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16100   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16101   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16102   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16103   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16104   case X86ISD::FXOR:
16105   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16106   case X86ISD::FMIN:
16107   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16108   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16109   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16110   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16111   case ISD::ANY_EXTEND:
16112   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16113   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16114   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16115   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16116   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16117   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16118   case X86ISD::SHUFP:       // Handle all target specific shuffles
16119   case X86ISD::PALIGN:
16120   case X86ISD::UNPCKH:
16121   case X86ISD::UNPCKL:
16122   case X86ISD::MOVHLPS:
16123   case X86ISD::MOVLHPS:
16124   case X86ISD::PSHUFD:
16125   case X86ISD::PSHUFHW:
16126   case X86ISD::PSHUFLW:
16127   case X86ISD::MOVSS:
16128   case X86ISD::MOVSD:
16129   case X86ISD::VPERMILP:
16130   case X86ISD::VPERM2X128:
16131   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16132   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16133   }
16134
16135   return SDValue();
16136 }
16137
16138 /// isTypeDesirableForOp - Return true if the target has native support for
16139 /// the specified value type and it is 'desirable' to use the type for the
16140 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16141 /// instruction encodings are longer and some i16 instructions are slow.
16142 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16143   if (!isTypeLegal(VT))
16144     return false;
16145   if (VT != MVT::i16)
16146     return true;
16147
16148   switch (Opc) {
16149   default:
16150     return true;
16151   case ISD::LOAD:
16152   case ISD::SIGN_EXTEND:
16153   case ISD::ZERO_EXTEND:
16154   case ISD::ANY_EXTEND:
16155   case ISD::SHL:
16156   case ISD::SRL:
16157   case ISD::SUB:
16158   case ISD::ADD:
16159   case ISD::MUL:
16160   case ISD::AND:
16161   case ISD::OR:
16162   case ISD::XOR:
16163     return false;
16164   }
16165 }
16166
16167 /// IsDesirableToPromoteOp - This method query the target whether it is
16168 /// beneficial for dag combiner to promote the specified node. If true, it
16169 /// should return the desired promotion type by reference.
16170 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16171   EVT VT = Op.getValueType();
16172   if (VT != MVT::i16)
16173     return false;
16174
16175   bool Promote = false;
16176   bool Commute = false;
16177   switch (Op.getOpcode()) {
16178   default: break;
16179   case ISD::LOAD: {
16180     LoadSDNode *LD = cast<LoadSDNode>(Op);
16181     // If the non-extending load has a single use and it's not live out, then it
16182     // might be folded.
16183     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16184                                                      Op.hasOneUse()*/) {
16185       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16186              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16187         // The only case where we'd want to promote LOAD (rather then it being
16188         // promoted as an operand is when it's only use is liveout.
16189         if (UI->getOpcode() != ISD::CopyToReg)
16190           return false;
16191       }
16192     }
16193     Promote = true;
16194     break;
16195   }
16196   case ISD::SIGN_EXTEND:
16197   case ISD::ZERO_EXTEND:
16198   case ISD::ANY_EXTEND:
16199     Promote = true;
16200     break;
16201   case ISD::SHL:
16202   case ISD::SRL: {
16203     SDValue N0 = Op.getOperand(0);
16204     // Look out for (store (shl (load), x)).
16205     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16206       return false;
16207     Promote = true;
16208     break;
16209   }
16210   case ISD::ADD:
16211   case ISD::MUL:
16212   case ISD::AND:
16213   case ISD::OR:
16214   case ISD::XOR:
16215     Commute = true;
16216     // fallthrough
16217   case ISD::SUB: {
16218     SDValue N0 = Op.getOperand(0);
16219     SDValue N1 = Op.getOperand(1);
16220     if (!Commute && MayFoldLoad(N1))
16221       return false;
16222     // Avoid disabling potential load folding opportunities.
16223     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16224       return false;
16225     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16226       return false;
16227     Promote = true;
16228   }
16229   }
16230
16231   PVT = MVT::i32;
16232   return Promote;
16233 }
16234
16235 //===----------------------------------------------------------------------===//
16236 //                           X86 Inline Assembly Support
16237 //===----------------------------------------------------------------------===//
16238
16239 namespace {
16240   // Helper to match a string separated by whitespace.
16241   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16242     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16243
16244     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16245       StringRef piece(*args[i]);
16246       if (!s.startswith(piece)) // Check if the piece matches.
16247         return false;
16248
16249       s = s.substr(piece.size());
16250       StringRef::size_type pos = s.find_first_not_of(" \t");
16251       if (pos == 0) // We matched a prefix.
16252         return false;
16253
16254       s = s.substr(pos);
16255     }
16256
16257     return s.empty();
16258   }
16259   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16260 }
16261
16262 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16263   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16264
16265   std::string AsmStr = IA->getAsmString();
16266
16267   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16268   if (!Ty || Ty->getBitWidth() % 16 != 0)
16269     return false;
16270
16271   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16272   SmallVector<StringRef, 4> AsmPieces;
16273   SplitString(AsmStr, AsmPieces, ";\n");
16274
16275   switch (AsmPieces.size()) {
16276   default: return false;
16277   case 1:
16278     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16279     // we will turn this bswap into something that will be lowered to logical
16280     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16281     // lower so don't worry about this.
16282     // bswap $0
16283     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16284         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16285         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16286         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16287         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16288         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16289       // No need to check constraints, nothing other than the equivalent of
16290       // "=r,0" would be valid here.
16291       return IntrinsicLowering::LowerToByteSwap(CI);
16292     }
16293
16294     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16295     if (CI->getType()->isIntegerTy(16) &&
16296         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16297         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16298          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16299       AsmPieces.clear();
16300       const std::string &ConstraintsStr = IA->getConstraintString();
16301       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16302       std::sort(AsmPieces.begin(), AsmPieces.end());
16303       if (AsmPieces.size() == 4 &&
16304           AsmPieces[0] == "~{cc}" &&
16305           AsmPieces[1] == "~{dirflag}" &&
16306           AsmPieces[2] == "~{flags}" &&
16307           AsmPieces[3] == "~{fpsr}")
16308       return IntrinsicLowering::LowerToByteSwap(CI);
16309     }
16310     break;
16311   case 3:
16312     if (CI->getType()->isIntegerTy(32) &&
16313         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16314         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16315         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16316         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16317       AsmPieces.clear();
16318       const std::string &ConstraintsStr = IA->getConstraintString();
16319       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16320       std::sort(AsmPieces.begin(), AsmPieces.end());
16321       if (AsmPieces.size() == 4 &&
16322           AsmPieces[0] == "~{cc}" &&
16323           AsmPieces[1] == "~{dirflag}" &&
16324           AsmPieces[2] == "~{flags}" &&
16325           AsmPieces[3] == "~{fpsr}")
16326         return IntrinsicLowering::LowerToByteSwap(CI);
16327     }
16328
16329     if (CI->getType()->isIntegerTy(64)) {
16330       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16331       if (Constraints.size() >= 2 &&
16332           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16333           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16334         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16335         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16336             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16337             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16338           return IntrinsicLowering::LowerToByteSwap(CI);
16339       }
16340     }
16341     break;
16342   }
16343   return false;
16344 }
16345
16346
16347
16348 /// getConstraintType - Given a constraint letter, return the type of
16349 /// constraint it is for this target.
16350 X86TargetLowering::ConstraintType
16351 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16352   if (Constraint.size() == 1) {
16353     switch (Constraint[0]) {
16354     case 'R':
16355     case 'q':
16356     case 'Q':
16357     case 'f':
16358     case 't':
16359     case 'u':
16360     case 'y':
16361     case 'x':
16362     case 'Y':
16363     case 'l':
16364       return C_RegisterClass;
16365     case 'a':
16366     case 'b':
16367     case 'c':
16368     case 'd':
16369     case 'S':
16370     case 'D':
16371     case 'A':
16372       return C_Register;
16373     case 'I':
16374     case 'J':
16375     case 'K':
16376     case 'L':
16377     case 'M':
16378     case 'N':
16379     case 'G':
16380     case 'C':
16381     case 'e':
16382     case 'Z':
16383       return C_Other;
16384     default:
16385       break;
16386     }
16387   }
16388   return TargetLowering::getConstraintType(Constraint);
16389 }
16390
16391 /// Examine constraint type and operand type and determine a weight value.
16392 /// This object must already have been set up with the operand type
16393 /// and the current alternative constraint selected.
16394 TargetLowering::ConstraintWeight
16395   X86TargetLowering::getSingleConstraintMatchWeight(
16396     AsmOperandInfo &info, const char *constraint) const {
16397   ConstraintWeight weight = CW_Invalid;
16398   Value *CallOperandVal = info.CallOperandVal;
16399     // If we don't have a value, we can't do a match,
16400     // but allow it at the lowest weight.
16401   if (CallOperandVal == NULL)
16402     return CW_Default;
16403   Type *type = CallOperandVal->getType();
16404   // Look at the constraint type.
16405   switch (*constraint) {
16406   default:
16407     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16408   case 'R':
16409   case 'q':
16410   case 'Q':
16411   case 'a':
16412   case 'b':
16413   case 'c':
16414   case 'd':
16415   case 'S':
16416   case 'D':
16417   case 'A':
16418     if (CallOperandVal->getType()->isIntegerTy())
16419       weight = CW_SpecificReg;
16420     break;
16421   case 'f':
16422   case 't':
16423   case 'u':
16424       if (type->isFloatingPointTy())
16425         weight = CW_SpecificReg;
16426       break;
16427   case 'y':
16428       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16429         weight = CW_SpecificReg;
16430       break;
16431   case 'x':
16432   case 'Y':
16433     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16434         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16435       weight = CW_Register;
16436     break;
16437   case 'I':
16438     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16439       if (C->getZExtValue() <= 31)
16440         weight = CW_Constant;
16441     }
16442     break;
16443   case 'J':
16444     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16445       if (C->getZExtValue() <= 63)
16446         weight = CW_Constant;
16447     }
16448     break;
16449   case 'K':
16450     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16451       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16452         weight = CW_Constant;
16453     }
16454     break;
16455   case 'L':
16456     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16457       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16458         weight = CW_Constant;
16459     }
16460     break;
16461   case 'M':
16462     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16463       if (C->getZExtValue() <= 3)
16464         weight = CW_Constant;
16465     }
16466     break;
16467   case 'N':
16468     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16469       if (C->getZExtValue() <= 0xff)
16470         weight = CW_Constant;
16471     }
16472     break;
16473   case 'G':
16474   case 'C':
16475     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16476       weight = CW_Constant;
16477     }
16478     break;
16479   case 'e':
16480     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16481       if ((C->getSExtValue() >= -0x80000000LL) &&
16482           (C->getSExtValue() <= 0x7fffffffLL))
16483         weight = CW_Constant;
16484     }
16485     break;
16486   case 'Z':
16487     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16488       if (C->getZExtValue() <= 0xffffffff)
16489         weight = CW_Constant;
16490     }
16491     break;
16492   }
16493   return weight;
16494 }
16495
16496 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16497 /// with another that has more specific requirements based on the type of the
16498 /// corresponding operand.
16499 const char *X86TargetLowering::
16500 LowerXConstraint(EVT ConstraintVT) const {
16501   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16502   // 'f' like normal targets.
16503   if (ConstraintVT.isFloatingPoint()) {
16504     if (Subtarget->hasSSE2())
16505       return "Y";
16506     if (Subtarget->hasSSE1())
16507       return "x";
16508   }
16509
16510   return TargetLowering::LowerXConstraint(ConstraintVT);
16511 }
16512
16513 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16514 /// vector.  If it is invalid, don't add anything to Ops.
16515 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16516                                                      std::string &Constraint,
16517                                                      std::vector<SDValue>&Ops,
16518                                                      SelectionDAG &DAG) const {
16519   SDValue Result(0, 0);
16520
16521   // Only support length 1 constraints for now.
16522   if (Constraint.length() > 1) return;
16523
16524   char ConstraintLetter = Constraint[0];
16525   switch (ConstraintLetter) {
16526   default: break;
16527   case 'I':
16528     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16529       if (C->getZExtValue() <= 31) {
16530         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16531         break;
16532       }
16533     }
16534     return;
16535   case 'J':
16536     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16537       if (C->getZExtValue() <= 63) {
16538         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16539         break;
16540       }
16541     }
16542     return;
16543   case 'K':
16544     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16545       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16546         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16547         break;
16548       }
16549     }
16550     return;
16551   case 'N':
16552     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16553       if (C->getZExtValue() <= 255) {
16554         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16555         break;
16556       }
16557     }
16558     return;
16559   case 'e': {
16560     // 32-bit signed value
16561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16562       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16563                                            C->getSExtValue())) {
16564         // Widen to 64 bits here to get it sign extended.
16565         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16566         break;
16567       }
16568     // FIXME gcc accepts some relocatable values here too, but only in certain
16569     // memory models; it's complicated.
16570     }
16571     return;
16572   }
16573   case 'Z': {
16574     // 32-bit unsigned value
16575     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16576       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16577                                            C->getZExtValue())) {
16578         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16579         break;
16580       }
16581     }
16582     // FIXME gcc accepts some relocatable values here too, but only in certain
16583     // memory models; it's complicated.
16584     return;
16585   }
16586   case 'i': {
16587     // Literal immediates are always ok.
16588     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16589       // Widen to 64 bits here to get it sign extended.
16590       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16591       break;
16592     }
16593
16594     // In any sort of PIC mode addresses need to be computed at runtime by
16595     // adding in a register or some sort of table lookup.  These can't
16596     // be used as immediates.
16597     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16598       return;
16599
16600     // If we are in non-pic codegen mode, we allow the address of a global (with
16601     // an optional displacement) to be used with 'i'.
16602     GlobalAddressSDNode *GA = 0;
16603     int64_t Offset = 0;
16604
16605     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16606     while (1) {
16607       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16608         Offset += GA->getOffset();
16609         break;
16610       } else if (Op.getOpcode() == ISD::ADD) {
16611         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16612           Offset += C->getZExtValue();
16613           Op = Op.getOperand(0);
16614           continue;
16615         }
16616       } else if (Op.getOpcode() == ISD::SUB) {
16617         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16618           Offset += -C->getZExtValue();
16619           Op = Op.getOperand(0);
16620           continue;
16621         }
16622       }
16623
16624       // Otherwise, this isn't something we can handle, reject it.
16625       return;
16626     }
16627
16628     const GlobalValue *GV = GA->getGlobal();
16629     // If we require an extra load to get this address, as in PIC mode, we
16630     // can't accept it.
16631     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16632                                                         getTargetMachine())))
16633       return;
16634
16635     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16636                                         GA->getValueType(0), Offset);
16637     break;
16638   }
16639   }
16640
16641   if (Result.getNode()) {
16642     Ops.push_back(Result);
16643     return;
16644   }
16645   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16646 }
16647
16648 std::pair<unsigned, const TargetRegisterClass*>
16649 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16650                                                 EVT VT) const {
16651   // First, see if this is a constraint that directly corresponds to an LLVM
16652   // register class.
16653   if (Constraint.size() == 1) {
16654     // GCC Constraint Letters
16655     switch (Constraint[0]) {
16656     default: break;
16657       // TODO: Slight differences here in allocation order and leaving
16658       // RIP in the class. Do they matter any more here than they do
16659       // in the normal allocation?
16660     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16661       if (Subtarget->is64Bit()) {
16662         if (VT == MVT::i32 || VT == MVT::f32)
16663           return std::make_pair(0U, &X86::GR32RegClass);
16664         if (VT == MVT::i16)
16665           return std::make_pair(0U, &X86::GR16RegClass);
16666         if (VT == MVT::i8 || VT == MVT::i1)
16667           return std::make_pair(0U, &X86::GR8RegClass);
16668         if (VT == MVT::i64 || VT == MVT::f64)
16669           return std::make_pair(0U, &X86::GR64RegClass);
16670         break;
16671       }
16672       // 32-bit fallthrough
16673     case 'Q':   // Q_REGS
16674       if (VT == MVT::i32 || VT == MVT::f32)
16675         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16676       if (VT == MVT::i16)
16677         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16678       if (VT == MVT::i8 || VT == MVT::i1)
16679         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16680       if (VT == MVT::i64)
16681         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16682       break;
16683     case 'r':   // GENERAL_REGS
16684     case 'l':   // INDEX_REGS
16685       if (VT == MVT::i8 || VT == MVT::i1)
16686         return std::make_pair(0U, &X86::GR8RegClass);
16687       if (VT == MVT::i16)
16688         return std::make_pair(0U, &X86::GR16RegClass);
16689       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16690         return std::make_pair(0U, &X86::GR32RegClass);
16691       return std::make_pair(0U, &X86::GR64RegClass);
16692     case 'R':   // LEGACY_REGS
16693       if (VT == MVT::i8 || VT == MVT::i1)
16694         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16695       if (VT == MVT::i16)
16696         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16697       if (VT == MVT::i32 || !Subtarget->is64Bit())
16698         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16699       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16700     case 'f':  // FP Stack registers.
16701       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16702       // value to the correct fpstack register class.
16703       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16704         return std::make_pair(0U, &X86::RFP32RegClass);
16705       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16706         return std::make_pair(0U, &X86::RFP64RegClass);
16707       return std::make_pair(0U, &X86::RFP80RegClass);
16708     case 'y':   // MMX_REGS if MMX allowed.
16709       if (!Subtarget->hasMMX()) break;
16710       return std::make_pair(0U, &X86::VR64RegClass);
16711     case 'Y':   // SSE_REGS if SSE2 allowed
16712       if (!Subtarget->hasSSE2()) break;
16713       // FALL THROUGH.
16714     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16715       if (!Subtarget->hasSSE1()) break;
16716
16717       switch (VT.getSimpleVT().SimpleTy) {
16718       default: break;
16719       // Scalar SSE types.
16720       case MVT::f32:
16721       case MVT::i32:
16722         return std::make_pair(0U, &X86::FR32RegClass);
16723       case MVT::f64:
16724       case MVT::i64:
16725         return std::make_pair(0U, &X86::FR64RegClass);
16726       // Vector types.
16727       case MVT::v16i8:
16728       case MVT::v8i16:
16729       case MVT::v4i32:
16730       case MVT::v2i64:
16731       case MVT::v4f32:
16732       case MVT::v2f64:
16733         return std::make_pair(0U, &X86::VR128RegClass);
16734       // AVX types.
16735       case MVT::v32i8:
16736       case MVT::v16i16:
16737       case MVT::v8i32:
16738       case MVT::v4i64:
16739       case MVT::v8f32:
16740       case MVT::v4f64:
16741         return std::make_pair(0U, &X86::VR256RegClass);
16742       }
16743       break;
16744     }
16745   }
16746
16747   // Use the default implementation in TargetLowering to convert the register
16748   // constraint into a member of a register class.
16749   std::pair<unsigned, const TargetRegisterClass*> Res;
16750   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16751
16752   // Not found as a standard register?
16753   if (Res.second == 0) {
16754     // Map st(0) -> st(7) -> ST0
16755     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16756         tolower(Constraint[1]) == 's' &&
16757         tolower(Constraint[2]) == 't' &&
16758         Constraint[3] == '(' &&
16759         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16760         Constraint[5] == ')' &&
16761         Constraint[6] == '}') {
16762
16763       Res.first = X86::ST0+Constraint[4]-'0';
16764       Res.second = &X86::RFP80RegClass;
16765       return Res;
16766     }
16767
16768     // GCC allows "st(0)" to be called just plain "st".
16769     if (StringRef("{st}").equals_lower(Constraint)) {
16770       Res.first = X86::ST0;
16771       Res.second = &X86::RFP80RegClass;
16772       return Res;
16773     }
16774
16775     // flags -> EFLAGS
16776     if (StringRef("{flags}").equals_lower(Constraint)) {
16777       Res.first = X86::EFLAGS;
16778       Res.second = &X86::CCRRegClass;
16779       return Res;
16780     }
16781
16782     // 'A' means EAX + EDX.
16783     if (Constraint == "A") {
16784       Res.first = X86::EAX;
16785       Res.second = &X86::GR32_ADRegClass;
16786       return Res;
16787     }
16788     return Res;
16789   }
16790
16791   // Otherwise, check to see if this is a register class of the wrong value
16792   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16793   // turn into {ax},{dx}.
16794   if (Res.second->hasType(VT))
16795     return Res;   // Correct type already, nothing to do.
16796
16797   // All of the single-register GCC register classes map their values onto
16798   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16799   // really want an 8-bit or 32-bit register, map to the appropriate register
16800   // class and return the appropriate register.
16801   if (Res.second == &X86::GR16RegClass) {
16802     if (VT == MVT::i8) {
16803       unsigned DestReg = 0;
16804       switch (Res.first) {
16805       default: break;
16806       case X86::AX: DestReg = X86::AL; break;
16807       case X86::DX: DestReg = X86::DL; break;
16808       case X86::CX: DestReg = X86::CL; break;
16809       case X86::BX: DestReg = X86::BL; break;
16810       }
16811       if (DestReg) {
16812         Res.first = DestReg;
16813         Res.second = &X86::GR8RegClass;
16814       }
16815     } else if (VT == MVT::i32) {
16816       unsigned DestReg = 0;
16817       switch (Res.first) {
16818       default: break;
16819       case X86::AX: DestReg = X86::EAX; break;
16820       case X86::DX: DestReg = X86::EDX; break;
16821       case X86::CX: DestReg = X86::ECX; break;
16822       case X86::BX: DestReg = X86::EBX; break;
16823       case X86::SI: DestReg = X86::ESI; break;
16824       case X86::DI: DestReg = X86::EDI; break;
16825       case X86::BP: DestReg = X86::EBP; break;
16826       case X86::SP: DestReg = X86::ESP; break;
16827       }
16828       if (DestReg) {
16829         Res.first = DestReg;
16830         Res.second = &X86::GR32RegClass;
16831       }
16832     } else if (VT == MVT::i64) {
16833       unsigned DestReg = 0;
16834       switch (Res.first) {
16835       default: break;
16836       case X86::AX: DestReg = X86::RAX; break;
16837       case X86::DX: DestReg = X86::RDX; break;
16838       case X86::CX: DestReg = X86::RCX; break;
16839       case X86::BX: DestReg = X86::RBX; break;
16840       case X86::SI: DestReg = X86::RSI; break;
16841       case X86::DI: DestReg = X86::RDI; break;
16842       case X86::BP: DestReg = X86::RBP; break;
16843       case X86::SP: DestReg = X86::RSP; break;
16844       }
16845       if (DestReg) {
16846         Res.first = DestReg;
16847         Res.second = &X86::GR64RegClass;
16848       }
16849     }
16850   } else if (Res.second == &X86::FR32RegClass ||
16851              Res.second == &X86::FR64RegClass ||
16852              Res.second == &X86::VR128RegClass) {
16853     // Handle references to XMM physical registers that got mapped into the
16854     // wrong class.  This can happen with constraints like {xmm0} where the
16855     // target independent register mapper will just pick the first match it can
16856     // find, ignoring the required type.
16857
16858     if (VT == MVT::f32 || VT == MVT::i32)
16859       Res.second = &X86::FR32RegClass;
16860     else if (VT == MVT::f64 || VT == MVT::i64)
16861       Res.second = &X86::FR64RegClass;
16862     else if (X86::VR128RegClass.hasType(VT))
16863       Res.second = &X86::VR128RegClass;
16864     else if (X86::VR256RegClass.hasType(VT))
16865       Res.second = &X86::VR256RegClass;
16866   }
16867
16868   return Res;
16869 }