0e6e4a3294b493e134b3c30615271174e46715cb
[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::f32  , Expand);
651       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
652       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
653       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
654     }
655     addLegalFPImmediate(APFloat(+0.0)); // FLD0
656     addLegalFPImmediate(APFloat(+1.0)); // FLD1
657     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
658     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
659     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
660     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
661     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
662     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
663   }
664
665   // We don't support FMA.
666   setOperationAction(ISD::FMA, MVT::f64, Expand);
667   setOperationAction(ISD::FMA, MVT::f32, Expand);
668
669   // Long double always uses X87.
670   if (!TM.Options.UseSoftFloat) {
671     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
672     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
673     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
674     {
675       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
676       addLegalFPImmediate(TmpFlt);  // FLD0
677       TmpFlt.changeSign();
678       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
679
680       bool ignored;
681       APFloat TmpFlt2(+1.0);
682       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
683                       &ignored);
684       addLegalFPImmediate(TmpFlt2);  // FLD1
685       TmpFlt2.changeSign();
686       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
687     }
688
689     if (!TM.Options.UnsafeFPMath) {
690       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
691       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
692     }
693
694     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
695     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
696     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
697     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
698     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
699     setOperationAction(ISD::FMA, MVT::f80, Expand);
700   }
701
702   // Always use a library call for pow.
703   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
704   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
705   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
706
707   setOperationAction(ISD::FLOG, MVT::f80, Expand);
708   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
709   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
710   setOperationAction(ISD::FEXP, MVT::f80, Expand);
711   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
712
713   // First set operation action for all vector types to either promote
714   // (for widening) or expand (for scalarization). Then we will selectively
715   // turn on ones that can be effectively codegen'd.
716   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
717            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
718     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
733     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
735     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
736     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
772     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
777     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
778              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
779       setTruncStoreAction((MVT::SimpleValueType)VT,
780                           (MVT::SimpleValueType)InnerVT, Expand);
781     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
782     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
783     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
784   }
785
786   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
787   // with -msoft-float, disable use of MMX as well.
788   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
789     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
790     // No operations on x86mmx supported, everything uses intrinsics.
791   }
792
793   // MMX-sized vectors (other than x86mmx) are expected to be expanded
794   // into smaller operations.
795   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
796   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
797   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
798   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
799   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
800   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
801   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
802   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
803   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
804   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
805   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
806   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
807   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
808   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
809   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
810   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
811   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
812   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
813   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
814   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
815   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
816   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
817   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
818   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
819   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
820   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
821   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
822   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
823   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
824
825   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
826     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
827
828     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
829     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
830     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
831     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
832     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
833     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
834     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
835     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
836     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
837     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
838     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
839     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
840   }
841
842   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
843     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
844
845     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
846     // registers cannot be used even for integer operations.
847     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
848     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
849     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
850     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
851
852     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
853     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
854     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
855     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
856     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
857     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
858     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
859     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
860     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
861     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
862     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
863     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
864     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
865     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
866     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
867     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
868     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
869
870     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
871     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
872     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
873     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
874
875     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
876     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
877     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
878     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
879     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
880
881     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
882     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
883       MVT VT = (MVT::SimpleValueType)i;
884       // Do not attempt to custom lower non-power-of-2 vectors
885       if (!isPowerOf2_32(VT.getVectorNumElements()))
886         continue;
887       // Do not attempt to custom lower non-128-bit vectors
888       if (!VT.is128BitVector())
889         continue;
890       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
891       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
892       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
893     }
894
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
896     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
898     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
899     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
900     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
901
902     if (Subtarget->is64Bit()) {
903       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
904       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
905     }
906
907     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
908     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
909       MVT VT = (MVT::SimpleValueType)i;
910
911       // Do not attempt to promote non-128-bit vectors
912       if (!VT.is128BitVector())
913         continue;
914
915       setOperationAction(ISD::AND,    VT, Promote);
916       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
917       setOperationAction(ISD::OR,     VT, Promote);
918       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
919       setOperationAction(ISD::XOR,    VT, Promote);
920       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
921       setOperationAction(ISD::LOAD,   VT, Promote);
922       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
923       setOperationAction(ISD::SELECT, VT, Promote);
924       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
925     }
926
927     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937
938     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
939   }
940
941   if (Subtarget->hasSSE41()) {
942     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
943     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
944     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
945     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
946     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
947     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
948     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
949     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
950     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
951     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
952
953     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
954     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
955
956     // FIXME: Do we need to handle scalar-to-vector here?
957     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
958
959     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
960     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
961     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
962     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
963     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
964
965     // i8 and i16 vectors are custom , because the source register and source
966     // source memory operand types are not the same width.  f32 vectors are
967     // custom since the immediate controlling the insert encodes additional
968     // information.
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
971     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
972     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
973
974     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
975     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
976     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
977     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
978
979     // FIXME: these should be Legal but thats only for the case where
980     // the index is constant.  For now custom expand to deal with that.
981     if (Subtarget->is64Bit()) {
982       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
983       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
984     }
985   }
986
987   if (Subtarget->hasSSE2()) {
988     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
989     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
990
991     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
992     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
993
994     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
995     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
996
997     if (Subtarget->hasAVX2()) {
998       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
999       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1000
1001       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1002       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1003
1004       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1005     } else {
1006       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1007       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1008
1009       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1010       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1011
1012       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1013     }
1014   }
1015
1016   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1017     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1019     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1021     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1023
1024     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1026     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1027
1028     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1033     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1034     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1035     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1036
1037     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1038     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1039     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1040     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1042     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1043     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1044     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1045
1046     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1047     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1048     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1049
1050     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1051
1052     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1053     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1054
1055     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1056     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1057
1058     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1059     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1060
1061     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1062     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1063     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1064     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1065
1066     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1067     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1068     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1069
1070     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1071     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1072     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1073     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1074
1075     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1076       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1077       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1078       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1079       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1080       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1081       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1082     }
1083
1084     if (Subtarget->hasAVX2()) {
1085       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1086       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1087       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1088       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1089
1090       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1091       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1092       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1093       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1094
1095       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1097       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1098       // Don't lower v32i8 because there is no 128-bit byte mul
1099
1100       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1101
1102       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1103       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1104
1105       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1106       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1107
1108       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1109     } else {
1110       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1112       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1113       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1114
1115       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1117       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1118       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1119
1120       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1121       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1122       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1123       // Don't lower v32i8 because there is no 128-bit byte mul
1124
1125       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1126       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1127
1128       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1129       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1130
1131       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1132     }
1133
1134     // Custom lower several nodes for 256-bit types.
1135     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1136              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1137       MVT VT = (MVT::SimpleValueType)i;
1138
1139       // Extract subvector is special because the value type
1140       // (result) is 128-bit but the source is 256-bit wide.
1141       if (VT.is128BitVector())
1142         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1143
1144       // Do not attempt to custom lower other non-256-bit vectors
1145       if (!VT.is256BitVector())
1146         continue;
1147
1148       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1149       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1150       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1151       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1152       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1153       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1154       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1155     }
1156
1157     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1158     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1159       MVT VT = (MVT::SimpleValueType)i;
1160
1161       // Do not attempt to promote non-256-bit vectors
1162       if (!VT.is256BitVector())
1163         continue;
1164
1165       setOperationAction(ISD::AND,    VT, Promote);
1166       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1167       setOperationAction(ISD::OR,     VT, Promote);
1168       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1169       setOperationAction(ISD::XOR,    VT, Promote);
1170       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1171       setOperationAction(ISD::LOAD,   VT, Promote);
1172       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1173       setOperationAction(ISD::SELECT, VT, Promote);
1174       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1175     }
1176   }
1177
1178   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1179   // of this type with custom code.
1180   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1181            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1182     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1183                        Custom);
1184   }
1185
1186   // We want to custom lower some of our intrinsics.
1187   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1188   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1189
1190
1191   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1192   // handle type legalization for these operations here.
1193   //
1194   // FIXME: We really should do custom legalization for addition and
1195   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1196   // than generic legalization for 64-bit multiplication-with-overflow, though.
1197   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1198     // Add/Sub/Mul with overflow operations are custom lowered.
1199     MVT VT = IntVTs[i];
1200     setOperationAction(ISD::SADDO, VT, Custom);
1201     setOperationAction(ISD::UADDO, VT, Custom);
1202     setOperationAction(ISD::SSUBO, VT, Custom);
1203     setOperationAction(ISD::USUBO, VT, Custom);
1204     setOperationAction(ISD::SMULO, VT, Custom);
1205     setOperationAction(ISD::UMULO, VT, Custom);
1206   }
1207
1208   // There are no 8-bit 3-address imul/mul instructions
1209   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1210   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1211
1212   if (!Subtarget->is64Bit()) {
1213     // These libcalls are not available in 32-bit.
1214     setLibcallName(RTLIB::SHL_I128, 0);
1215     setLibcallName(RTLIB::SRL_I128, 0);
1216     setLibcallName(RTLIB::SRA_I128, 0);
1217   }
1218
1219   // We have target-specific dag combine patterns for the following nodes:
1220   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1221   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1222   setTargetDAGCombine(ISD::VSELECT);
1223   setTargetDAGCombine(ISD::SELECT);
1224   setTargetDAGCombine(ISD::SHL);
1225   setTargetDAGCombine(ISD::SRA);
1226   setTargetDAGCombine(ISD::SRL);
1227   setTargetDAGCombine(ISD::OR);
1228   setTargetDAGCombine(ISD::AND);
1229   setTargetDAGCombine(ISD::ADD);
1230   setTargetDAGCombine(ISD::FADD);
1231   setTargetDAGCombine(ISD::FSUB);
1232   setTargetDAGCombine(ISD::FMA);
1233   setTargetDAGCombine(ISD::SUB);
1234   setTargetDAGCombine(ISD::LOAD);
1235   setTargetDAGCombine(ISD::STORE);
1236   setTargetDAGCombine(ISD::ZERO_EXTEND);
1237   setTargetDAGCombine(ISD::ANY_EXTEND);
1238   setTargetDAGCombine(ISD::SIGN_EXTEND);
1239   setTargetDAGCombine(ISD::TRUNCATE);
1240   setTargetDAGCombine(ISD::UINT_TO_FP);
1241   setTargetDAGCombine(ISD::SINT_TO_FP);
1242   setTargetDAGCombine(ISD::SETCC);
1243   setTargetDAGCombine(ISD::FP_TO_SINT);
1244   if (Subtarget->is64Bit())
1245     setTargetDAGCombine(ISD::MUL);
1246   setTargetDAGCombine(ISD::XOR);
1247
1248   computeRegisterProperties();
1249
1250   // On Darwin, -Os means optimize for size without hurting performance,
1251   // do not reduce the limit.
1252   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1253   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1254   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1255   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1256   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1257   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1258   setPrefLoopAlignment(4); // 2^4 bytes.
1259   benefitFromCodePlacementOpt = true;
1260
1261   // Predictable cmov don't hurt on atom because it's in-order.
1262   predictableSelectIsExpensive = !Subtarget->isAtom();
1263
1264   setPrefFunctionAlignment(4); // 2^4 bytes.
1265 }
1266
1267
1268 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1269   if (!VT.isVector()) return MVT::i8;
1270   return VT.changeVectorElementTypeToInteger();
1271 }
1272
1273
1274 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1275 /// the desired ByVal argument alignment.
1276 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1277   if (MaxAlign == 16)
1278     return;
1279   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1280     if (VTy->getBitWidth() == 128)
1281       MaxAlign = 16;
1282   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1283     unsigned EltAlign = 0;
1284     getMaxByValAlign(ATy->getElementType(), EltAlign);
1285     if (EltAlign > MaxAlign)
1286       MaxAlign = EltAlign;
1287   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1288     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1289       unsigned EltAlign = 0;
1290       getMaxByValAlign(STy->getElementType(i), EltAlign);
1291       if (EltAlign > MaxAlign)
1292         MaxAlign = EltAlign;
1293       if (MaxAlign == 16)
1294         break;
1295     }
1296   }
1297 }
1298
1299 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1300 /// function arguments in the caller parameter area. For X86, aggregates
1301 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1302 /// are at 4-byte boundaries.
1303 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1304   if (Subtarget->is64Bit()) {
1305     // Max of 8 and alignment of type.
1306     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1307     if (TyAlign > 8)
1308       return TyAlign;
1309     return 8;
1310   }
1311
1312   unsigned Align = 4;
1313   if (Subtarget->hasSSE1())
1314     getMaxByValAlign(Ty, Align);
1315   return Align;
1316 }
1317
1318 /// getOptimalMemOpType - Returns the target specific optimal type for load
1319 /// and store operations as a result of memset, memcpy, and memmove
1320 /// lowering. If DstAlign is zero that means it's safe to destination
1321 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1322 /// means there isn't a need to check it against alignment requirement,
1323 /// probably because the source does not need to be loaded. If
1324 /// 'IsZeroVal' is true, that means it's safe to return a
1325 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1326 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1327 /// constant so it does not need to be loaded.
1328 /// It returns EVT::Other if the type should be determined using generic
1329 /// target-independent logic.
1330 EVT
1331 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1332                                        unsigned DstAlign, unsigned SrcAlign,
1333                                        bool IsZeroVal,
1334                                        bool MemcpyStrSrc,
1335                                        MachineFunction &MF) const {
1336   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1337   // linux.  This is because the stack realignment code can't handle certain
1338   // cases like PR2962.  This should be removed when PR2962 is fixed.
1339   const Function *F = MF.getFunction();
1340   if (IsZeroVal &&
1341       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1342     if (Size >= 16 &&
1343         (Subtarget->isUnalignedMemAccessFast() ||
1344          ((DstAlign == 0 || DstAlign >= 16) &&
1345           (SrcAlign == 0 || SrcAlign >= 16))) &&
1346         Subtarget->getStackAlignment() >= 16) {
1347       if (Subtarget->getStackAlignment() >= 32) {
1348         if (Subtarget->hasAVX2())
1349           return MVT::v8i32;
1350         if (Subtarget->hasAVX())
1351           return MVT::v8f32;
1352       }
1353       if (Subtarget->hasSSE2())
1354         return MVT::v4i32;
1355       if (Subtarget->hasSSE1())
1356         return MVT::v4f32;
1357     } else if (!MemcpyStrSrc && Size >= 8 &&
1358                !Subtarget->is64Bit() &&
1359                Subtarget->getStackAlignment() >= 8 &&
1360                Subtarget->hasSSE2()) {
1361       // Do not use f64 to lower memcpy if source is string constant. It's
1362       // better to use i32 to avoid the loads.
1363       return MVT::f64;
1364     }
1365   }
1366   if (Subtarget->is64Bit() && Size >= 8)
1367     return MVT::i64;
1368   return MVT::i32;
1369 }
1370
1371 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1372 /// current function.  The returned value is a member of the
1373 /// MachineJumpTableInfo::JTEntryKind enum.
1374 unsigned X86TargetLowering::getJumpTableEncoding() const {
1375   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1376   // symbol.
1377   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1378       Subtarget->isPICStyleGOT())
1379     return MachineJumpTableInfo::EK_Custom32;
1380
1381   // Otherwise, use the normal jump table encoding heuristics.
1382   return TargetLowering::getJumpTableEncoding();
1383 }
1384
1385 const MCExpr *
1386 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1387                                              const MachineBasicBlock *MBB,
1388                                              unsigned uid,MCContext &Ctx) const{
1389   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1390          Subtarget->isPICStyleGOT());
1391   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1392   // entries.
1393   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1394                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1395 }
1396
1397 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1398 /// jumptable.
1399 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1400                                                     SelectionDAG &DAG) const {
1401   if (!Subtarget->is64Bit())
1402     // This doesn't have DebugLoc associated with it, but is not really the
1403     // same as a Register.
1404     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1405   return Table;
1406 }
1407
1408 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1409 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1410 /// MCExpr.
1411 const MCExpr *X86TargetLowering::
1412 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1413                              MCContext &Ctx) const {
1414   // X86-64 uses RIP relative addressing based on the jump table label.
1415   if (Subtarget->isPICStyleRIPRel())
1416     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1417
1418   // Otherwise, the reference is relative to the PIC base.
1419   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1420 }
1421
1422 // FIXME: Why this routine is here? Move to RegInfo!
1423 std::pair<const TargetRegisterClass*, uint8_t>
1424 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1425   const TargetRegisterClass *RRC = 0;
1426   uint8_t Cost = 1;
1427   switch (VT.getSimpleVT().SimpleTy) {
1428   default:
1429     return TargetLowering::findRepresentativeClass(VT);
1430   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1431     RRC = Subtarget->is64Bit() ?
1432       (const TargetRegisterClass*)&X86::GR64RegClass :
1433       (const TargetRegisterClass*)&X86::GR32RegClass;
1434     break;
1435   case MVT::x86mmx:
1436     RRC = &X86::VR64RegClass;
1437     break;
1438   case MVT::f32: case MVT::f64:
1439   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1440   case MVT::v4f32: case MVT::v2f64:
1441   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1442   case MVT::v4f64:
1443     RRC = &X86::VR128RegClass;
1444     break;
1445   }
1446   return std::make_pair(RRC, Cost);
1447 }
1448
1449 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1450                                                unsigned &Offset) const {
1451   if (!Subtarget->isTargetLinux())
1452     return false;
1453
1454   if (Subtarget->is64Bit()) {
1455     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1456     Offset = 0x28;
1457     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1458       AddressSpace = 256;
1459     else
1460       AddressSpace = 257;
1461   } else {
1462     // %gs:0x14 on i386
1463     Offset = 0x14;
1464     AddressSpace = 256;
1465   }
1466   return true;
1467 }
1468
1469
1470 //===----------------------------------------------------------------------===//
1471 //               Return Value Calling Convention Implementation
1472 //===----------------------------------------------------------------------===//
1473
1474 #include "X86GenCallingConv.inc"
1475
1476 bool
1477 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1478                                   MachineFunction &MF, bool isVarArg,
1479                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1480                         LLVMContext &Context) const {
1481   SmallVector<CCValAssign, 16> RVLocs;
1482   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1483                  RVLocs, Context);
1484   return CCInfo.CheckReturn(Outs, RetCC_X86);
1485 }
1486
1487 SDValue
1488 X86TargetLowering::LowerReturn(SDValue Chain,
1489                                CallingConv::ID CallConv, bool isVarArg,
1490                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1491                                const SmallVectorImpl<SDValue> &OutVals,
1492                                DebugLoc dl, SelectionDAG &DAG) const {
1493   MachineFunction &MF = DAG.getMachineFunction();
1494   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1495
1496   SmallVector<CCValAssign, 16> RVLocs;
1497   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1498                  RVLocs, *DAG.getContext());
1499   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1500
1501   // Add the regs to the liveout set for the function.
1502   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1503   for (unsigned i = 0; i != RVLocs.size(); ++i)
1504     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1505       MRI.addLiveOut(RVLocs[i].getLocReg());
1506
1507   SDValue Flag;
1508
1509   SmallVector<SDValue, 6> RetOps;
1510   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1511   // Operand #1 = Bytes To Pop
1512   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1513                    MVT::i16));
1514
1515   // Copy the result values into the output registers.
1516   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1517     CCValAssign &VA = RVLocs[i];
1518     assert(VA.isRegLoc() && "Can only return in registers!");
1519     SDValue ValToCopy = OutVals[i];
1520     EVT ValVT = ValToCopy.getValueType();
1521
1522     // Promote values to the appropriate types
1523     if (VA.getLocInfo() == CCValAssign::SExt)
1524       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1525     else if (VA.getLocInfo() == CCValAssign::ZExt)
1526       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1527     else if (VA.getLocInfo() == CCValAssign::AExt)
1528       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1529     else if (VA.getLocInfo() == CCValAssign::BCvt)
1530       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1531
1532     // If this is x86-64, and we disabled SSE, we can't return FP values,
1533     // or SSE or MMX vectors.
1534     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1535          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1536           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1537       report_fatal_error("SSE register return with SSE disabled");
1538     }
1539     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1540     // llvm-gcc has never done it right and no one has noticed, so this
1541     // should be OK for now.
1542     if (ValVT == MVT::f64 &&
1543         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1544       report_fatal_error("SSE2 register return with SSE2 disabled");
1545
1546     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1547     // the RET instruction and handled by the FP Stackifier.
1548     if (VA.getLocReg() == X86::ST0 ||
1549         VA.getLocReg() == X86::ST1) {
1550       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1551       // change the value to the FP stack register class.
1552       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1553         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1554       RetOps.push_back(ValToCopy);
1555       // Don't emit a copytoreg.
1556       continue;
1557     }
1558
1559     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1560     // which is returned in RAX / RDX.
1561     if (Subtarget->is64Bit()) {
1562       if (ValVT == MVT::x86mmx) {
1563         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1564           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1565           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1566                                   ValToCopy);
1567           // If we don't have SSE2 available, convert to v4f32 so the generated
1568           // register is legal.
1569           if (!Subtarget->hasSSE2())
1570             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1571         }
1572       }
1573     }
1574
1575     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1576     Flag = Chain.getValue(1);
1577   }
1578
1579   // The x86-64 ABI for returning structs by value requires that we copy
1580   // the sret argument into %rax for the return. We saved the argument into
1581   // a virtual register in the entry block, so now we copy the value out
1582   // and into %rax.
1583   if (Subtarget->is64Bit() &&
1584       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1585     MachineFunction &MF = DAG.getMachineFunction();
1586     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1587     unsigned Reg = FuncInfo->getSRetReturnReg();
1588     assert(Reg &&
1589            "SRetReturnReg should have been set in LowerFormalArguments().");
1590     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1591
1592     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1593     Flag = Chain.getValue(1);
1594
1595     // RAX now acts like a return value.
1596     MRI.addLiveOut(X86::RAX);
1597   }
1598
1599   RetOps[0] = Chain;  // Update chain.
1600
1601   // Add the flag if we have it.
1602   if (Flag.getNode())
1603     RetOps.push_back(Flag);
1604
1605   return DAG.getNode(X86ISD::RET_FLAG, dl,
1606                      MVT::Other, &RetOps[0], RetOps.size());
1607 }
1608
1609 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1610   if (N->getNumValues() != 1)
1611     return false;
1612   if (!N->hasNUsesOfValue(1, 0))
1613     return false;
1614
1615   SDValue TCChain = Chain;
1616   SDNode *Copy = *N->use_begin();
1617   if (Copy->getOpcode() == ISD::CopyToReg) {
1618     // If the copy has a glue operand, we conservatively assume it isn't safe to
1619     // perform a tail call.
1620     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1621       return false;
1622     TCChain = Copy->getOperand(0);
1623   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1624     return false;
1625
1626   bool HasRet = false;
1627   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1628        UI != UE; ++UI) {
1629     if (UI->getOpcode() != X86ISD::RET_FLAG)
1630       return false;
1631     HasRet = true;
1632   }
1633
1634   if (!HasRet)
1635     return false;
1636
1637   Chain = TCChain;
1638   return true;
1639 }
1640
1641 EVT
1642 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1643                                             ISD::NodeType ExtendKind) const {
1644   MVT ReturnMVT;
1645   // TODO: Is this also valid on 32-bit?
1646   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1647     ReturnMVT = MVT::i8;
1648   else
1649     ReturnMVT = MVT::i32;
1650
1651   EVT MinVT = getRegisterType(Context, ReturnMVT);
1652   return VT.bitsLT(MinVT) ? MinVT : VT;
1653 }
1654
1655 /// LowerCallResult - Lower the result values of a call into the
1656 /// appropriate copies out of appropriate physical registers.
1657 ///
1658 SDValue
1659 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1660                                    CallingConv::ID CallConv, bool isVarArg,
1661                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1662                                    DebugLoc dl, SelectionDAG &DAG,
1663                                    SmallVectorImpl<SDValue> &InVals) const {
1664
1665   // Assign locations to each value returned by this call.
1666   SmallVector<CCValAssign, 16> RVLocs;
1667   bool Is64Bit = Subtarget->is64Bit();
1668   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1669                  getTargetMachine(), RVLocs, *DAG.getContext());
1670   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1671
1672   // Copy all of the result registers out of their specified physreg.
1673   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1674     CCValAssign &VA = RVLocs[i];
1675     EVT CopyVT = VA.getValVT();
1676
1677     // If this is x86-64, and we disabled SSE, we can't return FP values
1678     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1679         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1680       report_fatal_error("SSE register return with SSE disabled");
1681     }
1682
1683     SDValue Val;
1684
1685     // If this is a call to a function that returns an fp value on the floating
1686     // point stack, we must guarantee the value is popped from the stack, so
1687     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1688     // if the return value is not used. We use the FpPOP_RETVAL instruction
1689     // instead.
1690     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1691       // If we prefer to use the value in xmm registers, copy it out as f80 and
1692       // use a truncate to move it from fp stack reg to xmm reg.
1693       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1694       SDValue Ops[] = { Chain, InFlag };
1695       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1696                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1697       Val = Chain.getValue(0);
1698
1699       // Round the f80 to the right size, which also moves it to the appropriate
1700       // xmm register.
1701       if (CopyVT != VA.getValVT())
1702         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1703                           // This truncation won't change the value.
1704                           DAG.getIntPtrConstant(1));
1705     } else {
1706       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1707                                  CopyVT, InFlag).getValue(1);
1708       Val = Chain.getValue(0);
1709     }
1710     InFlag = Chain.getValue(2);
1711     InVals.push_back(Val);
1712   }
1713
1714   return Chain;
1715 }
1716
1717
1718 //===----------------------------------------------------------------------===//
1719 //                C & StdCall & Fast Calling Convention implementation
1720 //===----------------------------------------------------------------------===//
1721 //  StdCall calling convention seems to be standard for many Windows' API
1722 //  routines and around. It differs from C calling convention just a little:
1723 //  callee should clean up the stack, not caller. Symbols should be also
1724 //  decorated in some fancy way :) It doesn't support any vector arguments.
1725 //  For info on fast calling convention see Fast Calling Convention (tail call)
1726 //  implementation LowerX86_32FastCCCallTo.
1727
1728 /// CallIsStructReturn - Determines whether a call uses struct return
1729 /// semantics.
1730 enum StructReturnType {
1731   NotStructReturn,
1732   RegStructReturn,
1733   StackStructReturn
1734 };
1735 static StructReturnType
1736 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1737   if (Outs.empty())
1738     return NotStructReturn;
1739
1740   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1741   if (!Flags.isSRet())
1742     return NotStructReturn;
1743   if (Flags.isInReg())
1744     return RegStructReturn;
1745   return StackStructReturn;
1746 }
1747
1748 /// ArgsAreStructReturn - Determines whether a function uses struct
1749 /// return semantics.
1750 static StructReturnType
1751 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1752   if (Ins.empty())
1753     return NotStructReturn;
1754
1755   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1756   if (!Flags.isSRet())
1757     return NotStructReturn;
1758   if (Flags.isInReg())
1759     return RegStructReturn;
1760   return StackStructReturn;
1761 }
1762
1763 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1764 /// by "Src" to address "Dst" with size and alignment information specified by
1765 /// the specific parameter attribute. The copy will be passed as a byval
1766 /// function parameter.
1767 static SDValue
1768 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1769                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1770                           DebugLoc dl) {
1771   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1772
1773   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1774                        /*isVolatile*/false, /*AlwaysInline=*/true,
1775                        MachinePointerInfo(), MachinePointerInfo());
1776 }
1777
1778 /// IsTailCallConvention - Return true if the calling convention is one that
1779 /// supports tail call optimization.
1780 static bool IsTailCallConvention(CallingConv::ID CC) {
1781   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1782 }
1783
1784 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1785   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1786     return false;
1787
1788   CallSite CS(CI);
1789   CallingConv::ID CalleeCC = CS.getCallingConv();
1790   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1791     return false;
1792
1793   return true;
1794 }
1795
1796 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1797 /// a tailcall target by changing its ABI.
1798 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1799                                    bool GuaranteedTailCallOpt) {
1800   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1801 }
1802
1803 SDValue
1804 X86TargetLowering::LowerMemArgument(SDValue Chain,
1805                                     CallingConv::ID CallConv,
1806                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1807                                     DebugLoc dl, SelectionDAG &DAG,
1808                                     const CCValAssign &VA,
1809                                     MachineFrameInfo *MFI,
1810                                     unsigned i) const {
1811   // Create the nodes corresponding to a load from this parameter slot.
1812   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1813   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1814                               getTargetMachine().Options.GuaranteedTailCallOpt);
1815   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1816   EVT ValVT;
1817
1818   // If value is passed by pointer we have address passed instead of the value
1819   // itself.
1820   if (VA.getLocInfo() == CCValAssign::Indirect)
1821     ValVT = VA.getLocVT();
1822   else
1823     ValVT = VA.getValVT();
1824
1825   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1826   // changed with more analysis.
1827   // In case of tail call optimization mark all arguments mutable. Since they
1828   // could be overwritten by lowering of arguments in case of a tail call.
1829   if (Flags.isByVal()) {
1830     unsigned Bytes = Flags.getByValSize();
1831     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1832     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1833     return DAG.getFrameIndex(FI, getPointerTy());
1834   } else {
1835     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1836                                     VA.getLocMemOffset(), isImmutable);
1837     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1838     return DAG.getLoad(ValVT, dl, Chain, FIN,
1839                        MachinePointerInfo::getFixedStack(FI),
1840                        false, false, false, 0);
1841   }
1842 }
1843
1844 SDValue
1845 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1846                                         CallingConv::ID CallConv,
1847                                         bool isVarArg,
1848                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1849                                         DebugLoc dl,
1850                                         SelectionDAG &DAG,
1851                                         SmallVectorImpl<SDValue> &InVals)
1852                                           const {
1853   MachineFunction &MF = DAG.getMachineFunction();
1854   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1855
1856   const Function* Fn = MF.getFunction();
1857   if (Fn->hasExternalLinkage() &&
1858       Subtarget->isTargetCygMing() &&
1859       Fn->getName() == "main")
1860     FuncInfo->setForceFramePointer(true);
1861
1862   MachineFrameInfo *MFI = MF.getFrameInfo();
1863   bool Is64Bit = Subtarget->is64Bit();
1864   bool IsWindows = Subtarget->isTargetWindows();
1865   bool IsWin64 = Subtarget->isTargetWin64();
1866
1867   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1868          "Var args not supported with calling convention fastcc or ghc");
1869
1870   // Assign locations to all of the incoming arguments.
1871   SmallVector<CCValAssign, 16> ArgLocs;
1872   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1873                  ArgLocs, *DAG.getContext());
1874
1875   // Allocate shadow area for Win64
1876   if (IsWin64) {
1877     CCInfo.AllocateStack(32, 8);
1878   }
1879
1880   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1881
1882   unsigned LastVal = ~0U;
1883   SDValue ArgValue;
1884   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1885     CCValAssign &VA = ArgLocs[i];
1886     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1887     // places.
1888     assert(VA.getValNo() != LastVal &&
1889            "Don't support value assigned to multiple locs yet");
1890     (void)LastVal;
1891     LastVal = VA.getValNo();
1892
1893     if (VA.isRegLoc()) {
1894       EVT RegVT = VA.getLocVT();
1895       const TargetRegisterClass *RC;
1896       if (RegVT == MVT::i32)
1897         RC = &X86::GR32RegClass;
1898       else if (Is64Bit && RegVT == MVT::i64)
1899         RC = &X86::GR64RegClass;
1900       else if (RegVT == MVT::f32)
1901         RC = &X86::FR32RegClass;
1902       else if (RegVT == MVT::f64)
1903         RC = &X86::FR64RegClass;
1904       else if (RegVT.is256BitVector())
1905         RC = &X86::VR256RegClass;
1906       else if (RegVT.is128BitVector())
1907         RC = &X86::VR128RegClass;
1908       else if (RegVT == MVT::x86mmx)
1909         RC = &X86::VR64RegClass;
1910       else
1911         llvm_unreachable("Unknown argument type!");
1912
1913       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1914       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1915
1916       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1917       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1918       // right size.
1919       if (VA.getLocInfo() == CCValAssign::SExt)
1920         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1921                                DAG.getValueType(VA.getValVT()));
1922       else if (VA.getLocInfo() == CCValAssign::ZExt)
1923         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1924                                DAG.getValueType(VA.getValVT()));
1925       else if (VA.getLocInfo() == CCValAssign::BCvt)
1926         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1927
1928       if (VA.isExtInLoc()) {
1929         // Handle MMX values passed in XMM regs.
1930         if (RegVT.isVector()) {
1931           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1932                                  ArgValue);
1933         } else
1934           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1935       }
1936     } else {
1937       assert(VA.isMemLoc());
1938       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1939     }
1940
1941     // If value is passed via pointer - do a load.
1942     if (VA.getLocInfo() == CCValAssign::Indirect)
1943       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1944                              MachinePointerInfo(), false, false, false, 0);
1945
1946     InVals.push_back(ArgValue);
1947   }
1948
1949   // The x86-64 ABI for returning structs by value requires that we copy
1950   // the sret argument into %rax for the return. Save the argument into
1951   // a virtual register so that we can access it from the return points.
1952   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1953     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1954     unsigned Reg = FuncInfo->getSRetReturnReg();
1955     if (!Reg) {
1956       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1957       FuncInfo->setSRetReturnReg(Reg);
1958     }
1959     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1960     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1961   }
1962
1963   unsigned StackSize = CCInfo.getNextStackOffset();
1964   // Align stack specially for tail calls.
1965   if (FuncIsMadeTailCallSafe(CallConv,
1966                              MF.getTarget().Options.GuaranteedTailCallOpt))
1967     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1968
1969   // If the function takes variable number of arguments, make a frame index for
1970   // the start of the first vararg value... for expansion of llvm.va_start.
1971   if (isVarArg) {
1972     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1973                     CallConv != CallingConv::X86_ThisCall)) {
1974       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1975     }
1976     if (Is64Bit) {
1977       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1978
1979       // FIXME: We should really autogenerate these arrays
1980       static const uint16_t GPR64ArgRegsWin64[] = {
1981         X86::RCX, X86::RDX, X86::R8,  X86::R9
1982       };
1983       static const uint16_t GPR64ArgRegs64Bit[] = {
1984         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1985       };
1986       static const uint16_t XMMArgRegs64Bit[] = {
1987         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1988         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1989       };
1990       const uint16_t *GPR64ArgRegs;
1991       unsigned NumXMMRegs = 0;
1992
1993       if (IsWin64) {
1994         // The XMM registers which might contain var arg parameters are shadowed
1995         // in their paired GPR.  So we only need to save the GPR to their home
1996         // slots.
1997         TotalNumIntRegs = 4;
1998         GPR64ArgRegs = GPR64ArgRegsWin64;
1999       } else {
2000         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2001         GPR64ArgRegs = GPR64ArgRegs64Bit;
2002
2003         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2004                                                 TotalNumXMMRegs);
2005       }
2006       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2007                                                        TotalNumIntRegs);
2008
2009       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2010       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2011              "SSE register cannot be used when SSE is disabled!");
2012       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2013                NoImplicitFloatOps) &&
2014              "SSE register cannot be used when SSE is disabled!");
2015       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2016           !Subtarget->hasSSE1())
2017         // Kernel mode asks for SSE to be disabled, so don't push them
2018         // on the stack.
2019         TotalNumXMMRegs = 0;
2020
2021       if (IsWin64) {
2022         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2023         // Get to the caller-allocated home save location.  Add 8 to account
2024         // for the return address.
2025         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2026         FuncInfo->setRegSaveFrameIndex(
2027           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2028         // Fixup to set vararg frame on shadow area (4 x i64).
2029         if (NumIntRegs < 4)
2030           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2031       } else {
2032         // For X86-64, if there are vararg parameters that are passed via
2033         // registers, then we must store them to their spots on the stack so
2034         // they may be loaded by deferencing the result of va_next.
2035         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2036         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2037         FuncInfo->setRegSaveFrameIndex(
2038           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2039                                false));
2040       }
2041
2042       // Store the integer parameter registers.
2043       SmallVector<SDValue, 8> MemOps;
2044       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2045                                         getPointerTy());
2046       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2047       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2048         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2049                                   DAG.getIntPtrConstant(Offset));
2050         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2051                                      &X86::GR64RegClass);
2052         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2053         SDValue Store =
2054           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2055                        MachinePointerInfo::getFixedStack(
2056                          FuncInfo->getRegSaveFrameIndex(), Offset),
2057                        false, false, 0);
2058         MemOps.push_back(Store);
2059         Offset += 8;
2060       }
2061
2062       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2063         // Now store the XMM (fp + vector) parameter registers.
2064         SmallVector<SDValue, 11> SaveXMMOps;
2065         SaveXMMOps.push_back(Chain);
2066
2067         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2068         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2069         SaveXMMOps.push_back(ALVal);
2070
2071         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2072                                FuncInfo->getRegSaveFrameIndex()));
2073         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2074                                FuncInfo->getVarArgsFPOffset()));
2075
2076         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2077           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2078                                        &X86::VR128RegClass);
2079           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2080           SaveXMMOps.push_back(Val);
2081         }
2082         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2083                                      MVT::Other,
2084                                      &SaveXMMOps[0], SaveXMMOps.size()));
2085       }
2086
2087       if (!MemOps.empty())
2088         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2089                             &MemOps[0], MemOps.size());
2090     }
2091   }
2092
2093   // Some CCs need callee pop.
2094   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2095                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2096     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2097   } else {
2098     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2099     // If this is an sret function, the return should pop the hidden pointer.
2100     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2101         argsAreStructReturn(Ins) == StackStructReturn)
2102       FuncInfo->setBytesToPopOnReturn(4);
2103   }
2104
2105   if (!Is64Bit) {
2106     // RegSaveFrameIndex is X86-64 only.
2107     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2108     if (CallConv == CallingConv::X86_FastCall ||
2109         CallConv == CallingConv::X86_ThisCall)
2110       // fastcc functions can't have varargs.
2111       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2112   }
2113
2114   FuncInfo->setArgumentStackSize(StackSize);
2115
2116   return Chain;
2117 }
2118
2119 SDValue
2120 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2121                                     SDValue StackPtr, SDValue Arg,
2122                                     DebugLoc dl, SelectionDAG &DAG,
2123                                     const CCValAssign &VA,
2124                                     ISD::ArgFlagsTy Flags) const {
2125   unsigned LocMemOffset = VA.getLocMemOffset();
2126   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2127   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2128   if (Flags.isByVal())
2129     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2130
2131   return DAG.getStore(Chain, dl, Arg, PtrOff,
2132                       MachinePointerInfo::getStack(LocMemOffset),
2133                       false, false, 0);
2134 }
2135
2136 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2137 /// optimization is performed and it is required.
2138 SDValue
2139 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2140                                            SDValue &OutRetAddr, SDValue Chain,
2141                                            bool IsTailCall, bool Is64Bit,
2142                                            int FPDiff, DebugLoc dl) const {
2143   // Adjust the Return address stack slot.
2144   EVT VT = getPointerTy();
2145   OutRetAddr = getReturnAddressFrameIndex(DAG);
2146
2147   // Load the "old" Return address.
2148   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2149                            false, false, false, 0);
2150   return SDValue(OutRetAddr.getNode(), 1);
2151 }
2152
2153 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2154 /// optimization is performed and it is required (FPDiff!=0).
2155 static SDValue
2156 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2157                          SDValue Chain, SDValue RetAddrFrIdx,
2158                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2159   // Store the return address to the appropriate stack slot.
2160   if (!FPDiff) return Chain;
2161   // Calculate the new stack slot for the return address.
2162   int SlotSize = Is64Bit ? 8 : 4;
2163   int NewReturnAddrFI =
2164     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2165   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2166   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2167   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2168                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2169                        false, false, 0);
2170   return Chain;
2171 }
2172
2173 SDValue
2174 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2175                              SmallVectorImpl<SDValue> &InVals) const {
2176   SelectionDAG &DAG                     = CLI.DAG;
2177   DebugLoc &dl                          = CLI.DL;
2178   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2179   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2180   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2181   SDValue Chain                         = CLI.Chain;
2182   SDValue Callee                        = CLI.Callee;
2183   CallingConv::ID CallConv              = CLI.CallConv;
2184   bool &isTailCall                      = CLI.IsTailCall;
2185   bool isVarArg                         = CLI.IsVarArg;
2186
2187   MachineFunction &MF = DAG.getMachineFunction();
2188   bool Is64Bit        = Subtarget->is64Bit();
2189   bool IsWin64        = Subtarget->isTargetWin64();
2190   bool IsWindows      = Subtarget->isTargetWindows();
2191   StructReturnType SR = callIsStructReturn(Outs);
2192   bool IsSibcall      = false;
2193
2194   if (MF.getTarget().Options.DisableTailCalls)
2195     isTailCall = false;
2196
2197   if (isTailCall) {
2198     // Check if it's really possible to do a tail call.
2199     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2200                     isVarArg, SR != NotStructReturn,
2201                     MF.getFunction()->hasStructRetAttr(),
2202                     Outs, OutVals, Ins, DAG);
2203
2204     // Sibcalls are automatically detected tailcalls which do not require
2205     // ABI changes.
2206     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2207       IsSibcall = true;
2208
2209     if (isTailCall)
2210       ++NumTailCalls;
2211   }
2212
2213   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2214          "Var args not supported with calling convention fastcc or ghc");
2215
2216   // Analyze operands of the call, assigning locations to each operand.
2217   SmallVector<CCValAssign, 16> ArgLocs;
2218   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2219                  ArgLocs, *DAG.getContext());
2220
2221   // Allocate shadow area for Win64
2222   if (IsWin64) {
2223     CCInfo.AllocateStack(32, 8);
2224   }
2225
2226   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2227
2228   // Get a count of how many bytes are to be pushed on the stack.
2229   unsigned NumBytes = CCInfo.getNextStackOffset();
2230   if (IsSibcall)
2231     // This is a sibcall. The memory operands are available in caller's
2232     // own caller's stack.
2233     NumBytes = 0;
2234   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2235            IsTailCallConvention(CallConv))
2236     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2237
2238   int FPDiff = 0;
2239   if (isTailCall && !IsSibcall) {
2240     // Lower arguments at fp - stackoffset + fpdiff.
2241     unsigned NumBytesCallerPushed =
2242       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2243     FPDiff = NumBytesCallerPushed - NumBytes;
2244
2245     // Set the delta of movement of the returnaddr stackslot.
2246     // But only set if delta is greater than previous delta.
2247     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2248       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2249   }
2250
2251   if (!IsSibcall)
2252     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2253
2254   SDValue RetAddrFrIdx;
2255   // Load return address for tail calls.
2256   if (isTailCall && FPDiff)
2257     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2258                                     Is64Bit, FPDiff, dl);
2259
2260   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2261   SmallVector<SDValue, 8> MemOpChains;
2262   SDValue StackPtr;
2263
2264   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2265   // of tail call optimization arguments are handle later.
2266   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2267     CCValAssign &VA = ArgLocs[i];
2268     EVT RegVT = VA.getLocVT();
2269     SDValue Arg = OutVals[i];
2270     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2271     bool isByVal = Flags.isByVal();
2272
2273     // Promote the value if needed.
2274     switch (VA.getLocInfo()) {
2275     default: llvm_unreachable("Unknown loc info!");
2276     case CCValAssign::Full: break;
2277     case CCValAssign::SExt:
2278       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2279       break;
2280     case CCValAssign::ZExt:
2281       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2282       break;
2283     case CCValAssign::AExt:
2284       if (RegVT.is128BitVector()) {
2285         // Special case: passing MMX values in XMM registers.
2286         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2287         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2288         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2289       } else
2290         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2291       break;
2292     case CCValAssign::BCvt:
2293       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2294       break;
2295     case CCValAssign::Indirect: {
2296       // Store the argument.
2297       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2298       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2299       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2300                            MachinePointerInfo::getFixedStack(FI),
2301                            false, false, 0);
2302       Arg = SpillSlot;
2303       break;
2304     }
2305     }
2306
2307     if (VA.isRegLoc()) {
2308       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2309       if (isVarArg && IsWin64) {
2310         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2311         // shadow reg if callee is a varargs function.
2312         unsigned ShadowReg = 0;
2313         switch (VA.getLocReg()) {
2314         case X86::XMM0: ShadowReg = X86::RCX; break;
2315         case X86::XMM1: ShadowReg = X86::RDX; break;
2316         case X86::XMM2: ShadowReg = X86::R8; break;
2317         case X86::XMM3: ShadowReg = X86::R9; break;
2318         }
2319         if (ShadowReg)
2320           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2321       }
2322     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2323       assert(VA.isMemLoc());
2324       if (StackPtr.getNode() == 0)
2325         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2326       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2327                                              dl, DAG, VA, Flags));
2328     }
2329   }
2330
2331   if (!MemOpChains.empty())
2332     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2333                         &MemOpChains[0], MemOpChains.size());
2334
2335   if (Subtarget->isPICStyleGOT()) {
2336     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2337     // GOT pointer.
2338     if (!isTailCall) {
2339       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2340                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2341     } else {
2342       // If we are tail calling and generating PIC/GOT style code load the
2343       // address of the callee into ECX. The value in ecx is used as target of
2344       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2345       // for tail calls on PIC/GOT architectures. Normally we would just put the
2346       // address of GOT into ebx and then call target@PLT. But for tail calls
2347       // ebx would be restored (since ebx is callee saved) before jumping to the
2348       // target@PLT.
2349
2350       // Note: The actual moving to ECX is done further down.
2351       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2352       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2353           !G->getGlobal()->hasProtectedVisibility())
2354         Callee = LowerGlobalAddress(Callee, DAG);
2355       else if (isa<ExternalSymbolSDNode>(Callee))
2356         Callee = LowerExternalSymbol(Callee, DAG);
2357     }
2358   }
2359
2360   if (Is64Bit && isVarArg && !IsWin64) {
2361     // From AMD64 ABI document:
2362     // For calls that may call functions that use varargs or stdargs
2363     // (prototype-less calls or calls to functions containing ellipsis (...) in
2364     // the declaration) %al is used as hidden argument to specify the number
2365     // of SSE registers used. The contents of %al do not need to match exactly
2366     // the number of registers, but must be an ubound on the number of SSE
2367     // registers used and is in the range 0 - 8 inclusive.
2368
2369     // Count the number of XMM registers allocated.
2370     static const uint16_t XMMArgRegs[] = {
2371       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2372       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2373     };
2374     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2375     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2376            && "SSE registers cannot be used when SSE is disabled");
2377
2378     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2379                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2380   }
2381
2382   // For tail calls lower the arguments to the 'real' stack slot.
2383   if (isTailCall) {
2384     // Force all the incoming stack arguments to be loaded from the stack
2385     // before any new outgoing arguments are stored to the stack, because the
2386     // outgoing stack slots may alias the incoming argument stack slots, and
2387     // the alias isn't otherwise explicit. This is slightly more conservative
2388     // than necessary, because it means that each store effectively depends
2389     // on every argument instead of just those arguments it would clobber.
2390     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2391
2392     SmallVector<SDValue, 8> MemOpChains2;
2393     SDValue FIN;
2394     int FI = 0;
2395     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2396       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2397         CCValAssign &VA = ArgLocs[i];
2398         if (VA.isRegLoc())
2399           continue;
2400         assert(VA.isMemLoc());
2401         SDValue Arg = OutVals[i];
2402         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2403         // Create frame index.
2404         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2405         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2406         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2407         FIN = DAG.getFrameIndex(FI, getPointerTy());
2408
2409         if (Flags.isByVal()) {
2410           // Copy relative to framepointer.
2411           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2412           if (StackPtr.getNode() == 0)
2413             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2414                                           getPointerTy());
2415           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2416
2417           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2418                                                            ArgChain,
2419                                                            Flags, DAG, dl));
2420         } else {
2421           // Store relative to framepointer.
2422           MemOpChains2.push_back(
2423             DAG.getStore(ArgChain, dl, Arg, FIN,
2424                          MachinePointerInfo::getFixedStack(FI),
2425                          false, false, 0));
2426         }
2427       }
2428     }
2429
2430     if (!MemOpChains2.empty())
2431       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2432                           &MemOpChains2[0], MemOpChains2.size());
2433
2434     // Store the return address to the appropriate stack slot.
2435     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2436                                      FPDiff, dl);
2437   }
2438
2439   // Build a sequence of copy-to-reg nodes chained together with token chain
2440   // and flag operands which copy the outgoing args into registers.
2441   SDValue InFlag;
2442   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2443     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2444                              RegsToPass[i].second, InFlag);
2445     InFlag = Chain.getValue(1);
2446   }
2447
2448   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2449     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2450     // In the 64-bit large code model, we have to make all calls
2451     // through a register, since the call instruction's 32-bit
2452     // pc-relative offset may not be large enough to hold the whole
2453     // address.
2454   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2455     // If the callee is a GlobalAddress node (quite common, every direct call
2456     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2457     // it.
2458
2459     // We should use extra load for direct calls to dllimported functions in
2460     // non-JIT mode.
2461     const GlobalValue *GV = G->getGlobal();
2462     if (!GV->hasDLLImportLinkage()) {
2463       unsigned char OpFlags = 0;
2464       bool ExtraLoad = false;
2465       unsigned WrapperKind = ISD::DELETED_NODE;
2466
2467       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2468       // external symbols most go through the PLT in PIC mode.  If the symbol
2469       // has hidden or protected visibility, or if it is static or local, then
2470       // we don't need to use the PLT - we can directly call it.
2471       if (Subtarget->isTargetELF() &&
2472           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2473           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2474         OpFlags = X86II::MO_PLT;
2475       } else if (Subtarget->isPICStyleStubAny() &&
2476                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2477                  (!Subtarget->getTargetTriple().isMacOSX() ||
2478                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2479         // PC-relative references to external symbols should go through $stub,
2480         // unless we're building with the leopard linker or later, which
2481         // automatically synthesizes these stubs.
2482         OpFlags = X86II::MO_DARWIN_STUB;
2483       } else if (Subtarget->isPICStyleRIPRel() &&
2484                  isa<Function>(GV) &&
2485                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2486         // If the function is marked as non-lazy, generate an indirect call
2487         // which loads from the GOT directly. This avoids runtime overhead
2488         // at the cost of eager binding (and one extra byte of encoding).
2489         OpFlags = X86II::MO_GOTPCREL;
2490         WrapperKind = X86ISD::WrapperRIP;
2491         ExtraLoad = true;
2492       }
2493
2494       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2495                                           G->getOffset(), OpFlags);
2496
2497       // Add a wrapper if needed.
2498       if (WrapperKind != ISD::DELETED_NODE)
2499         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2500       // Add extra indirection if needed.
2501       if (ExtraLoad)
2502         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2503                              MachinePointerInfo::getGOT(),
2504                              false, false, false, 0);
2505     }
2506   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2507     unsigned char OpFlags = 0;
2508
2509     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2510     // external symbols should go through the PLT.
2511     if (Subtarget->isTargetELF() &&
2512         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2513       OpFlags = X86II::MO_PLT;
2514     } else if (Subtarget->isPICStyleStubAny() &&
2515                (!Subtarget->getTargetTriple().isMacOSX() ||
2516                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2517       // PC-relative references to external symbols should go through $stub,
2518       // unless we're building with the leopard linker or later, which
2519       // automatically synthesizes these stubs.
2520       OpFlags = X86II::MO_DARWIN_STUB;
2521     }
2522
2523     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2524                                          OpFlags);
2525   }
2526
2527   // Returns a chain & a flag for retval copy to use.
2528   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2529   SmallVector<SDValue, 8> Ops;
2530
2531   if (!IsSibcall && isTailCall) {
2532     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2533                            DAG.getIntPtrConstant(0, true), InFlag);
2534     InFlag = Chain.getValue(1);
2535   }
2536
2537   Ops.push_back(Chain);
2538   Ops.push_back(Callee);
2539
2540   if (isTailCall)
2541     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2542
2543   // Add argument registers to the end of the list so that they are known live
2544   // into the call.
2545   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2546     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2547                                   RegsToPass[i].second.getValueType()));
2548
2549   // Add a register mask operand representing the call-preserved registers.
2550   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2551   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2552   assert(Mask && "Missing call preserved mask for calling convention");
2553   Ops.push_back(DAG.getRegisterMask(Mask));
2554
2555   if (InFlag.getNode())
2556     Ops.push_back(InFlag);
2557
2558   if (isTailCall) {
2559     // We used to do:
2560     //// If this is the first return lowered for this function, add the regs
2561     //// to the liveout set for the function.
2562     // This isn't right, although it's probably harmless on x86; liveouts
2563     // should be computed from returns not tail calls.  Consider a void
2564     // function making a tail call to a function returning int.
2565     return DAG.getNode(X86ISD::TC_RETURN, dl,
2566                        NodeTys, &Ops[0], Ops.size());
2567   }
2568
2569   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2570   InFlag = Chain.getValue(1);
2571
2572   // Create the CALLSEQ_END node.
2573   unsigned NumBytesForCalleeToPush;
2574   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2575                        getTargetMachine().Options.GuaranteedTailCallOpt))
2576     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2577   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2578            SR == StackStructReturn)
2579     // If this is a call to a struct-return function, the callee
2580     // pops the hidden struct pointer, so we have to push it back.
2581     // This is common for Darwin/X86, Linux & Mingw32 targets.
2582     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2583     NumBytesForCalleeToPush = 4;
2584   else
2585     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2586
2587   // Returns a flag for retval copy to use.
2588   if (!IsSibcall) {
2589     Chain = DAG.getCALLSEQ_END(Chain,
2590                                DAG.getIntPtrConstant(NumBytes, true),
2591                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2592                                                      true),
2593                                InFlag);
2594     InFlag = Chain.getValue(1);
2595   }
2596
2597   // Handle result values, copying them out of physregs into vregs that we
2598   // return.
2599   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2600                          Ins, dl, DAG, InVals);
2601 }
2602
2603
2604 //===----------------------------------------------------------------------===//
2605 //                Fast Calling Convention (tail call) implementation
2606 //===----------------------------------------------------------------------===//
2607
2608 //  Like std call, callee cleans arguments, convention except that ECX is
2609 //  reserved for storing the tail called function address. Only 2 registers are
2610 //  free for argument passing (inreg). Tail call optimization is performed
2611 //  provided:
2612 //                * tailcallopt is enabled
2613 //                * caller/callee are fastcc
2614 //  On X86_64 architecture with GOT-style position independent code only local
2615 //  (within module) calls are supported at the moment.
2616 //  To keep the stack aligned according to platform abi the function
2617 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2618 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2619 //  If a tail called function callee has more arguments than the caller the
2620 //  caller needs to make sure that there is room to move the RETADDR to. This is
2621 //  achieved by reserving an area the size of the argument delta right after the
2622 //  original REtADDR, but before the saved framepointer or the spilled registers
2623 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2624 //  stack layout:
2625 //    arg1
2626 //    arg2
2627 //    RETADDR
2628 //    [ new RETADDR
2629 //      move area ]
2630 //    (possible EBP)
2631 //    ESI
2632 //    EDI
2633 //    local1 ..
2634
2635 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2636 /// for a 16 byte align requirement.
2637 unsigned
2638 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2639                                                SelectionDAG& DAG) const {
2640   MachineFunction &MF = DAG.getMachineFunction();
2641   const TargetMachine &TM = MF.getTarget();
2642   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2643   unsigned StackAlignment = TFI.getStackAlignment();
2644   uint64_t AlignMask = StackAlignment - 1;
2645   int64_t Offset = StackSize;
2646   uint64_t SlotSize = TD->getPointerSize();
2647   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2648     // Number smaller than 12 so just add the difference.
2649     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2650   } else {
2651     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2652     Offset = ((~AlignMask) & Offset) + StackAlignment +
2653       (StackAlignment-SlotSize);
2654   }
2655   return Offset;
2656 }
2657
2658 /// MatchingStackOffset - Return true if the given stack call argument is
2659 /// already available in the same position (relatively) of the caller's
2660 /// incoming argument stack.
2661 static
2662 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2663                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2664                          const X86InstrInfo *TII) {
2665   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2666   int FI = INT_MAX;
2667   if (Arg.getOpcode() == ISD::CopyFromReg) {
2668     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2669     if (!TargetRegisterInfo::isVirtualRegister(VR))
2670       return false;
2671     MachineInstr *Def = MRI->getVRegDef(VR);
2672     if (!Def)
2673       return false;
2674     if (!Flags.isByVal()) {
2675       if (!TII->isLoadFromStackSlot(Def, FI))
2676         return false;
2677     } else {
2678       unsigned Opcode = Def->getOpcode();
2679       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2680           Def->getOperand(1).isFI()) {
2681         FI = Def->getOperand(1).getIndex();
2682         Bytes = Flags.getByValSize();
2683       } else
2684         return false;
2685     }
2686   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2687     if (Flags.isByVal())
2688       // ByVal argument is passed in as a pointer but it's now being
2689       // dereferenced. e.g.
2690       // define @foo(%struct.X* %A) {
2691       //   tail call @bar(%struct.X* byval %A)
2692       // }
2693       return false;
2694     SDValue Ptr = Ld->getBasePtr();
2695     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2696     if (!FINode)
2697       return false;
2698     FI = FINode->getIndex();
2699   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2700     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2701     FI = FINode->getIndex();
2702     Bytes = Flags.getByValSize();
2703   } else
2704     return false;
2705
2706   assert(FI != INT_MAX);
2707   if (!MFI->isFixedObjectIndex(FI))
2708     return false;
2709   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2710 }
2711
2712 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2713 /// for tail call optimization. Targets which want to do tail call
2714 /// optimization should implement this function.
2715 bool
2716 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2717                                                      CallingConv::ID CalleeCC,
2718                                                      bool isVarArg,
2719                                                      bool isCalleeStructRet,
2720                                                      bool isCallerStructRet,
2721                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2722                                     const SmallVectorImpl<SDValue> &OutVals,
2723                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2724                                                      SelectionDAG& DAG) const {
2725   if (!IsTailCallConvention(CalleeCC) &&
2726       CalleeCC != CallingConv::C)
2727     return false;
2728
2729   // If -tailcallopt is specified, make fastcc functions tail-callable.
2730   const MachineFunction &MF = DAG.getMachineFunction();
2731   const Function *CallerF = DAG.getMachineFunction().getFunction();
2732   CallingConv::ID CallerCC = CallerF->getCallingConv();
2733   bool CCMatch = CallerCC == CalleeCC;
2734
2735   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2736     if (IsTailCallConvention(CalleeCC) && CCMatch)
2737       return true;
2738     return false;
2739   }
2740
2741   // Look for obvious safe cases to perform tail call optimization that do not
2742   // require ABI changes. This is what gcc calls sibcall.
2743
2744   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2745   // emit a special epilogue.
2746   if (RegInfo->needsStackRealignment(MF))
2747     return false;
2748
2749   // Also avoid sibcall optimization if either caller or callee uses struct
2750   // return semantics.
2751   if (isCalleeStructRet || isCallerStructRet)
2752     return false;
2753
2754   // An stdcall caller is expected to clean up its arguments; the callee
2755   // isn't going to do that.
2756   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2757     return false;
2758
2759   // Do not sibcall optimize vararg calls unless all arguments are passed via
2760   // registers.
2761   if (isVarArg && !Outs.empty()) {
2762
2763     // Optimizing for varargs on Win64 is unlikely to be safe without
2764     // additional testing.
2765     if (Subtarget->isTargetWin64())
2766       return false;
2767
2768     SmallVector<CCValAssign, 16> ArgLocs;
2769     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2770                    getTargetMachine(), ArgLocs, *DAG.getContext());
2771
2772     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2773     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2774       if (!ArgLocs[i].isRegLoc())
2775         return false;
2776   }
2777
2778   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2779   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2780   // this into a sibcall.
2781   bool Unused = false;
2782   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2783     if (!Ins[i].Used) {
2784       Unused = true;
2785       break;
2786     }
2787   }
2788   if (Unused) {
2789     SmallVector<CCValAssign, 16> RVLocs;
2790     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2791                    getTargetMachine(), RVLocs, *DAG.getContext());
2792     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2793     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2794       CCValAssign &VA = RVLocs[i];
2795       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2796         return false;
2797     }
2798   }
2799
2800   // If the calling conventions do not match, then we'd better make sure the
2801   // results are returned in the same way as what the caller expects.
2802   if (!CCMatch) {
2803     SmallVector<CCValAssign, 16> RVLocs1;
2804     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2805                     getTargetMachine(), RVLocs1, *DAG.getContext());
2806     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2807
2808     SmallVector<CCValAssign, 16> RVLocs2;
2809     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2810                     getTargetMachine(), RVLocs2, *DAG.getContext());
2811     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2812
2813     if (RVLocs1.size() != RVLocs2.size())
2814       return false;
2815     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2816       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2817         return false;
2818       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2819         return false;
2820       if (RVLocs1[i].isRegLoc()) {
2821         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2822           return false;
2823       } else {
2824         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2825           return false;
2826       }
2827     }
2828   }
2829
2830   // If the callee takes no arguments then go on to check the results of the
2831   // call.
2832   if (!Outs.empty()) {
2833     // Check if stack adjustment is needed. For now, do not do this if any
2834     // argument is passed on the stack.
2835     SmallVector<CCValAssign, 16> ArgLocs;
2836     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2837                    getTargetMachine(), ArgLocs, *DAG.getContext());
2838
2839     // Allocate shadow area for Win64
2840     if (Subtarget->isTargetWin64()) {
2841       CCInfo.AllocateStack(32, 8);
2842     }
2843
2844     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2845     if (CCInfo.getNextStackOffset()) {
2846       MachineFunction &MF = DAG.getMachineFunction();
2847       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2848         return false;
2849
2850       // Check if the arguments are already laid out in the right way as
2851       // the caller's fixed stack objects.
2852       MachineFrameInfo *MFI = MF.getFrameInfo();
2853       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2854       const X86InstrInfo *TII =
2855         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2856       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2857         CCValAssign &VA = ArgLocs[i];
2858         SDValue Arg = OutVals[i];
2859         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2860         if (VA.getLocInfo() == CCValAssign::Indirect)
2861           return false;
2862         if (!VA.isRegLoc()) {
2863           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2864                                    MFI, MRI, TII))
2865             return false;
2866         }
2867       }
2868     }
2869
2870     // If the tailcall address may be in a register, then make sure it's
2871     // possible to register allocate for it. In 32-bit, the call address can
2872     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2873     // callee-saved registers are restored. These happen to be the same
2874     // registers used to pass 'inreg' arguments so watch out for those.
2875     if (!Subtarget->is64Bit() &&
2876         !isa<GlobalAddressSDNode>(Callee) &&
2877         !isa<ExternalSymbolSDNode>(Callee)) {
2878       unsigned NumInRegs = 0;
2879       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2880         CCValAssign &VA = ArgLocs[i];
2881         if (!VA.isRegLoc())
2882           continue;
2883         unsigned Reg = VA.getLocReg();
2884         switch (Reg) {
2885         default: break;
2886         case X86::EAX: case X86::EDX: case X86::ECX:
2887           if (++NumInRegs == 3)
2888             return false;
2889           break;
2890         }
2891       }
2892     }
2893   }
2894
2895   return true;
2896 }
2897
2898 FastISel *
2899 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2900                                   const TargetLibraryInfo *libInfo) const {
2901   return X86::createFastISel(funcInfo, libInfo);
2902 }
2903
2904
2905 //===----------------------------------------------------------------------===//
2906 //                           Other Lowering Hooks
2907 //===----------------------------------------------------------------------===//
2908
2909 static bool MayFoldLoad(SDValue Op) {
2910   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2911 }
2912
2913 static bool MayFoldIntoStore(SDValue Op) {
2914   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2915 }
2916
2917 static bool isTargetShuffle(unsigned Opcode) {
2918   switch(Opcode) {
2919   default: return false;
2920   case X86ISD::PSHUFD:
2921   case X86ISD::PSHUFHW:
2922   case X86ISD::PSHUFLW:
2923   case X86ISD::SHUFP:
2924   case X86ISD::PALIGN:
2925   case X86ISD::MOVLHPS:
2926   case X86ISD::MOVLHPD:
2927   case X86ISD::MOVHLPS:
2928   case X86ISD::MOVLPS:
2929   case X86ISD::MOVLPD:
2930   case X86ISD::MOVSHDUP:
2931   case X86ISD::MOVSLDUP:
2932   case X86ISD::MOVDDUP:
2933   case X86ISD::MOVSS:
2934   case X86ISD::MOVSD:
2935   case X86ISD::UNPCKL:
2936   case X86ISD::UNPCKH:
2937   case X86ISD::VPERMILP:
2938   case X86ISD::VPERM2X128:
2939   case X86ISD::VPERMI:
2940     return true;
2941   }
2942 }
2943
2944 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2945                                     SDValue V1, SelectionDAG &DAG) {
2946   switch(Opc) {
2947   default: llvm_unreachable("Unknown x86 shuffle node");
2948   case X86ISD::MOVSHDUP:
2949   case X86ISD::MOVSLDUP:
2950   case X86ISD::MOVDDUP:
2951     return DAG.getNode(Opc, dl, VT, V1);
2952   }
2953 }
2954
2955 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2956                                     SDValue V1, unsigned TargetMask,
2957                                     SelectionDAG &DAG) {
2958   switch(Opc) {
2959   default: llvm_unreachable("Unknown x86 shuffle node");
2960   case X86ISD::PSHUFD:
2961   case X86ISD::PSHUFHW:
2962   case X86ISD::PSHUFLW:
2963   case X86ISD::VPERMILP:
2964   case X86ISD::VPERMI:
2965     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2966   }
2967 }
2968
2969 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2970                                     SDValue V1, SDValue V2, unsigned TargetMask,
2971                                     SelectionDAG &DAG) {
2972   switch(Opc) {
2973   default: llvm_unreachable("Unknown x86 shuffle node");
2974   case X86ISD::PALIGN:
2975   case X86ISD::SHUFP:
2976   case X86ISD::VPERM2X128:
2977     return DAG.getNode(Opc, dl, VT, V1, V2,
2978                        DAG.getConstant(TargetMask, MVT::i8));
2979   }
2980 }
2981
2982 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2983                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2984   switch(Opc) {
2985   default: llvm_unreachable("Unknown x86 shuffle node");
2986   case X86ISD::MOVLHPS:
2987   case X86ISD::MOVLHPD:
2988   case X86ISD::MOVHLPS:
2989   case X86ISD::MOVLPS:
2990   case X86ISD::MOVLPD:
2991   case X86ISD::MOVSS:
2992   case X86ISD::MOVSD:
2993   case X86ISD::UNPCKL:
2994   case X86ISD::UNPCKH:
2995     return DAG.getNode(Opc, dl, VT, V1, V2);
2996   }
2997 }
2998
2999 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3000   MachineFunction &MF = DAG.getMachineFunction();
3001   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3002   int ReturnAddrIndex = FuncInfo->getRAIndex();
3003
3004   if (ReturnAddrIndex == 0) {
3005     // Set up a frame object for the return address.
3006     uint64_t SlotSize = TD->getPointerSize();
3007     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3008                                                            false);
3009     FuncInfo->setRAIndex(ReturnAddrIndex);
3010   }
3011
3012   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3013 }
3014
3015
3016 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3017                                        bool hasSymbolicDisplacement) {
3018   // Offset should fit into 32 bit immediate field.
3019   if (!isInt<32>(Offset))
3020     return false;
3021
3022   // If we don't have a symbolic displacement - we don't have any extra
3023   // restrictions.
3024   if (!hasSymbolicDisplacement)
3025     return true;
3026
3027   // FIXME: Some tweaks might be needed for medium code model.
3028   if (M != CodeModel::Small && M != CodeModel::Kernel)
3029     return false;
3030
3031   // For small code model we assume that latest object is 16MB before end of 31
3032   // bits boundary. We may also accept pretty large negative constants knowing
3033   // that all objects are in the positive half of address space.
3034   if (M == CodeModel::Small && Offset < 16*1024*1024)
3035     return true;
3036
3037   // For kernel code model we know that all object resist in the negative half
3038   // of 32bits address space. We may not accept negative offsets, since they may
3039   // be just off and we may accept pretty large positive ones.
3040   if (M == CodeModel::Kernel && Offset > 0)
3041     return true;
3042
3043   return false;
3044 }
3045
3046 /// isCalleePop - Determines whether the callee is required to pop its
3047 /// own arguments. Callee pop is necessary to support tail calls.
3048 bool X86::isCalleePop(CallingConv::ID CallingConv,
3049                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3050   if (IsVarArg)
3051     return false;
3052
3053   switch (CallingConv) {
3054   default:
3055     return false;
3056   case CallingConv::X86_StdCall:
3057     return !is64Bit;
3058   case CallingConv::X86_FastCall:
3059     return !is64Bit;
3060   case CallingConv::X86_ThisCall:
3061     return !is64Bit;
3062   case CallingConv::Fast:
3063     return TailCallOpt;
3064   case CallingConv::GHC:
3065     return TailCallOpt;
3066   }
3067 }
3068
3069 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3070 /// specific condition code, returning the condition code and the LHS/RHS of the
3071 /// comparison to make.
3072 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3073                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3074   if (!isFP) {
3075     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3076       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3077         // X > -1   -> X == 0, jump !sign.
3078         RHS = DAG.getConstant(0, RHS.getValueType());
3079         return X86::COND_NS;
3080       }
3081       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3082         // X < 0   -> X == 0, jump on sign.
3083         return X86::COND_S;
3084       }
3085       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3086         // X < 1   -> X <= 0
3087         RHS = DAG.getConstant(0, RHS.getValueType());
3088         return X86::COND_LE;
3089       }
3090     }
3091
3092     switch (SetCCOpcode) {
3093     default: llvm_unreachable("Invalid integer condition!");
3094     case ISD::SETEQ:  return X86::COND_E;
3095     case ISD::SETGT:  return X86::COND_G;
3096     case ISD::SETGE:  return X86::COND_GE;
3097     case ISD::SETLT:  return X86::COND_L;
3098     case ISD::SETLE:  return X86::COND_LE;
3099     case ISD::SETNE:  return X86::COND_NE;
3100     case ISD::SETULT: return X86::COND_B;
3101     case ISD::SETUGT: return X86::COND_A;
3102     case ISD::SETULE: return X86::COND_BE;
3103     case ISD::SETUGE: return X86::COND_AE;
3104     }
3105   }
3106
3107   // First determine if it is required or is profitable to flip the operands.
3108
3109   // If LHS is a foldable load, but RHS is not, flip the condition.
3110   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3111       !ISD::isNON_EXTLoad(RHS.getNode())) {
3112     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3113     std::swap(LHS, RHS);
3114   }
3115
3116   switch (SetCCOpcode) {
3117   default: break;
3118   case ISD::SETOLT:
3119   case ISD::SETOLE:
3120   case ISD::SETUGT:
3121   case ISD::SETUGE:
3122     std::swap(LHS, RHS);
3123     break;
3124   }
3125
3126   // On a floating point condition, the flags are set as follows:
3127   // ZF  PF  CF   op
3128   //  0 | 0 | 0 | X > Y
3129   //  0 | 0 | 1 | X < Y
3130   //  1 | 0 | 0 | X == Y
3131   //  1 | 1 | 1 | unordered
3132   switch (SetCCOpcode) {
3133   default: llvm_unreachable("Condcode should be pre-legalized away");
3134   case ISD::SETUEQ:
3135   case ISD::SETEQ:   return X86::COND_E;
3136   case ISD::SETOLT:              // flipped
3137   case ISD::SETOGT:
3138   case ISD::SETGT:   return X86::COND_A;
3139   case ISD::SETOLE:              // flipped
3140   case ISD::SETOGE:
3141   case ISD::SETGE:   return X86::COND_AE;
3142   case ISD::SETUGT:              // flipped
3143   case ISD::SETULT:
3144   case ISD::SETLT:   return X86::COND_B;
3145   case ISD::SETUGE:              // flipped
3146   case ISD::SETULE:
3147   case ISD::SETLE:   return X86::COND_BE;
3148   case ISD::SETONE:
3149   case ISD::SETNE:   return X86::COND_NE;
3150   case ISD::SETUO:   return X86::COND_P;
3151   case ISD::SETO:    return X86::COND_NP;
3152   case ISD::SETOEQ:
3153   case ISD::SETUNE:  return X86::COND_INVALID;
3154   }
3155 }
3156
3157 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3158 /// code. Current x86 isa includes the following FP cmov instructions:
3159 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3160 static bool hasFPCMov(unsigned X86CC) {
3161   switch (X86CC) {
3162   default:
3163     return false;
3164   case X86::COND_B:
3165   case X86::COND_BE:
3166   case X86::COND_E:
3167   case X86::COND_P:
3168   case X86::COND_A:
3169   case X86::COND_AE:
3170   case X86::COND_NE:
3171   case X86::COND_NP:
3172     return true;
3173   }
3174 }
3175
3176 /// isFPImmLegal - Returns true if the target can instruction select the
3177 /// specified FP immediate natively. If false, the legalizer will
3178 /// materialize the FP immediate as a load from a constant pool.
3179 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3180   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3181     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3182       return true;
3183   }
3184   return false;
3185 }
3186
3187 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3188 /// the specified range (L, H].
3189 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3190   return (Val < 0) || (Val >= Low && Val < Hi);
3191 }
3192
3193 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3194 /// specified value.
3195 static bool isUndefOrEqual(int Val, int CmpVal) {
3196   if (Val < 0 || Val == CmpVal)
3197     return true;
3198   return false;
3199 }
3200
3201 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3202 /// from position Pos and ending in Pos+Size, falls within the specified
3203 /// sequential range (L, L+Pos]. or is undef.
3204 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3205                                        unsigned Pos, unsigned Size, int Low) {
3206   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3207     if (!isUndefOrEqual(Mask[i], Low))
3208       return false;
3209   return true;
3210 }
3211
3212 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3214 /// the second operand.
3215 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3216   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3217     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3218   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3219     return (Mask[0] < 2 && Mask[1] < 2);
3220   return false;
3221 }
3222
3223 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3224 /// is suitable for input to PSHUFHW.
3225 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3226   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3227     return false;
3228
3229   // Lower quadword copied in order or undef.
3230   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3231     return false;
3232
3233   // Upper quadword shuffled.
3234   for (unsigned i = 4; i != 8; ++i)
3235     if (!isUndefOrInRange(Mask[i], 4, 8))
3236       return false;
3237
3238   if (VT == MVT::v16i16) {
3239     // Lower quadword copied in order or undef.
3240     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3241       return false;
3242
3243     // Upper quadword shuffled.
3244     for (unsigned i = 12; i != 16; ++i)
3245       if (!isUndefOrInRange(Mask[i], 12, 16))
3246         return false;
3247   }
3248
3249   return true;
3250 }
3251
3252 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PSHUFLW.
3254 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3255   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3256     return false;
3257
3258   // Upper quadword copied in order.
3259   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3260     return false;
3261
3262   // Lower quadword shuffled.
3263   for (unsigned i = 0; i != 4; ++i)
3264     if (!isUndefOrInRange(Mask[i], 0, 4))
3265       return false;
3266
3267   if (VT == MVT::v16i16) {
3268     // Upper quadword copied in order.
3269     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3270       return false;
3271
3272     // Lower quadword shuffled.
3273     for (unsigned i = 8; i != 12; ++i)
3274       if (!isUndefOrInRange(Mask[i], 8, 12))
3275         return false;
3276   }
3277
3278   return true;
3279 }
3280
3281 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3282 /// is suitable for input to PALIGNR.
3283 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3284                           const X86Subtarget *Subtarget) {
3285   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3286       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3287     return false;
3288
3289   unsigned NumElts = VT.getVectorNumElements();
3290   unsigned NumLanes = VT.getSizeInBits()/128;
3291   unsigned NumLaneElts = NumElts/NumLanes;
3292
3293   // Do not handle 64-bit element shuffles with palignr.
3294   if (NumLaneElts == 2)
3295     return false;
3296
3297   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3298     unsigned i;
3299     for (i = 0; i != NumLaneElts; ++i) {
3300       if (Mask[i+l] >= 0)
3301         break;
3302     }
3303
3304     // Lane is all undef, go to next lane
3305     if (i == NumLaneElts)
3306       continue;
3307
3308     int Start = Mask[i+l];
3309
3310     // Make sure its in this lane in one of the sources
3311     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3312         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3313       return false;
3314
3315     // If not lane 0, then we must match lane 0
3316     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3317       return false;
3318
3319     // Correct second source to be contiguous with first source
3320     if (Start >= (int)NumElts)
3321       Start -= NumElts - NumLaneElts;
3322
3323     // Make sure we're shifting in the right direction.
3324     if (Start <= (int)(i+l))
3325       return false;
3326
3327     Start -= i;
3328
3329     // Check the rest of the elements to see if they are consecutive.
3330     for (++i; i != NumLaneElts; ++i) {
3331       int Idx = Mask[i+l];
3332
3333       // Make sure its in this lane
3334       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3335           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3336         return false;
3337
3338       // If not lane 0, then we must match lane 0
3339       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3340         return false;
3341
3342       if (Idx >= (int)NumElts)
3343         Idx -= NumElts - NumLaneElts;
3344
3345       if (!isUndefOrEqual(Idx, Start+i))
3346         return false;
3347
3348     }
3349   }
3350
3351   return true;
3352 }
3353
3354 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3355 /// the two vector operands have swapped position.
3356 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3357                                      unsigned NumElems) {
3358   for (unsigned i = 0; i != NumElems; ++i) {
3359     int idx = Mask[i];
3360     if (idx < 0)
3361       continue;
3362     else if (idx < (int)NumElems)
3363       Mask[i] = idx + NumElems;
3364     else
3365       Mask[i] = idx - NumElems;
3366   }
3367 }
3368
3369 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3370 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3371 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3372 /// reverse of what x86 shuffles want.
3373 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3374                         bool Commuted = false) {
3375   if (!HasAVX && VT.getSizeInBits() == 256)
3376     return false;
3377
3378   unsigned NumElems = VT.getVectorNumElements();
3379   unsigned NumLanes = VT.getSizeInBits()/128;
3380   unsigned NumLaneElems = NumElems/NumLanes;
3381
3382   if (NumLaneElems != 2 && NumLaneElems != 4)
3383     return false;
3384
3385   // VSHUFPSY divides the resulting vector into 4 chunks.
3386   // The sources are also splitted into 4 chunks, and each destination
3387   // chunk must come from a different source chunk.
3388   //
3389   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3390   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3391   //
3392   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3393   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3394   //
3395   // VSHUFPDY divides the resulting vector into 4 chunks.
3396   // The sources are also splitted into 4 chunks, and each destination
3397   // chunk must come from a different source chunk.
3398   //
3399   //  SRC1 =>      X3       X2       X1       X0
3400   //  SRC2 =>      Y3       Y2       Y1       Y0
3401   //
3402   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3403   //
3404   unsigned HalfLaneElems = NumLaneElems/2;
3405   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3406     for (unsigned i = 0; i != NumLaneElems; ++i) {
3407       int Idx = Mask[i+l];
3408       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3409       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3410         return false;
3411       // For VSHUFPSY, the mask of the second half must be the same as the
3412       // first but with the appropriate offsets. This works in the same way as
3413       // VPERMILPS works with masks.
3414       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3415         continue;
3416       if (!isUndefOrEqual(Idx, Mask[i]+l))
3417         return false;
3418     }
3419   }
3420
3421   return true;
3422 }
3423
3424 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3425 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3426 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3427   if (!VT.is128BitVector())
3428     return false;
3429
3430   unsigned NumElems = VT.getVectorNumElements();
3431
3432   if (NumElems != 4)
3433     return false;
3434
3435   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3436   return isUndefOrEqual(Mask[0], 6) &&
3437          isUndefOrEqual(Mask[1], 7) &&
3438          isUndefOrEqual(Mask[2], 2) &&
3439          isUndefOrEqual(Mask[3], 3);
3440 }
3441
3442 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3443 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3444 /// <2, 3, 2, 3>
3445 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3446   if (!VT.is128BitVector())
3447     return false;
3448
3449   unsigned NumElems = VT.getVectorNumElements();
3450
3451   if (NumElems != 4)
3452     return false;
3453
3454   return isUndefOrEqual(Mask[0], 2) &&
3455          isUndefOrEqual(Mask[1], 3) &&
3456          isUndefOrEqual(Mask[2], 2) &&
3457          isUndefOrEqual(Mask[3], 3);
3458 }
3459
3460 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3461 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3462 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3463   if (!VT.is128BitVector())
3464     return false;
3465
3466   unsigned NumElems = VT.getVectorNumElements();
3467
3468   if (NumElems != 2 && NumElems != 4)
3469     return false;
3470
3471   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3472     if (!isUndefOrEqual(Mask[i], i + NumElems))
3473       return false;
3474
3475   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3476     if (!isUndefOrEqual(Mask[i], i))
3477       return false;
3478
3479   return true;
3480 }
3481
3482 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3483 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3484 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3485   if (!VT.is128BitVector())
3486     return false;
3487
3488   unsigned NumElems = VT.getVectorNumElements();
3489
3490   if (NumElems != 2 && NumElems != 4)
3491     return false;
3492
3493   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3494     if (!isUndefOrEqual(Mask[i], i))
3495       return false;
3496
3497   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3498     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3499       return false;
3500
3501   return true;
3502 }
3503
3504 //
3505 // Some special combinations that can be optimized.
3506 //
3507 static
3508 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3509                                SelectionDAG &DAG) {
3510   EVT VT = SVOp->getValueType(0);
3511   DebugLoc dl = SVOp->getDebugLoc();
3512
3513   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3514     return SDValue();
3515
3516   ArrayRef<int> Mask = SVOp->getMask();
3517
3518   // These are the special masks that may be optimized.
3519   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3520   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3521   bool MatchEvenMask = true;
3522   bool MatchOddMask  = true;
3523   for (int i=0; i<8; ++i) {
3524     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3525       MatchEvenMask = false;
3526     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3527       MatchOddMask = false;
3528   }
3529
3530   if (!MatchEvenMask && !MatchOddMask)
3531     return SDValue();
3532   
3533   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3534
3535   SDValue Op0 = SVOp->getOperand(0);
3536   SDValue Op1 = SVOp->getOperand(1);
3537
3538   if (MatchEvenMask) {
3539     // Shift the second operand right to 32 bits.
3540     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3541     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3542   } else {
3543     // Shift the first operand left to 32 bits.
3544     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3545     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3546   }
3547   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3548   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3549 }
3550
3551 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3552 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3553 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3554                          bool HasAVX2, bool V2IsSplat = false) {
3555   unsigned NumElts = VT.getVectorNumElements();
3556
3557   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3558          "Unsupported vector type for unpckh");
3559
3560   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3561       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3562     return false;
3563
3564   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3565   // independently on 128-bit lanes.
3566   unsigned NumLanes = VT.getSizeInBits()/128;
3567   unsigned NumLaneElts = NumElts/NumLanes;
3568
3569   for (unsigned l = 0; l != NumLanes; ++l) {
3570     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3571          i != (l+1)*NumLaneElts;
3572          i += 2, ++j) {
3573       int BitI  = Mask[i];
3574       int BitI1 = Mask[i+1];
3575       if (!isUndefOrEqual(BitI, j))
3576         return false;
3577       if (V2IsSplat) {
3578         if (!isUndefOrEqual(BitI1, NumElts))
3579           return false;
3580       } else {
3581         if (!isUndefOrEqual(BitI1, j + NumElts))
3582           return false;
3583       }
3584     }
3585   }
3586
3587   return true;
3588 }
3589
3590 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3591 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3592 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3593                          bool HasAVX2, bool V2IsSplat = false) {
3594   unsigned NumElts = VT.getVectorNumElements();
3595
3596   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3597          "Unsupported vector type for unpckh");
3598
3599   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3600       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3601     return false;
3602
3603   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3604   // independently on 128-bit lanes.
3605   unsigned NumLanes = VT.getSizeInBits()/128;
3606   unsigned NumLaneElts = NumElts/NumLanes;
3607
3608   for (unsigned l = 0; l != NumLanes; ++l) {
3609     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3610          i != (l+1)*NumLaneElts; i += 2, ++j) {
3611       int BitI  = Mask[i];
3612       int BitI1 = Mask[i+1];
3613       if (!isUndefOrEqual(BitI, j))
3614         return false;
3615       if (V2IsSplat) {
3616         if (isUndefOrEqual(BitI1, NumElts))
3617           return false;
3618       } else {
3619         if (!isUndefOrEqual(BitI1, j+NumElts))
3620           return false;
3621       }
3622     }
3623   }
3624   return true;
3625 }
3626
3627 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3628 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3629 /// <0, 0, 1, 1>
3630 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3631                                   bool HasAVX2) {
3632   unsigned NumElts = VT.getVectorNumElements();
3633
3634   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3635          "Unsupported vector type for unpckh");
3636
3637   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3638       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3639     return false;
3640
3641   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3642   // FIXME: Need a better way to get rid of this, there's no latency difference
3643   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3644   // the former later. We should also remove the "_undef" special mask.
3645   if (NumElts == 4 && VT.getSizeInBits() == 256)
3646     return false;
3647
3648   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3649   // independently on 128-bit lanes.
3650   unsigned NumLanes = VT.getSizeInBits()/128;
3651   unsigned NumLaneElts = NumElts/NumLanes;
3652
3653   for (unsigned l = 0; l != NumLanes; ++l) {
3654     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3655          i != (l+1)*NumLaneElts;
3656          i += 2, ++j) {
3657       int BitI  = Mask[i];
3658       int BitI1 = Mask[i+1];
3659
3660       if (!isUndefOrEqual(BitI, j))
3661         return false;
3662       if (!isUndefOrEqual(BitI1, j))
3663         return false;
3664     }
3665   }
3666
3667   return true;
3668 }
3669
3670 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3671 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3672 /// <2, 2, 3, 3>
3673 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3674   unsigned NumElts = VT.getVectorNumElements();
3675
3676   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3677          "Unsupported vector type for unpckh");
3678
3679   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3680       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3681     return false;
3682
3683   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3684   // independently on 128-bit lanes.
3685   unsigned NumLanes = VT.getSizeInBits()/128;
3686   unsigned NumLaneElts = NumElts/NumLanes;
3687
3688   for (unsigned l = 0; l != NumLanes; ++l) {
3689     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3690          i != (l+1)*NumLaneElts; i += 2, ++j) {
3691       int BitI  = Mask[i];
3692       int BitI1 = Mask[i+1];
3693       if (!isUndefOrEqual(BitI, j))
3694         return false;
3695       if (!isUndefOrEqual(BitI1, j))
3696         return false;
3697     }
3698   }
3699   return true;
3700 }
3701
3702 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3703 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3704 /// MOVSD, and MOVD, i.e. setting the lowest element.
3705 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3706   if (VT.getVectorElementType().getSizeInBits() < 32)
3707     return false;
3708   if (!VT.is128BitVector())
3709     return false;
3710
3711   unsigned NumElts = VT.getVectorNumElements();
3712
3713   if (!isUndefOrEqual(Mask[0], NumElts))
3714     return false;
3715
3716   for (unsigned i = 1; i != NumElts; ++i)
3717     if (!isUndefOrEqual(Mask[i], i))
3718       return false;
3719
3720   return true;
3721 }
3722
3723 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3724 /// as permutations between 128-bit chunks or halves. As an example: this
3725 /// shuffle bellow:
3726 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3727 /// The first half comes from the second half of V1 and the second half from the
3728 /// the second half of V2.
3729 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3730   if (!HasAVX || !VT.is256BitVector())
3731     return false;
3732
3733   // The shuffle result is divided into half A and half B. In total the two
3734   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3735   // B must come from C, D, E or F.
3736   unsigned HalfSize = VT.getVectorNumElements()/2;
3737   bool MatchA = false, MatchB = false;
3738
3739   // Check if A comes from one of C, D, E, F.
3740   for (unsigned Half = 0; Half != 4; ++Half) {
3741     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3742       MatchA = true;
3743       break;
3744     }
3745   }
3746
3747   // Check if B comes from one of C, D, E, F.
3748   for (unsigned Half = 0; Half != 4; ++Half) {
3749     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3750       MatchB = true;
3751       break;
3752     }
3753   }
3754
3755   return MatchA && MatchB;
3756 }
3757
3758 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3759 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3760 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3761   EVT VT = SVOp->getValueType(0);
3762
3763   unsigned HalfSize = VT.getVectorNumElements()/2;
3764
3765   unsigned FstHalf = 0, SndHalf = 0;
3766   for (unsigned i = 0; i < HalfSize; ++i) {
3767     if (SVOp->getMaskElt(i) > 0) {
3768       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3769       break;
3770     }
3771   }
3772   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3773     if (SVOp->getMaskElt(i) > 0) {
3774       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3775       break;
3776     }
3777   }
3778
3779   return (FstHalf | (SndHalf << 4));
3780 }
3781
3782 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3783 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3784 /// Note that VPERMIL mask matching is different depending whether theunderlying
3785 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3786 /// to the same elements of the low, but to the higher half of the source.
3787 /// In VPERMILPD the two lanes could be shuffled independently of each other
3788 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3789 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3790   if (!HasAVX)
3791     return false;
3792
3793   unsigned NumElts = VT.getVectorNumElements();
3794   // Only match 256-bit with 32/64-bit types
3795   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3796     return false;
3797
3798   unsigned NumLanes = VT.getSizeInBits()/128;
3799   unsigned LaneSize = NumElts/NumLanes;
3800   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3801     for (unsigned i = 0; i != LaneSize; ++i) {
3802       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3803         return false;
3804       if (NumElts != 8 || l == 0)
3805         continue;
3806       // VPERMILPS handling
3807       if (Mask[i] < 0)
3808         continue;
3809       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3810         return false;
3811     }
3812   }
3813
3814   return true;
3815 }
3816
3817 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3818 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3819 /// element of vector 2 and the other elements to come from vector 1 in order.
3820 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3821                                bool V2IsSplat = false, bool V2IsUndef = false) {
3822   if (!VT.is128BitVector())
3823     return false;
3824
3825   unsigned NumOps = VT.getVectorNumElements();
3826   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3827     return false;
3828
3829   if (!isUndefOrEqual(Mask[0], 0))
3830     return false;
3831
3832   for (unsigned i = 1; i != NumOps; ++i)
3833     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3834           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3835           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3836       return false;
3837
3838   return true;
3839 }
3840
3841 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3842 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3843 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3844 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3845                            const X86Subtarget *Subtarget) {
3846   if (!Subtarget->hasSSE3())
3847     return false;
3848
3849   unsigned NumElems = VT.getVectorNumElements();
3850
3851   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3852       (VT.getSizeInBits() == 256 && NumElems != 8))
3853     return false;
3854
3855   // "i+1" is the value the indexed mask element must have
3856   for (unsigned i = 0; i != NumElems; i += 2)
3857     if (!isUndefOrEqual(Mask[i], i+1) ||
3858         !isUndefOrEqual(Mask[i+1], i+1))
3859       return false;
3860
3861   return true;
3862 }
3863
3864 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3865 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3866 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3867 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3868                            const X86Subtarget *Subtarget) {
3869   if (!Subtarget->hasSSE3())
3870     return false;
3871
3872   unsigned NumElems = VT.getVectorNumElements();
3873
3874   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3875       (VT.getSizeInBits() == 256 && NumElems != 8))
3876     return false;
3877
3878   // "i" is the value the indexed mask element must have
3879   for (unsigned i = 0; i != NumElems; i += 2)
3880     if (!isUndefOrEqual(Mask[i], i) ||
3881         !isUndefOrEqual(Mask[i+1], i))
3882       return false;
3883
3884   return true;
3885 }
3886
3887 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to 256-bit
3889 /// version of MOVDDUP.
3890 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3891   if (!HasAVX || !VT.is256BitVector())
3892     return false;
3893
3894   unsigned NumElts = VT.getVectorNumElements();
3895   if (NumElts != 4)
3896     return false;
3897
3898   for (unsigned i = 0; i != NumElts/2; ++i)
3899     if (!isUndefOrEqual(Mask[i], 0))
3900       return false;
3901   for (unsigned i = NumElts/2; i != NumElts; ++i)
3902     if (!isUndefOrEqual(Mask[i], NumElts/2))
3903       return false;
3904   return true;
3905 }
3906
3907 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to 128-bit
3909 /// version of MOVDDUP.
3910 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3911   if (!VT.is128BitVector())
3912     return false;
3913
3914   unsigned e = VT.getVectorNumElements() / 2;
3915   for (unsigned i = 0; i != e; ++i)
3916     if (!isUndefOrEqual(Mask[i], i))
3917       return false;
3918   for (unsigned i = 0; i != e; ++i)
3919     if (!isUndefOrEqual(Mask[e+i], i))
3920       return false;
3921   return true;
3922 }
3923
3924 /// isVEXTRACTF128Index - Return true if the specified
3925 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3926 /// suitable for input to VEXTRACTF128.
3927 bool X86::isVEXTRACTF128Index(SDNode *N) {
3928   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929     return false;
3930
3931   // The index should be aligned on a 128-bit boundary.
3932   uint64_t Index =
3933     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3934
3935   unsigned VL = N->getValueType(0).getVectorNumElements();
3936   unsigned VBits = N->getValueType(0).getSizeInBits();
3937   unsigned ElSize = VBits / VL;
3938   bool Result = (Index * ElSize) % 128 == 0;
3939
3940   return Result;
3941 }
3942
3943 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3944 /// operand specifies a subvector insert that is suitable for input to
3945 /// VINSERTF128.
3946 bool X86::isVINSERTF128Index(SDNode *N) {
3947   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3948     return false;
3949
3950   // The index should be aligned on a 128-bit boundary.
3951   uint64_t Index =
3952     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3953
3954   unsigned VL = N->getValueType(0).getVectorNumElements();
3955   unsigned VBits = N->getValueType(0).getSizeInBits();
3956   unsigned ElSize = VBits / VL;
3957   bool Result = (Index * ElSize) % 128 == 0;
3958
3959   return Result;
3960 }
3961
3962 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3963 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3964 /// Handles 128-bit and 256-bit.
3965 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3966   EVT VT = N->getValueType(0);
3967
3968   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3969          "Unsupported vector type for PSHUF/SHUFP");
3970
3971   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3972   // independently on 128-bit lanes.
3973   unsigned NumElts = VT.getVectorNumElements();
3974   unsigned NumLanes = VT.getSizeInBits()/128;
3975   unsigned NumLaneElts = NumElts/NumLanes;
3976
3977   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3978          "Only supports 2 or 4 elements per lane");
3979
3980   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3981   unsigned Mask = 0;
3982   for (unsigned i = 0; i != NumElts; ++i) {
3983     int Elt = N->getMaskElt(i);
3984     if (Elt < 0) continue;
3985     Elt &= NumLaneElts - 1;
3986     unsigned ShAmt = (i << Shift) % 8;
3987     Mask |= Elt << ShAmt;
3988   }
3989
3990   return Mask;
3991 }
3992
3993 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3994 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3995 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3996   EVT VT = N->getValueType(0);
3997
3998   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3999          "Unsupported vector type for PSHUFHW");
4000
4001   unsigned NumElts = VT.getVectorNumElements();
4002
4003   unsigned Mask = 0;
4004   for (unsigned l = 0; l != NumElts; l += 8) {
4005     // 8 nodes per lane, but we only care about the last 4.
4006     for (unsigned i = 0; i < 4; ++i) {
4007       int Elt = N->getMaskElt(l+i+4);
4008       if (Elt < 0) continue;
4009       Elt &= 0x3; // only 2-bits.
4010       Mask |= Elt << (i * 2);
4011     }
4012   }
4013
4014   return Mask;
4015 }
4016
4017 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4018 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4019 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4020   EVT VT = N->getValueType(0);
4021
4022   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4023          "Unsupported vector type for PSHUFHW");
4024
4025   unsigned NumElts = VT.getVectorNumElements();
4026
4027   unsigned Mask = 0;
4028   for (unsigned l = 0; l != NumElts; l += 8) {
4029     // 8 nodes per lane, but we only care about the first 4.
4030     for (unsigned i = 0; i < 4; ++i) {
4031       int Elt = N->getMaskElt(l+i);
4032       if (Elt < 0) continue;
4033       Elt &= 0x3; // only 2-bits
4034       Mask |= Elt << (i * 2);
4035     }
4036   }
4037
4038   return Mask;
4039 }
4040
4041 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4042 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4043 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4044   EVT VT = SVOp->getValueType(0);
4045   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4046
4047   unsigned NumElts = VT.getVectorNumElements();
4048   unsigned NumLanes = VT.getSizeInBits()/128;
4049   unsigned NumLaneElts = NumElts/NumLanes;
4050
4051   int Val = 0;
4052   unsigned i;
4053   for (i = 0; i != NumElts; ++i) {
4054     Val = SVOp->getMaskElt(i);
4055     if (Val >= 0)
4056       break;
4057   }
4058   if (Val >= (int)NumElts)
4059     Val -= NumElts - NumLaneElts;
4060
4061   assert(Val - i > 0 && "PALIGNR imm should be positive");
4062   return (Val - i) * EltSize;
4063 }
4064
4065 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4066 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4067 /// instructions.
4068 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4069   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4070     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4071
4072   uint64_t Index =
4073     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4074
4075   EVT VecVT = N->getOperand(0).getValueType();
4076   EVT ElVT = VecVT.getVectorElementType();
4077
4078   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4079   return Index / NumElemsPerChunk;
4080 }
4081
4082 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4083 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4084 /// instructions.
4085 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4086   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4087     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4088
4089   uint64_t Index =
4090     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4091
4092   EVT VecVT = N->getValueType(0);
4093   EVT ElVT = VecVT.getVectorElementType();
4094
4095   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4096   return Index / NumElemsPerChunk;
4097 }
4098
4099 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4100 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4101 /// Handles 256-bit.
4102 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4103   EVT VT = N->getValueType(0);
4104
4105   unsigned NumElts = VT.getVectorNumElements();
4106
4107   assert((VT.is256BitVector() && NumElts == 4) &&
4108          "Unsupported vector type for VPERMQ/VPERMPD");
4109
4110   unsigned Mask = 0;
4111   for (unsigned i = 0; i != NumElts; ++i) {
4112     int Elt = N->getMaskElt(i);
4113     if (Elt < 0)
4114       continue;
4115     Mask |= Elt << (i*2);
4116   }
4117
4118   return Mask;
4119 }
4120 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4121 /// constant +0.0.
4122 bool X86::isZeroNode(SDValue Elt) {
4123   return ((isa<ConstantSDNode>(Elt) &&
4124            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4125           (isa<ConstantFPSDNode>(Elt) &&
4126            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4127 }
4128
4129 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4130 /// their permute mask.
4131 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4132                                     SelectionDAG &DAG) {
4133   EVT VT = SVOp->getValueType(0);
4134   unsigned NumElems = VT.getVectorNumElements();
4135   SmallVector<int, 8> MaskVec;
4136
4137   for (unsigned i = 0; i != NumElems; ++i) {
4138     int Idx = SVOp->getMaskElt(i);
4139     if (Idx >= 0) {
4140       if (Idx < (int)NumElems)
4141         Idx += NumElems;
4142       else
4143         Idx -= NumElems;
4144     }
4145     MaskVec.push_back(Idx);
4146   }
4147   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4148                               SVOp->getOperand(0), &MaskVec[0]);
4149 }
4150
4151 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4152 /// match movhlps. The lower half elements should come from upper half of
4153 /// V1 (and in order), and the upper half elements should come from the upper
4154 /// half of V2 (and in order).
4155 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4156   if (!VT.is128BitVector())
4157     return false;
4158   if (VT.getVectorNumElements() != 4)
4159     return false;
4160   for (unsigned i = 0, e = 2; i != e; ++i)
4161     if (!isUndefOrEqual(Mask[i], i+2))
4162       return false;
4163   for (unsigned i = 2; i != 4; ++i)
4164     if (!isUndefOrEqual(Mask[i], i+4))
4165       return false;
4166   return true;
4167 }
4168
4169 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4170 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4171 /// required.
4172 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4173   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4174     return false;
4175   N = N->getOperand(0).getNode();
4176   if (!ISD::isNON_EXTLoad(N))
4177     return false;
4178   if (LD)
4179     *LD = cast<LoadSDNode>(N);
4180   return true;
4181 }
4182
4183 // Test whether the given value is a vector value which will be legalized
4184 // into a load.
4185 static bool WillBeConstantPoolLoad(SDNode *N) {
4186   if (N->getOpcode() != ISD::BUILD_VECTOR)
4187     return false;
4188
4189   // Check for any non-constant elements.
4190   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4191     switch (N->getOperand(i).getNode()->getOpcode()) {
4192     case ISD::UNDEF:
4193     case ISD::ConstantFP:
4194     case ISD::Constant:
4195       break;
4196     default:
4197       return false;
4198     }
4199
4200   // Vectors of all-zeros and all-ones are materialized with special
4201   // instructions rather than being loaded.
4202   return !ISD::isBuildVectorAllZeros(N) &&
4203          !ISD::isBuildVectorAllOnes(N);
4204 }
4205
4206 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4207 /// match movlp{s|d}. The lower half elements should come from lower half of
4208 /// V1 (and in order), and the upper half elements should come from the upper
4209 /// half of V2 (and in order). And since V1 will become the source of the
4210 /// MOVLP, it must be either a vector load or a scalar load to vector.
4211 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4212                                ArrayRef<int> Mask, EVT VT) {
4213   if (!VT.is128BitVector())
4214     return false;
4215
4216   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4217     return false;
4218   // Is V2 is a vector load, don't do this transformation. We will try to use
4219   // load folding shufps op.
4220   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4221     return false;
4222
4223   unsigned NumElems = VT.getVectorNumElements();
4224
4225   if (NumElems != 2 && NumElems != 4)
4226     return false;
4227   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4228     if (!isUndefOrEqual(Mask[i], i))
4229       return false;
4230   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4231     if (!isUndefOrEqual(Mask[i], i+NumElems))
4232       return false;
4233   return true;
4234 }
4235
4236 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4237 /// all the same.
4238 static bool isSplatVector(SDNode *N) {
4239   if (N->getOpcode() != ISD::BUILD_VECTOR)
4240     return false;
4241
4242   SDValue SplatValue = N->getOperand(0);
4243   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4244     if (N->getOperand(i) != SplatValue)
4245       return false;
4246   return true;
4247 }
4248
4249 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4250 /// to an zero vector.
4251 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4252 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4253   SDValue V1 = N->getOperand(0);
4254   SDValue V2 = N->getOperand(1);
4255   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4256   for (unsigned i = 0; i != NumElems; ++i) {
4257     int Idx = N->getMaskElt(i);
4258     if (Idx >= (int)NumElems) {
4259       unsigned Opc = V2.getOpcode();
4260       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4261         continue;
4262       if (Opc != ISD::BUILD_VECTOR ||
4263           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4264         return false;
4265     } else if (Idx >= 0) {
4266       unsigned Opc = V1.getOpcode();
4267       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4268         continue;
4269       if (Opc != ISD::BUILD_VECTOR ||
4270           !X86::isZeroNode(V1.getOperand(Idx)))
4271         return false;
4272     }
4273   }
4274   return true;
4275 }
4276
4277 /// getZeroVector - Returns a vector of specified type with all zero elements.
4278 ///
4279 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4280                              SelectionDAG &DAG, DebugLoc dl) {
4281   assert(VT.isVector() && "Expected a vector type");
4282   unsigned Size = VT.getSizeInBits();
4283
4284   // Always build SSE zero vectors as <4 x i32> bitcasted
4285   // to their dest type. This ensures they get CSE'd.
4286   SDValue Vec;
4287   if (Size == 128) {  // SSE
4288     if (Subtarget->hasSSE2()) {  // SSE2
4289       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4290       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4291     } else { // SSE1
4292       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4293       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4294     }
4295   } else if (Size == 256) { // AVX
4296     if (Subtarget->hasAVX2()) { // AVX2
4297       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4298       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4299       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4300     } else {
4301       // 256-bit logic and arithmetic instructions in AVX are all
4302       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4303       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4304       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4305       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4306     }
4307   } else
4308     llvm_unreachable("Unexpected vector type");
4309
4310   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4311 }
4312
4313 /// getOnesVector - Returns a vector of specified type with all bits set.
4314 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4315 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4316 /// Then bitcast to their original type, ensuring they get CSE'd.
4317 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4318                              DebugLoc dl) {
4319   assert(VT.isVector() && "Expected a vector type");
4320   unsigned Size = VT.getSizeInBits();
4321
4322   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4323   SDValue Vec;
4324   if (Size == 256) {
4325     if (HasAVX2) { // AVX2
4326       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4328     } else { // AVX
4329       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4330       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4331     }
4332   } else if (Size == 128) {
4333     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4334   } else
4335     llvm_unreachable("Unexpected vector type");
4336
4337   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4338 }
4339
4340 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4341 /// that point to V2 points to its first element.
4342 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4343   for (unsigned i = 0; i != NumElems; ++i) {
4344     if (Mask[i] > (int)NumElems) {
4345       Mask[i] = NumElems;
4346     }
4347   }
4348 }
4349
4350 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4351 /// operation of specified width.
4352 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4353                        SDValue V2) {
4354   unsigned NumElems = VT.getVectorNumElements();
4355   SmallVector<int, 8> Mask;
4356   Mask.push_back(NumElems);
4357   for (unsigned i = 1; i != NumElems; ++i)
4358     Mask.push_back(i);
4359   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4360 }
4361
4362 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4363 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4364                           SDValue V2) {
4365   unsigned NumElems = VT.getVectorNumElements();
4366   SmallVector<int, 8> Mask;
4367   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4368     Mask.push_back(i);
4369     Mask.push_back(i + NumElems);
4370   }
4371   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4372 }
4373
4374 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4375 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4376                           SDValue V2) {
4377   unsigned NumElems = VT.getVectorNumElements();
4378   SmallVector<int, 8> Mask;
4379   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4380     Mask.push_back(i + Half);
4381     Mask.push_back(i + NumElems + Half);
4382   }
4383   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4384 }
4385
4386 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4387 // a generic shuffle instruction because the target has no such instructions.
4388 // Generate shuffles which repeat i16 and i8 several times until they can be
4389 // represented by v4f32 and then be manipulated by target suported shuffles.
4390 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4391   EVT VT = V.getValueType();
4392   int NumElems = VT.getVectorNumElements();
4393   DebugLoc dl = V.getDebugLoc();
4394
4395   while (NumElems > 4) {
4396     if (EltNo < NumElems/2) {
4397       V = getUnpackl(DAG, dl, VT, V, V);
4398     } else {
4399       V = getUnpackh(DAG, dl, VT, V, V);
4400       EltNo -= NumElems/2;
4401     }
4402     NumElems >>= 1;
4403   }
4404   return V;
4405 }
4406
4407 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4408 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4409   EVT VT = V.getValueType();
4410   DebugLoc dl = V.getDebugLoc();
4411   unsigned Size = VT.getSizeInBits();
4412
4413   if (Size == 128) {
4414     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4415     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4416     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4417                              &SplatMask[0]);
4418   } else if (Size == 256) {
4419     // To use VPERMILPS to splat scalars, the second half of indicies must
4420     // refer to the higher part, which is a duplication of the lower one,
4421     // because VPERMILPS can only handle in-lane permutations.
4422     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4423                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4424
4425     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4426     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4427                              &SplatMask[0]);
4428   } else
4429     llvm_unreachable("Vector size not supported");
4430
4431   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4432 }
4433
4434 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4435 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4436   EVT SrcVT = SV->getValueType(0);
4437   SDValue V1 = SV->getOperand(0);
4438   DebugLoc dl = SV->getDebugLoc();
4439
4440   int EltNo = SV->getSplatIndex();
4441   int NumElems = SrcVT.getVectorNumElements();
4442   unsigned Size = SrcVT.getSizeInBits();
4443
4444   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4445           "Unknown how to promote splat for type");
4446
4447   // Extract the 128-bit part containing the splat element and update
4448   // the splat element index when it refers to the higher register.
4449   if (Size == 256) {
4450     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4451     if (EltNo >= NumElems/2)
4452       EltNo -= NumElems/2;
4453   }
4454
4455   // All i16 and i8 vector types can't be used directly by a generic shuffle
4456   // instruction because the target has no such instruction. Generate shuffles
4457   // which repeat i16 and i8 several times until they fit in i32, and then can
4458   // be manipulated by target suported shuffles.
4459   EVT EltVT = SrcVT.getVectorElementType();
4460   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4461     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4462
4463   // Recreate the 256-bit vector and place the same 128-bit vector
4464   // into the low and high part. This is necessary because we want
4465   // to use VPERM* to shuffle the vectors
4466   if (Size == 256) {
4467     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4468   }
4469
4470   return getLegalSplat(DAG, V1, EltNo);
4471 }
4472
4473 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4474 /// vector of zero or undef vector.  This produces a shuffle where the low
4475 /// element of V2 is swizzled into the zero/undef vector, landing at element
4476 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4477 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4478                                            bool IsZero,
4479                                            const X86Subtarget *Subtarget,
4480                                            SelectionDAG &DAG) {
4481   EVT VT = V2.getValueType();
4482   SDValue V1 = IsZero
4483     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4484   unsigned NumElems = VT.getVectorNumElements();
4485   SmallVector<int, 16> MaskVec;
4486   for (unsigned i = 0; i != NumElems; ++i)
4487     // If this is the insertion idx, put the low elt of V2 here.
4488     MaskVec.push_back(i == Idx ? NumElems : i);
4489   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4490 }
4491
4492 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4493 /// target specific opcode. Returns true if the Mask could be calculated.
4494 /// Sets IsUnary to true if only uses one source.
4495 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4496                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4497   unsigned NumElems = VT.getVectorNumElements();
4498   SDValue ImmN;
4499
4500   IsUnary = false;
4501   switch(N->getOpcode()) {
4502   case X86ISD::SHUFP:
4503     ImmN = N->getOperand(N->getNumOperands()-1);
4504     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505     break;
4506   case X86ISD::UNPCKH:
4507     DecodeUNPCKHMask(VT, Mask);
4508     break;
4509   case X86ISD::UNPCKL:
4510     DecodeUNPCKLMask(VT, Mask);
4511     break;
4512   case X86ISD::MOVHLPS:
4513     DecodeMOVHLPSMask(NumElems, Mask);
4514     break;
4515   case X86ISD::MOVLHPS:
4516     DecodeMOVLHPSMask(NumElems, Mask);
4517     break;
4518   case X86ISD::PSHUFD:
4519   case X86ISD::VPERMILP:
4520     ImmN = N->getOperand(N->getNumOperands()-1);
4521     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4522     IsUnary = true;
4523     break;
4524   case X86ISD::PSHUFHW:
4525     ImmN = N->getOperand(N->getNumOperands()-1);
4526     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4527     IsUnary = true;
4528     break;
4529   case X86ISD::PSHUFLW:
4530     ImmN = N->getOperand(N->getNumOperands()-1);
4531     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4532     IsUnary = true;
4533     break;
4534   case X86ISD::VPERMI:
4535     ImmN = N->getOperand(N->getNumOperands()-1);
4536     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537     IsUnary = true;
4538     break;
4539   case X86ISD::MOVSS:
4540   case X86ISD::MOVSD: {
4541     // The index 0 always comes from the first element of the second source,
4542     // this is why MOVSS and MOVSD are used in the first place. The other
4543     // elements come from the other positions of the first source vector
4544     Mask.push_back(NumElems);
4545     for (unsigned i = 1; i != NumElems; ++i) {
4546       Mask.push_back(i);
4547     }
4548     break;
4549   }
4550   case X86ISD::VPERM2X128:
4551     ImmN = N->getOperand(N->getNumOperands()-1);
4552     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4553     if (Mask.empty()) return false;
4554     break;
4555   case X86ISD::MOVDDUP:
4556   case X86ISD::MOVLHPD:
4557   case X86ISD::MOVLPD:
4558   case X86ISD::MOVLPS:
4559   case X86ISD::MOVSHDUP:
4560   case X86ISD::MOVSLDUP:
4561   case X86ISD::PALIGN:
4562     // Not yet implemented
4563     return false;
4564   default: llvm_unreachable("unknown target shuffle node");
4565   }
4566
4567   return true;
4568 }
4569
4570 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4571 /// element of the result of the vector shuffle.
4572 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4573                                    unsigned Depth) {
4574   if (Depth == 6)
4575     return SDValue();  // Limit search depth.
4576
4577   SDValue V = SDValue(N, 0);
4578   EVT VT = V.getValueType();
4579   unsigned Opcode = V.getOpcode();
4580
4581   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4582   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4583     int Elt = SV->getMaskElt(Index);
4584
4585     if (Elt < 0)
4586       return DAG.getUNDEF(VT.getVectorElementType());
4587
4588     unsigned NumElems = VT.getVectorNumElements();
4589     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4590                                          : SV->getOperand(1);
4591     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4592   }
4593
4594   // Recurse into target specific vector shuffles to find scalars.
4595   if (isTargetShuffle(Opcode)) {
4596     MVT ShufVT = V.getValueType().getSimpleVT();
4597     unsigned NumElems = ShufVT.getVectorNumElements();
4598     SmallVector<int, 16> ShuffleMask;
4599     SDValue ImmN;
4600     bool IsUnary;
4601
4602     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4603       return SDValue();
4604
4605     int Elt = ShuffleMask[Index];
4606     if (Elt < 0)
4607       return DAG.getUNDEF(ShufVT.getVectorElementType());
4608
4609     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4610                                          : N->getOperand(1);
4611     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4612                                Depth+1);
4613   }
4614
4615   // Actual nodes that may contain scalar elements
4616   if (Opcode == ISD::BITCAST) {
4617     V = V.getOperand(0);
4618     EVT SrcVT = V.getValueType();
4619     unsigned NumElems = VT.getVectorNumElements();
4620
4621     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4622       return SDValue();
4623   }
4624
4625   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4626     return (Index == 0) ? V.getOperand(0)
4627                         : DAG.getUNDEF(VT.getVectorElementType());
4628
4629   if (V.getOpcode() == ISD::BUILD_VECTOR)
4630     return V.getOperand(Index);
4631
4632   return SDValue();
4633 }
4634
4635 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4636 /// shuffle operation which come from a consecutively from a zero. The
4637 /// search can start in two different directions, from left or right.
4638 static
4639 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4640                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4641   unsigned i;
4642   for (i = 0; i != NumElems; ++i) {
4643     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4644     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4645     if (!(Elt.getNode() &&
4646          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4647       break;
4648   }
4649
4650   return i;
4651 }
4652
4653 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4654 /// correspond consecutively to elements from one of the vector operands,
4655 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4656 static
4657 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4658                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4659                               unsigned NumElems, unsigned &OpNum) {
4660   bool SeenV1 = false;
4661   bool SeenV2 = false;
4662
4663   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4664     int Idx = SVOp->getMaskElt(i);
4665     // Ignore undef indicies
4666     if (Idx < 0)
4667       continue;
4668
4669     if (Idx < (int)NumElems)
4670       SeenV1 = true;
4671     else
4672       SeenV2 = true;
4673
4674     // Only accept consecutive elements from the same vector
4675     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4676       return false;
4677   }
4678
4679   OpNum = SeenV1 ? 0 : 1;
4680   return true;
4681 }
4682
4683 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4684 /// logical left shift of a vector.
4685 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4686                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4687   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4688   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4689               false /* check zeros from right */, DAG);
4690   unsigned OpSrc;
4691
4692   if (!NumZeros)
4693     return false;
4694
4695   // Considering the elements in the mask that are not consecutive zeros,
4696   // check if they consecutively come from only one of the source vectors.
4697   //
4698   //               V1 = {X, A, B, C}     0
4699   //                         \  \  \    /
4700   //   vector_shuffle V1, V2 <1, 2, 3, X>
4701   //
4702   if (!isShuffleMaskConsecutive(SVOp,
4703             0,                   // Mask Start Index
4704             NumElems-NumZeros,   // Mask End Index(exclusive)
4705             NumZeros,            // Where to start looking in the src vector
4706             NumElems,            // Number of elements in vector
4707             OpSrc))              // Which source operand ?
4708     return false;
4709
4710   isLeft = false;
4711   ShAmt = NumZeros;
4712   ShVal = SVOp->getOperand(OpSrc);
4713   return true;
4714 }
4715
4716 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4717 /// logical left shift of a vector.
4718 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4719                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4720   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4721   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4722               true /* check zeros from left */, DAG);
4723   unsigned OpSrc;
4724
4725   if (!NumZeros)
4726     return false;
4727
4728   // Considering the elements in the mask that are not consecutive zeros,
4729   // check if they consecutively come from only one of the source vectors.
4730   //
4731   //                           0    { A, B, X, X } = V2
4732   //                          / \    /  /
4733   //   vector_shuffle V1, V2 <X, X, 4, 5>
4734   //
4735   if (!isShuffleMaskConsecutive(SVOp,
4736             NumZeros,     // Mask Start Index
4737             NumElems,     // Mask End Index(exclusive)
4738             0,            // Where to start looking in the src vector
4739             NumElems,     // Number of elements in vector
4740             OpSrc))       // Which source operand ?
4741     return false;
4742
4743   isLeft = true;
4744   ShAmt = NumZeros;
4745   ShVal = SVOp->getOperand(OpSrc);
4746   return true;
4747 }
4748
4749 /// isVectorShift - Returns true if the shuffle can be implemented as a
4750 /// logical left or right shift of a vector.
4751 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4752                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4753   // Although the logic below support any bitwidth size, there are no
4754   // shift instructions which handle more than 128-bit vectors.
4755   if (!SVOp->getValueType(0).is128BitVector())
4756     return false;
4757
4758   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4759       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4760     return true;
4761
4762   return false;
4763 }
4764
4765 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4766 ///
4767 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4768                                        unsigned NumNonZero, unsigned NumZero,
4769                                        SelectionDAG &DAG,
4770                                        const X86Subtarget* Subtarget,
4771                                        const TargetLowering &TLI) {
4772   if (NumNonZero > 8)
4773     return SDValue();
4774
4775   DebugLoc dl = Op.getDebugLoc();
4776   SDValue V(0, 0);
4777   bool First = true;
4778   for (unsigned i = 0; i < 16; ++i) {
4779     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4780     if (ThisIsNonZero && First) {
4781       if (NumZero)
4782         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4783       else
4784         V = DAG.getUNDEF(MVT::v8i16);
4785       First = false;
4786     }
4787
4788     if ((i & 1) != 0) {
4789       SDValue ThisElt(0, 0), LastElt(0, 0);
4790       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4791       if (LastIsNonZero) {
4792         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4793                               MVT::i16, Op.getOperand(i-1));
4794       }
4795       if (ThisIsNonZero) {
4796         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4797         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4798                               ThisElt, DAG.getConstant(8, MVT::i8));
4799         if (LastIsNonZero)
4800           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4801       } else
4802         ThisElt = LastElt;
4803
4804       if (ThisElt.getNode())
4805         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4806                         DAG.getIntPtrConstant(i/2));
4807     }
4808   }
4809
4810   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4811 }
4812
4813 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4814 ///
4815 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4816                                      unsigned NumNonZero, unsigned NumZero,
4817                                      SelectionDAG &DAG,
4818                                      const X86Subtarget* Subtarget,
4819                                      const TargetLowering &TLI) {
4820   if (NumNonZero > 4)
4821     return SDValue();
4822
4823   DebugLoc dl = Op.getDebugLoc();
4824   SDValue V(0, 0);
4825   bool First = true;
4826   for (unsigned i = 0; i < 8; ++i) {
4827     bool isNonZero = (NonZeros & (1 << i)) != 0;
4828     if (isNonZero) {
4829       if (First) {
4830         if (NumZero)
4831           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4832         else
4833           V = DAG.getUNDEF(MVT::v8i16);
4834         First = false;
4835       }
4836       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4837                       MVT::v8i16, V, Op.getOperand(i),
4838                       DAG.getIntPtrConstant(i));
4839     }
4840   }
4841
4842   return V;
4843 }
4844
4845 /// getVShift - Return a vector logical shift node.
4846 ///
4847 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4848                          unsigned NumBits, SelectionDAG &DAG,
4849                          const TargetLowering &TLI, DebugLoc dl) {
4850   assert(VT.is128BitVector() && "Unknown type for VShift");
4851   EVT ShVT = MVT::v2i64;
4852   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4853   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4854   return DAG.getNode(ISD::BITCAST, dl, VT,
4855                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4856                              DAG.getConstant(NumBits,
4857                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4858 }
4859
4860 SDValue
4861 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4862                                           SelectionDAG &DAG) const {
4863
4864   // Check if the scalar load can be widened into a vector load. And if
4865   // the address is "base + cst" see if the cst can be "absorbed" into
4866   // the shuffle mask.
4867   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4868     SDValue Ptr = LD->getBasePtr();
4869     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4870       return SDValue();
4871     EVT PVT = LD->getValueType(0);
4872     if (PVT != MVT::i32 && PVT != MVT::f32)
4873       return SDValue();
4874
4875     int FI = -1;
4876     int64_t Offset = 0;
4877     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4878       FI = FINode->getIndex();
4879       Offset = 0;
4880     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4881                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4882       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4883       Offset = Ptr.getConstantOperandVal(1);
4884       Ptr = Ptr.getOperand(0);
4885     } else {
4886       return SDValue();
4887     }
4888
4889     // FIXME: 256-bit vector instructions don't require a strict alignment,
4890     // improve this code to support it better.
4891     unsigned RequiredAlign = VT.getSizeInBits()/8;
4892     SDValue Chain = LD->getChain();
4893     // Make sure the stack object alignment is at least 16 or 32.
4894     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4895     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4896       if (MFI->isFixedObjectIndex(FI)) {
4897         // Can't change the alignment. FIXME: It's possible to compute
4898         // the exact stack offset and reference FI + adjust offset instead.
4899         // If someone *really* cares about this. That's the way to implement it.
4900         return SDValue();
4901       } else {
4902         MFI->setObjectAlignment(FI, RequiredAlign);
4903       }
4904     }
4905
4906     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4907     // Ptr + (Offset & ~15).
4908     if (Offset < 0)
4909       return SDValue();
4910     if ((Offset % RequiredAlign) & 3)
4911       return SDValue();
4912     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4913     if (StartOffset)
4914       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4915                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4916
4917     int EltNo = (Offset - StartOffset) >> 2;
4918     unsigned NumElems = VT.getVectorNumElements();
4919
4920     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4921     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4922                              LD->getPointerInfo().getWithOffset(StartOffset),
4923                              false, false, false, 0);
4924
4925     SmallVector<int, 8> Mask;
4926     for (unsigned i = 0; i != NumElems; ++i)
4927       Mask.push_back(EltNo);
4928
4929     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4930   }
4931
4932   return SDValue();
4933 }
4934
4935 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4936 /// vector of type 'VT', see if the elements can be replaced by a single large
4937 /// load which has the same value as a build_vector whose operands are 'elts'.
4938 ///
4939 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4940 ///
4941 /// FIXME: we'd also like to handle the case where the last elements are zero
4942 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4943 /// There's even a handy isZeroNode for that purpose.
4944 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4945                                         DebugLoc &DL, SelectionDAG &DAG) {
4946   EVT EltVT = VT.getVectorElementType();
4947   unsigned NumElems = Elts.size();
4948
4949   LoadSDNode *LDBase = NULL;
4950   unsigned LastLoadedElt = -1U;
4951
4952   // For each element in the initializer, see if we've found a load or an undef.
4953   // If we don't find an initial load element, or later load elements are
4954   // non-consecutive, bail out.
4955   for (unsigned i = 0; i < NumElems; ++i) {
4956     SDValue Elt = Elts[i];
4957
4958     if (!Elt.getNode() ||
4959         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4960       return SDValue();
4961     if (!LDBase) {
4962       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4963         return SDValue();
4964       LDBase = cast<LoadSDNode>(Elt.getNode());
4965       LastLoadedElt = i;
4966       continue;
4967     }
4968     if (Elt.getOpcode() == ISD::UNDEF)
4969       continue;
4970
4971     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4972     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4973       return SDValue();
4974     LastLoadedElt = i;
4975   }
4976
4977   // If we have found an entire vector of loads and undefs, then return a large
4978   // load of the entire vector width starting at the base pointer.  If we found
4979   // consecutive loads for the low half, generate a vzext_load node.
4980   if (LastLoadedElt == NumElems - 1) {
4981     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4982       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4983                          LDBase->getPointerInfo(),
4984                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4985                          LDBase->isInvariant(), 0);
4986     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4987                        LDBase->getPointerInfo(),
4988                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4989                        LDBase->isInvariant(), LDBase->getAlignment());
4990   }
4991   if (NumElems == 4 && LastLoadedElt == 1 &&
4992       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4993     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4994     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4995     SDValue ResNode =
4996         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4997                                 LDBase->getPointerInfo(),
4998                                 LDBase->getAlignment(),
4999                                 false/*isVolatile*/, true/*ReadMem*/,
5000                                 false/*WriteMem*/);
5001
5002     // Make sure the newly-created LOAD is in the same position as LDBase in
5003     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5004     // update uses of LDBase's output chain to use the TokenFactor.
5005     if (LDBase->hasAnyUseOfValue(1)) {
5006       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5007                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5008       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5009       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5010                              SDValue(ResNode.getNode(), 1));
5011     }
5012
5013     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5014   }
5015   return SDValue();
5016 }
5017
5018 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5019 /// to generate a splat value for the following cases:
5020 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5021 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5022 /// a scalar load, or a constant.
5023 /// The VBROADCAST node is returned when a pattern is found,
5024 /// or SDValue() otherwise.
5025 SDValue
5026 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5027   if (!Subtarget->hasAVX())
5028     return SDValue();
5029
5030   EVT VT = Op.getValueType();
5031   DebugLoc dl = Op.getDebugLoc();
5032
5033   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5034          "Unsupported vector type for broadcast.");
5035
5036   SDValue Ld;
5037   bool ConstSplatVal;
5038
5039   switch (Op.getOpcode()) {
5040     default:
5041       // Unknown pattern found.
5042       return SDValue();
5043
5044     case ISD::BUILD_VECTOR: {
5045       // The BUILD_VECTOR node must be a splat.
5046       if (!isSplatVector(Op.getNode()))
5047         return SDValue();
5048
5049       Ld = Op.getOperand(0);
5050       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5051                      Ld.getOpcode() == ISD::ConstantFP);
5052
5053       // The suspected load node has several users. Make sure that all
5054       // of its users are from the BUILD_VECTOR node.
5055       // Constants may have multiple users.
5056       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5057         return SDValue();
5058       break;
5059     }
5060
5061     case ISD::VECTOR_SHUFFLE: {
5062       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5063
5064       // Shuffles must have a splat mask where the first element is
5065       // broadcasted.
5066       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5067         return SDValue();
5068
5069       SDValue Sc = Op.getOperand(0);
5070       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5071           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5072
5073         if (!Subtarget->hasAVX2())
5074           return SDValue();
5075
5076         // Use the register form of the broadcast instruction available on AVX2.
5077         if (VT.is256BitVector())
5078           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5079         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5080       }
5081
5082       Ld = Sc.getOperand(0);
5083       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5084                        Ld.getOpcode() == ISD::ConstantFP);
5085
5086       // The scalar_to_vector node and the suspected
5087       // load node must have exactly one user.
5088       // Constants may have multiple users.
5089       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5090         return SDValue();
5091       break;
5092     }
5093   }
5094
5095   bool Is256 = VT.is256BitVector();
5096
5097   // Handle the broadcasting a single constant scalar from the constant pool
5098   // into a vector. On Sandybridge it is still better to load a constant vector
5099   // from the constant pool and not to broadcast it from a scalar.
5100   if (ConstSplatVal && Subtarget->hasAVX2()) {
5101     EVT CVT = Ld.getValueType();
5102     assert(!CVT.isVector() && "Must not broadcast a vector type");
5103     unsigned ScalarSize = CVT.getSizeInBits();
5104
5105     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5106       const Constant *C = 0;
5107       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5108         C = CI->getConstantIntValue();
5109       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5110         C = CF->getConstantFPValue();
5111
5112       assert(C && "Invalid constant type");
5113
5114       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5115       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5116       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5117                        MachinePointerInfo::getConstantPool(),
5118                        false, false, false, Alignment);
5119
5120       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5121     }
5122   }
5123
5124   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5125   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5126
5127   // Handle AVX2 in-register broadcasts.
5128   if (!IsLoad && Subtarget->hasAVX2() &&
5129       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5130     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5131
5132   // The scalar source must be a normal load.
5133   if (!IsLoad)
5134     return SDValue();
5135
5136   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5137     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5138
5139   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5140   // double since there is no vbroadcastsd xmm
5141   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5142     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5143       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5144   }
5145
5146   // Unsupported broadcast.
5147   return SDValue();
5148 }
5149
5150 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5151 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5152 // constraint of matching input/output vector elements.
5153 SDValue
5154 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5155   DebugLoc DL = Op.getDebugLoc();
5156   SDNode *N = Op.getNode();
5157   EVT VT = Op.getValueType();
5158   unsigned NumElts = Op.getNumOperands();
5159
5160   // Check supported types and sub-targets.
5161   //
5162   // Only v2f32 -> v2f64 needs special handling.
5163   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5164     return SDValue();
5165
5166   SDValue VecIn;
5167   EVT VecInVT;
5168   SmallVector<int, 8> Mask;
5169   EVT SrcVT = MVT::Other;
5170
5171   // Check the patterns could be translated into X86vfpext.
5172   for (unsigned i = 0; i < NumElts; ++i) {
5173     SDValue In = N->getOperand(i);
5174     unsigned Opcode = In.getOpcode();
5175
5176     // Skip if the element is undefined.
5177     if (Opcode == ISD::UNDEF) {
5178       Mask.push_back(-1);
5179       continue;
5180     }
5181
5182     // Quit if one of the elements is not defined from 'fpext'.
5183     if (Opcode != ISD::FP_EXTEND)
5184       return SDValue();
5185
5186     // Check how the source of 'fpext' is defined.
5187     SDValue L2In = In.getOperand(0);
5188     EVT L2InVT = L2In.getValueType();
5189
5190     // Check the original type
5191     if (SrcVT == MVT::Other)
5192       SrcVT = L2InVT;
5193     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5194       return SDValue();
5195
5196     // Check whether the value being 'fpext'ed is extracted from the same
5197     // source.
5198     Opcode = L2In.getOpcode();
5199
5200     // Quit if it's not extracted with a constant index.
5201     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5202         !isa<ConstantSDNode>(L2In.getOperand(1)))
5203       return SDValue();
5204
5205     SDValue ExtractedFromVec = L2In.getOperand(0);
5206
5207     if (VecIn.getNode() == 0) {
5208       VecIn = ExtractedFromVec;
5209       VecInVT = ExtractedFromVec.getValueType();
5210     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5211       return SDValue();
5212
5213     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5214   }
5215
5216   // Quit if all operands of BUILD_VECTOR are undefined.
5217   if (!VecIn.getNode())
5218     return SDValue();
5219
5220   // Fill the remaining mask as undef.
5221   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5222     Mask.push_back(-1);
5223
5224   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5225                      DAG.getVectorShuffle(VecInVT, DL,
5226                                           VecIn, DAG.getUNDEF(VecInVT),
5227                                           &Mask[0]));
5228 }
5229
5230 SDValue
5231 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5232   DebugLoc dl = Op.getDebugLoc();
5233
5234   EVT VT = Op.getValueType();
5235   EVT ExtVT = VT.getVectorElementType();
5236   unsigned NumElems = Op.getNumOperands();
5237
5238   // Vectors containing all zeros can be matched by pxor and xorps later
5239   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5240     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5241     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5242     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5243       return Op;
5244
5245     return getZeroVector(VT, Subtarget, DAG, dl);
5246   }
5247
5248   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5249   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5250   // vpcmpeqd on 256-bit vectors.
5251   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5252     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5253       return Op;
5254
5255     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5256   }
5257
5258   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5259   if (Broadcast.getNode())
5260     return Broadcast;
5261
5262   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5263   if (FpExt.getNode())
5264     return FpExt;
5265
5266   unsigned EVTBits = ExtVT.getSizeInBits();
5267
5268   unsigned NumZero  = 0;
5269   unsigned NumNonZero = 0;
5270   unsigned NonZeros = 0;
5271   bool IsAllConstants = true;
5272   SmallSet<SDValue, 8> Values;
5273   for (unsigned i = 0; i < NumElems; ++i) {
5274     SDValue Elt = Op.getOperand(i);
5275     if (Elt.getOpcode() == ISD::UNDEF)
5276       continue;
5277     Values.insert(Elt);
5278     if (Elt.getOpcode() != ISD::Constant &&
5279         Elt.getOpcode() != ISD::ConstantFP)
5280       IsAllConstants = false;
5281     if (X86::isZeroNode(Elt))
5282       NumZero++;
5283     else {
5284       NonZeros |= (1 << i);
5285       NumNonZero++;
5286     }
5287   }
5288
5289   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5290   if (NumNonZero == 0)
5291     return DAG.getUNDEF(VT);
5292
5293   // Special case for single non-zero, non-undef, element.
5294   if (NumNonZero == 1) {
5295     unsigned Idx = CountTrailingZeros_32(NonZeros);
5296     SDValue Item = Op.getOperand(Idx);
5297
5298     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5299     // the value are obviously zero, truncate the value to i32 and do the
5300     // insertion that way.  Only do this if the value is non-constant or if the
5301     // value is a constant being inserted into element 0.  It is cheaper to do
5302     // a constant pool load than it is to do a movd + shuffle.
5303     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5304         (!IsAllConstants || Idx == 0)) {
5305       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5306         // Handle SSE only.
5307         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5308         EVT VecVT = MVT::v4i32;
5309         unsigned VecElts = 4;
5310
5311         // Truncate the value (which may itself be a constant) to i32, and
5312         // convert it to a vector with movd (S2V+shuffle to zero extend).
5313         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5314         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5315         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5316
5317         // Now we have our 32-bit value zero extended in the low element of
5318         // a vector.  If Idx != 0, swizzle it into place.
5319         if (Idx != 0) {
5320           SmallVector<int, 4> Mask;
5321           Mask.push_back(Idx);
5322           for (unsigned i = 1; i != VecElts; ++i)
5323             Mask.push_back(i);
5324           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5325                                       &Mask[0]);
5326         }
5327         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5328       }
5329     }
5330
5331     // If we have a constant or non-constant insertion into the low element of
5332     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5333     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5334     // depending on what the source datatype is.
5335     if (Idx == 0) {
5336       if (NumZero == 0)
5337         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5338
5339       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5340           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5341         if (VT.is256BitVector()) {
5342           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5343           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5344                              Item, DAG.getIntPtrConstant(0));
5345         }
5346         assert(VT.is128BitVector() && "Expected an SSE value type!");
5347         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5348         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5349         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5350       }
5351
5352       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5353         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5354         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5355         if (VT.is256BitVector()) {
5356           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5357           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5358         } else {
5359           assert(VT.is128BitVector() && "Expected an SSE value type!");
5360           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5361         }
5362         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5363       }
5364     }
5365
5366     // Is it a vector logical left shift?
5367     if (NumElems == 2 && Idx == 1 &&
5368         X86::isZeroNode(Op.getOperand(0)) &&
5369         !X86::isZeroNode(Op.getOperand(1))) {
5370       unsigned NumBits = VT.getSizeInBits();
5371       return getVShift(true, VT,
5372                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5373                                    VT, Op.getOperand(1)),
5374                        NumBits/2, DAG, *this, dl);
5375     }
5376
5377     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5378       return SDValue();
5379
5380     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5381     // is a non-constant being inserted into an element other than the low one,
5382     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5383     // movd/movss) to move this into the low element, then shuffle it into
5384     // place.
5385     if (EVTBits == 32) {
5386       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5387
5388       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5389       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5390       SmallVector<int, 8> MaskVec;
5391       for (unsigned i = 0; i != NumElems; ++i)
5392         MaskVec.push_back(i == Idx ? 0 : 1);
5393       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5394     }
5395   }
5396
5397   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5398   if (Values.size() == 1) {
5399     if (EVTBits == 32) {
5400       // Instead of a shuffle like this:
5401       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5402       // Check if it's possible to issue this instead.
5403       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5404       unsigned Idx = CountTrailingZeros_32(NonZeros);
5405       SDValue Item = Op.getOperand(Idx);
5406       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5407         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5408     }
5409     return SDValue();
5410   }
5411
5412   // A vector full of immediates; various special cases are already
5413   // handled, so this is best done with a single constant-pool load.
5414   if (IsAllConstants)
5415     return SDValue();
5416
5417   // For AVX-length vectors, build the individual 128-bit pieces and use
5418   // shuffles to put them in place.
5419   if (VT.is256BitVector()) {
5420     SmallVector<SDValue, 32> V;
5421     for (unsigned i = 0; i != NumElems; ++i)
5422       V.push_back(Op.getOperand(i));
5423
5424     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5425
5426     // Build both the lower and upper subvector.
5427     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5428     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5429                                 NumElems/2);
5430
5431     // Recreate the wider vector with the lower and upper part.
5432     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5433   }
5434
5435   // Let legalizer expand 2-wide build_vectors.
5436   if (EVTBits == 64) {
5437     if (NumNonZero == 1) {
5438       // One half is zero or undef.
5439       unsigned Idx = CountTrailingZeros_32(NonZeros);
5440       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5441                                  Op.getOperand(Idx));
5442       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5443     }
5444     return SDValue();
5445   }
5446
5447   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5448   if (EVTBits == 8 && NumElems == 16) {
5449     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5450                                         Subtarget, *this);
5451     if (V.getNode()) return V;
5452   }
5453
5454   if (EVTBits == 16 && NumElems == 8) {
5455     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5456                                       Subtarget, *this);
5457     if (V.getNode()) return V;
5458   }
5459
5460   // If element VT is == 32 bits, turn it into a number of shuffles.
5461   SmallVector<SDValue, 8> V(NumElems);
5462   if (NumElems == 4 && NumZero > 0) {
5463     for (unsigned i = 0; i < 4; ++i) {
5464       bool isZero = !(NonZeros & (1 << i));
5465       if (isZero)
5466         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5467       else
5468         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5469     }
5470
5471     for (unsigned i = 0; i < 2; ++i) {
5472       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5473         default: break;
5474         case 0:
5475           V[i] = V[i*2];  // Must be a zero vector.
5476           break;
5477         case 1:
5478           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5479           break;
5480         case 2:
5481           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5482           break;
5483         case 3:
5484           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5485           break;
5486       }
5487     }
5488
5489     bool Reverse1 = (NonZeros & 0x3) == 2;
5490     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5491     int MaskVec[] = {
5492       Reverse1 ? 1 : 0,
5493       Reverse1 ? 0 : 1,
5494       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5495       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5496     };
5497     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5498   }
5499
5500   if (Values.size() > 1 && VT.is128BitVector()) {
5501     // Check for a build vector of consecutive loads.
5502     for (unsigned i = 0; i < NumElems; ++i)
5503       V[i] = Op.getOperand(i);
5504
5505     // Check for elements which are consecutive loads.
5506     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5507     if (LD.getNode())
5508       return LD;
5509
5510     // For SSE 4.1, use insertps to put the high elements into the low element.
5511     if (getSubtarget()->hasSSE41()) {
5512       SDValue Result;
5513       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5514         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5515       else
5516         Result = DAG.getUNDEF(VT);
5517
5518       for (unsigned i = 1; i < NumElems; ++i) {
5519         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5520         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5521                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5522       }
5523       return Result;
5524     }
5525
5526     // Otherwise, expand into a number of unpckl*, start by extending each of
5527     // our (non-undef) elements to the full vector width with the element in the
5528     // bottom slot of the vector (which generates no code for SSE).
5529     for (unsigned i = 0; i < NumElems; ++i) {
5530       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5531         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5532       else
5533         V[i] = DAG.getUNDEF(VT);
5534     }
5535
5536     // Next, we iteratively mix elements, e.g. for v4f32:
5537     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5538     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5539     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5540     unsigned EltStride = NumElems >> 1;
5541     while (EltStride != 0) {
5542       for (unsigned i = 0; i < EltStride; ++i) {
5543         // If V[i+EltStride] is undef and this is the first round of mixing,
5544         // then it is safe to just drop this shuffle: V[i] is already in the
5545         // right place, the one element (since it's the first round) being
5546         // inserted as undef can be dropped.  This isn't safe for successive
5547         // rounds because they will permute elements within both vectors.
5548         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5549             EltStride == NumElems/2)
5550           continue;
5551
5552         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5553       }
5554       EltStride >>= 1;
5555     }
5556     return V[0];
5557   }
5558   return SDValue();
5559 }
5560
5561 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5562 // to create 256-bit vectors from two other 128-bit ones.
5563 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5564   DebugLoc dl = Op.getDebugLoc();
5565   EVT ResVT = Op.getValueType();
5566
5567   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5568
5569   SDValue V1 = Op.getOperand(0);
5570   SDValue V2 = Op.getOperand(1);
5571   unsigned NumElems = ResVT.getVectorNumElements();
5572
5573   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5574 }
5575
5576 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5577   assert(Op.getNumOperands() == 2);
5578
5579   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5580   // from two other 128-bit ones.
5581   return LowerAVXCONCAT_VECTORS(Op, DAG);
5582 }
5583
5584 // Try to lower a shuffle node into a simple blend instruction.
5585 static SDValue
5586 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5587                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5588   SDValue V1 = SVOp->getOperand(0);
5589   SDValue V2 = SVOp->getOperand(1);
5590   DebugLoc dl = SVOp->getDebugLoc();
5591   MVT VT = SVOp->getValueType(0).getSimpleVT();
5592   unsigned NumElems = VT.getVectorNumElements();
5593
5594   if (!Subtarget->hasSSE41())
5595     return SDValue();
5596
5597   unsigned ISDNo = 0;
5598   MVT OpTy;
5599
5600   switch (VT.SimpleTy) {
5601   default: return SDValue();
5602   case MVT::v8i16:
5603     ISDNo = X86ISD::BLENDPW;
5604     OpTy = MVT::v8i16;
5605     break;
5606   case MVT::v4i32:
5607   case MVT::v4f32:
5608     ISDNo = X86ISD::BLENDPS;
5609     OpTy = MVT::v4f32;
5610     break;
5611   case MVT::v2i64:
5612   case MVT::v2f64:
5613     ISDNo = X86ISD::BLENDPD;
5614     OpTy = MVT::v2f64;
5615     break;
5616   case MVT::v8i32:
5617   case MVT::v8f32:
5618     if (!Subtarget->hasAVX())
5619       return SDValue();
5620     ISDNo = X86ISD::BLENDPS;
5621     OpTy = MVT::v8f32;
5622     break;
5623   case MVT::v4i64:
5624   case MVT::v4f64:
5625     if (!Subtarget->hasAVX())
5626       return SDValue();
5627     ISDNo = X86ISD::BLENDPD;
5628     OpTy = MVT::v4f64;
5629     break;
5630   }
5631   assert(ISDNo && "Invalid Op Number");
5632
5633   unsigned MaskVals = 0;
5634
5635   for (unsigned i = 0; i != NumElems; ++i) {
5636     int EltIdx = SVOp->getMaskElt(i);
5637     if (EltIdx == (int)i || EltIdx < 0)
5638       MaskVals |= (1<<i);
5639     else if (EltIdx == (int)(i + NumElems))
5640       continue; // Bit is set to zero;
5641     else
5642       return SDValue();
5643   }
5644
5645   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5646   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5647   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5648                              DAG.getConstant(MaskVals, MVT::i32));
5649   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5650 }
5651
5652 // v8i16 shuffles - Prefer shuffles in the following order:
5653 // 1. [all]   pshuflw, pshufhw, optional move
5654 // 2. [ssse3] 1 x pshufb
5655 // 3. [ssse3] 2 x pshufb + 1 x por
5656 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5657 static SDValue
5658 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5659                          SelectionDAG &DAG) {
5660   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5661   SDValue V1 = SVOp->getOperand(0);
5662   SDValue V2 = SVOp->getOperand(1);
5663   DebugLoc dl = SVOp->getDebugLoc();
5664   SmallVector<int, 8> MaskVals;
5665
5666   // Determine if more than 1 of the words in each of the low and high quadwords
5667   // of the result come from the same quadword of one of the two inputs.  Undef
5668   // mask values count as coming from any quadword, for better codegen.
5669   unsigned LoQuad[] = { 0, 0, 0, 0 };
5670   unsigned HiQuad[] = { 0, 0, 0, 0 };
5671   std::bitset<4> InputQuads;
5672   for (unsigned i = 0; i < 8; ++i) {
5673     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5674     int EltIdx = SVOp->getMaskElt(i);
5675     MaskVals.push_back(EltIdx);
5676     if (EltIdx < 0) {
5677       ++Quad[0];
5678       ++Quad[1];
5679       ++Quad[2];
5680       ++Quad[3];
5681       continue;
5682     }
5683     ++Quad[EltIdx / 4];
5684     InputQuads.set(EltIdx / 4);
5685   }
5686
5687   int BestLoQuad = -1;
5688   unsigned MaxQuad = 1;
5689   for (unsigned i = 0; i < 4; ++i) {
5690     if (LoQuad[i] > MaxQuad) {
5691       BestLoQuad = i;
5692       MaxQuad = LoQuad[i];
5693     }
5694   }
5695
5696   int BestHiQuad = -1;
5697   MaxQuad = 1;
5698   for (unsigned i = 0; i < 4; ++i) {
5699     if (HiQuad[i] > MaxQuad) {
5700       BestHiQuad = i;
5701       MaxQuad = HiQuad[i];
5702     }
5703   }
5704
5705   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5706   // of the two input vectors, shuffle them into one input vector so only a
5707   // single pshufb instruction is necessary. If There are more than 2 input
5708   // quads, disable the next transformation since it does not help SSSE3.
5709   bool V1Used = InputQuads[0] || InputQuads[1];
5710   bool V2Used = InputQuads[2] || InputQuads[3];
5711   if (Subtarget->hasSSSE3()) {
5712     if (InputQuads.count() == 2 && V1Used && V2Used) {
5713       BestLoQuad = InputQuads[0] ? 0 : 1;
5714       BestHiQuad = InputQuads[2] ? 2 : 3;
5715     }
5716     if (InputQuads.count() > 2) {
5717       BestLoQuad = -1;
5718       BestHiQuad = -1;
5719     }
5720   }
5721
5722   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5723   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5724   // words from all 4 input quadwords.
5725   SDValue NewV;
5726   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5727     int MaskV[] = {
5728       BestLoQuad < 0 ? 0 : BestLoQuad,
5729       BestHiQuad < 0 ? 1 : BestHiQuad
5730     };
5731     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5732                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5733                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5734     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5735
5736     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5737     // source words for the shuffle, to aid later transformations.
5738     bool AllWordsInNewV = true;
5739     bool InOrder[2] = { true, true };
5740     for (unsigned i = 0; i != 8; ++i) {
5741       int idx = MaskVals[i];
5742       if (idx != (int)i)
5743         InOrder[i/4] = false;
5744       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5745         continue;
5746       AllWordsInNewV = false;
5747       break;
5748     }
5749
5750     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5751     if (AllWordsInNewV) {
5752       for (int i = 0; i != 8; ++i) {
5753         int idx = MaskVals[i];
5754         if (idx < 0)
5755           continue;
5756         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5757         if ((idx != i) && idx < 4)
5758           pshufhw = false;
5759         if ((idx != i) && idx > 3)
5760           pshuflw = false;
5761       }
5762       V1 = NewV;
5763       V2Used = false;
5764       BestLoQuad = 0;
5765       BestHiQuad = 1;
5766     }
5767
5768     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5769     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5770     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5771       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5772       unsigned TargetMask = 0;
5773       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5774                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5775       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5776       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5777                              getShufflePSHUFLWImmediate(SVOp);
5778       V1 = NewV.getOperand(0);
5779       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5780     }
5781   }
5782
5783   // If we have SSSE3, and all words of the result are from 1 input vector,
5784   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5785   // is present, fall back to case 4.
5786   if (Subtarget->hasSSSE3()) {
5787     SmallVector<SDValue,16> pshufbMask;
5788
5789     // If we have elements from both input vectors, set the high bit of the
5790     // shuffle mask element to zero out elements that come from V2 in the V1
5791     // mask, and elements that come from V1 in the V2 mask, so that the two
5792     // results can be OR'd together.
5793     bool TwoInputs = V1Used && V2Used;
5794     for (unsigned i = 0; i != 8; ++i) {
5795       int EltIdx = MaskVals[i] * 2;
5796       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5797       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5798       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5799       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5800     }
5801     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5802     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5803                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5804                                  MVT::v16i8, &pshufbMask[0], 16));
5805     if (!TwoInputs)
5806       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5807
5808     // Calculate the shuffle mask for the second input, shuffle it, and
5809     // OR it with the first shuffled input.
5810     pshufbMask.clear();
5811     for (unsigned i = 0; i != 8; ++i) {
5812       int EltIdx = MaskVals[i] * 2;
5813       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5814       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5815       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5816       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5817     }
5818     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5819     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5820                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5821                                  MVT::v16i8, &pshufbMask[0], 16));
5822     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5823     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5824   }
5825
5826   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5827   // and update MaskVals with new element order.
5828   std::bitset<8> InOrder;
5829   if (BestLoQuad >= 0) {
5830     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5831     for (int i = 0; i != 4; ++i) {
5832       int idx = MaskVals[i];
5833       if (idx < 0) {
5834         InOrder.set(i);
5835       } else if ((idx / 4) == BestLoQuad) {
5836         MaskV[i] = idx & 3;
5837         InOrder.set(i);
5838       }
5839     }
5840     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5841                                 &MaskV[0]);
5842
5843     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5844       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5845       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5846                                   NewV.getOperand(0),
5847                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5848     }
5849   }
5850
5851   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5852   // and update MaskVals with the new element order.
5853   if (BestHiQuad >= 0) {
5854     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5855     for (unsigned i = 4; i != 8; ++i) {
5856       int idx = MaskVals[i];
5857       if (idx < 0) {
5858         InOrder.set(i);
5859       } else if ((idx / 4) == BestHiQuad) {
5860         MaskV[i] = (idx & 3) + 4;
5861         InOrder.set(i);
5862       }
5863     }
5864     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5865                                 &MaskV[0]);
5866
5867     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5868       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5869       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5870                                   NewV.getOperand(0),
5871                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5872     }
5873   }
5874
5875   // In case BestHi & BestLo were both -1, which means each quadword has a word
5876   // from each of the four input quadwords, calculate the InOrder bitvector now
5877   // before falling through to the insert/extract cleanup.
5878   if (BestLoQuad == -1 && BestHiQuad == -1) {
5879     NewV = V1;
5880     for (int i = 0; i != 8; ++i)
5881       if (MaskVals[i] < 0 || MaskVals[i] == i)
5882         InOrder.set(i);
5883   }
5884
5885   // The other elements are put in the right place using pextrw and pinsrw.
5886   for (unsigned i = 0; i != 8; ++i) {
5887     if (InOrder[i])
5888       continue;
5889     int EltIdx = MaskVals[i];
5890     if (EltIdx < 0)
5891       continue;
5892     SDValue ExtOp = (EltIdx < 8) ?
5893       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5894                   DAG.getIntPtrConstant(EltIdx)) :
5895       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5896                   DAG.getIntPtrConstant(EltIdx - 8));
5897     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5898                        DAG.getIntPtrConstant(i));
5899   }
5900   return NewV;
5901 }
5902
5903 // v16i8 shuffles - Prefer shuffles in the following order:
5904 // 1. [ssse3] 1 x pshufb
5905 // 2. [ssse3] 2 x pshufb + 1 x por
5906 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5907 static
5908 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5909                                  SelectionDAG &DAG,
5910                                  const X86TargetLowering &TLI) {
5911   SDValue V1 = SVOp->getOperand(0);
5912   SDValue V2 = SVOp->getOperand(1);
5913   DebugLoc dl = SVOp->getDebugLoc();
5914   ArrayRef<int> MaskVals = SVOp->getMask();
5915
5916   // If we have SSSE3, case 1 is generated when all result bytes come from
5917   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5918   // present, fall back to case 3.
5919
5920   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5921   if (TLI.getSubtarget()->hasSSSE3()) {
5922     SmallVector<SDValue,16> pshufbMask;
5923
5924     // If all result elements are from one input vector, then only translate
5925     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5926     //
5927     // Otherwise, we have elements from both input vectors, and must zero out
5928     // elements that come from V2 in the first mask, and V1 in the second mask
5929     // so that we can OR them together.
5930     for (unsigned i = 0; i != 16; ++i) {
5931       int EltIdx = MaskVals[i];
5932       if (EltIdx < 0 || EltIdx >= 16)
5933         EltIdx = 0x80;
5934       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5935     }
5936     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5937                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5938                                  MVT::v16i8, &pshufbMask[0], 16));
5939
5940     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5941     // the 2nd operand if it's undefined or zero.
5942     if (V2.getOpcode() == ISD::UNDEF ||
5943         ISD::isBuildVectorAllZeros(V2.getNode()))
5944       return V1;
5945
5946     // Calculate the shuffle mask for the second input, shuffle it, and
5947     // OR it with the first shuffled input.
5948     pshufbMask.clear();
5949     for (unsigned i = 0; i != 16; ++i) {
5950       int EltIdx = MaskVals[i];
5951       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5952       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5953     }
5954     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5955                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5956                                  MVT::v16i8, &pshufbMask[0], 16));
5957     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5958   }
5959
5960   // No SSSE3 - Calculate in place words and then fix all out of place words
5961   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5962   // the 16 different words that comprise the two doublequadword input vectors.
5963   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5964   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5965   SDValue NewV = V1;
5966   for (int i = 0; i != 8; ++i) {
5967     int Elt0 = MaskVals[i*2];
5968     int Elt1 = MaskVals[i*2+1];
5969
5970     // This word of the result is all undef, skip it.
5971     if (Elt0 < 0 && Elt1 < 0)
5972       continue;
5973
5974     // This word of the result is already in the correct place, skip it.
5975     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5976       continue;
5977
5978     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5979     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5980     SDValue InsElt;
5981
5982     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5983     // using a single extract together, load it and store it.
5984     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5985       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5986                            DAG.getIntPtrConstant(Elt1 / 2));
5987       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5988                         DAG.getIntPtrConstant(i));
5989       continue;
5990     }
5991
5992     // If Elt1 is defined, extract it from the appropriate source.  If the
5993     // source byte is not also odd, shift the extracted word left 8 bits
5994     // otherwise clear the bottom 8 bits if we need to do an or.
5995     if (Elt1 >= 0) {
5996       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5997                            DAG.getIntPtrConstant(Elt1 / 2));
5998       if ((Elt1 & 1) == 0)
5999         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6000                              DAG.getConstant(8,
6001                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6002       else if (Elt0 >= 0)
6003         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6004                              DAG.getConstant(0xFF00, MVT::i16));
6005     }
6006     // If Elt0 is defined, extract it from the appropriate source.  If the
6007     // source byte is not also even, shift the extracted word right 8 bits. If
6008     // Elt1 was also defined, OR the extracted values together before
6009     // inserting them in the result.
6010     if (Elt0 >= 0) {
6011       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6012                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6013       if ((Elt0 & 1) != 0)
6014         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6015                               DAG.getConstant(8,
6016                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6017       else if (Elt1 >= 0)
6018         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6019                              DAG.getConstant(0x00FF, MVT::i16));
6020       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6021                          : InsElt0;
6022     }
6023     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6024                        DAG.getIntPtrConstant(i));
6025   }
6026   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6027 }
6028
6029 // v32i8 shuffles - Translate to VPSHUFB if possible.
6030 static
6031 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6032                                  const X86Subtarget *Subtarget,
6033                                  SelectionDAG &DAG) {
6034   EVT VT = SVOp->getValueType(0);
6035   SDValue V1 = SVOp->getOperand(0);
6036   SDValue V2 = SVOp->getOperand(1);
6037   DebugLoc dl = SVOp->getDebugLoc();
6038   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6039
6040   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6041   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6042   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6043
6044   // VPSHUFB may be generated if 
6045   // (1) one of input vector is undefined or zeroinitializer.
6046   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6047   // And (2) the mask indexes don't cross the 128-bit lane.
6048   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6049       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6050     return SDValue();
6051
6052   if (V1IsAllZero && !V2IsAllZero) {
6053     CommuteVectorShuffleMask(MaskVals, 32);
6054     V1 = V2;
6055   }
6056   SmallVector<SDValue, 32> pshufbMask;
6057   for (unsigned i = 0; i != 32; i++) {
6058     int EltIdx = MaskVals[i];
6059     if (EltIdx < 0 || EltIdx >= 32)
6060       EltIdx = 0x80;
6061     else {
6062       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6063         // Cross lane is not allowed.
6064         return SDValue();
6065       EltIdx &= 0xf;
6066     }
6067     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6068   }
6069   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6070                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6071                                   MVT::v32i8, &pshufbMask[0], 32));
6072 }
6073
6074 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6075 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6076 /// done when every pair / quad of shuffle mask elements point to elements in
6077 /// the right sequence. e.g.
6078 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6079 static
6080 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6081                                  SelectionDAG &DAG, DebugLoc dl) {
6082   MVT VT = SVOp->getValueType(0).getSimpleVT();
6083   unsigned NumElems = VT.getVectorNumElements();
6084   MVT NewVT;
6085   unsigned Scale;
6086   switch (VT.SimpleTy) {
6087   default: llvm_unreachable("Unexpected!");
6088   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6089   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6090   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6091   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6092   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6093   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6094   }
6095
6096   SmallVector<int, 8> MaskVec;
6097   for (unsigned i = 0; i != NumElems; i += Scale) {
6098     int StartIdx = -1;
6099     for (unsigned j = 0; j != Scale; ++j) {
6100       int EltIdx = SVOp->getMaskElt(i+j);
6101       if (EltIdx < 0)
6102         continue;
6103       if (StartIdx < 0)
6104         StartIdx = (EltIdx / Scale);
6105       if (EltIdx != (int)(StartIdx*Scale + j))
6106         return SDValue();
6107     }
6108     MaskVec.push_back(StartIdx);
6109   }
6110
6111   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6112   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6113   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6114 }
6115
6116 /// getVZextMovL - Return a zero-extending vector move low node.
6117 ///
6118 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6119                             SDValue SrcOp, SelectionDAG &DAG,
6120                             const X86Subtarget *Subtarget, DebugLoc dl) {
6121   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6122     LoadSDNode *LD = NULL;
6123     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6124       LD = dyn_cast<LoadSDNode>(SrcOp);
6125     if (!LD) {
6126       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6127       // instead.
6128       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6129       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6130           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6131           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6132           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6133         // PR2108
6134         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6135         return DAG.getNode(ISD::BITCAST, dl, VT,
6136                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6137                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6138                                                    OpVT,
6139                                                    SrcOp.getOperand(0)
6140                                                           .getOperand(0))));
6141       }
6142     }
6143   }
6144
6145   return DAG.getNode(ISD::BITCAST, dl, VT,
6146                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6147                                  DAG.getNode(ISD::BITCAST, dl,
6148                                              OpVT, SrcOp)));
6149 }
6150
6151 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6152 /// which could not be matched by any known target speficic shuffle
6153 static SDValue
6154 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6155
6156   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6157   if (NewOp.getNode())
6158     return NewOp;
6159
6160   EVT VT = SVOp->getValueType(0);
6161
6162   unsigned NumElems = VT.getVectorNumElements();
6163   unsigned NumLaneElems = NumElems / 2;
6164
6165   DebugLoc dl = SVOp->getDebugLoc();
6166   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6167   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6168   SDValue Output[2];
6169
6170   SmallVector<int, 16> Mask;
6171   for (unsigned l = 0; l < 2; ++l) {
6172     // Build a shuffle mask for the output, discovering on the fly which
6173     // input vectors to use as shuffle operands (recorded in InputUsed).
6174     // If building a suitable shuffle vector proves too hard, then bail
6175     // out with UseBuildVector set.
6176     bool UseBuildVector = false;
6177     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6178     unsigned LaneStart = l * NumLaneElems;
6179     for (unsigned i = 0; i != NumLaneElems; ++i) {
6180       // The mask element.  This indexes into the input.
6181       int Idx = SVOp->getMaskElt(i+LaneStart);
6182       if (Idx < 0) {
6183         // the mask element does not index into any input vector.
6184         Mask.push_back(-1);
6185         continue;
6186       }
6187
6188       // The input vector this mask element indexes into.
6189       int Input = Idx / NumLaneElems;
6190
6191       // Turn the index into an offset from the start of the input vector.
6192       Idx -= Input * NumLaneElems;
6193
6194       // Find or create a shuffle vector operand to hold this input.
6195       unsigned OpNo;
6196       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6197         if (InputUsed[OpNo] == Input)
6198           // This input vector is already an operand.
6199           break;
6200         if (InputUsed[OpNo] < 0) {
6201           // Create a new operand for this input vector.
6202           InputUsed[OpNo] = Input;
6203           break;
6204         }
6205       }
6206
6207       if (OpNo >= array_lengthof(InputUsed)) {
6208         // More than two input vectors used!  Give up on trying to create a
6209         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6210         UseBuildVector = true;
6211         break;
6212       }
6213
6214       // Add the mask index for the new shuffle vector.
6215       Mask.push_back(Idx + OpNo * NumLaneElems);
6216     }
6217
6218     if (UseBuildVector) {
6219       SmallVector<SDValue, 16> SVOps;
6220       for (unsigned i = 0; i != NumLaneElems; ++i) {
6221         // The mask element.  This indexes into the input.
6222         int Idx = SVOp->getMaskElt(i+LaneStart);
6223         if (Idx < 0) {
6224           SVOps.push_back(DAG.getUNDEF(EltVT));
6225           continue;
6226         }
6227
6228         // The input vector this mask element indexes into.
6229         int Input = Idx / NumElems;
6230
6231         // Turn the index into an offset from the start of the input vector.
6232         Idx -= Input * NumElems;
6233
6234         // Extract the vector element by hand.
6235         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6236                                     SVOp->getOperand(Input),
6237                                     DAG.getIntPtrConstant(Idx)));
6238       }
6239
6240       // Construct the output using a BUILD_VECTOR.
6241       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6242                               SVOps.size());
6243     } else if (InputUsed[0] < 0) {
6244       // No input vectors were used! The result is undefined.
6245       Output[l] = DAG.getUNDEF(NVT);
6246     } else {
6247       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6248                                         (InputUsed[0] % 2) * NumLaneElems,
6249                                         DAG, dl);
6250       // If only one input was used, use an undefined vector for the other.
6251       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6252         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6253                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6254       // At least one input vector was used. Create a new shuffle vector.
6255       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6256     }
6257
6258     Mask.clear();
6259   }
6260
6261   // Concatenate the result back
6262   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6263 }
6264
6265 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6266 /// 4 elements, and match them with several different shuffle types.
6267 static SDValue
6268 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6269   SDValue V1 = SVOp->getOperand(0);
6270   SDValue V2 = SVOp->getOperand(1);
6271   DebugLoc dl = SVOp->getDebugLoc();
6272   EVT VT = SVOp->getValueType(0);
6273
6274   assert(VT.is128BitVector() && "Unsupported vector size");
6275
6276   std::pair<int, int> Locs[4];
6277   int Mask1[] = { -1, -1, -1, -1 };
6278   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6279
6280   unsigned NumHi = 0;
6281   unsigned NumLo = 0;
6282   for (unsigned i = 0; i != 4; ++i) {
6283     int Idx = PermMask[i];
6284     if (Idx < 0) {
6285       Locs[i] = std::make_pair(-1, -1);
6286     } else {
6287       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6288       if (Idx < 4) {
6289         Locs[i] = std::make_pair(0, NumLo);
6290         Mask1[NumLo] = Idx;
6291         NumLo++;
6292       } else {
6293         Locs[i] = std::make_pair(1, NumHi);
6294         if (2+NumHi < 4)
6295           Mask1[2+NumHi] = Idx;
6296         NumHi++;
6297       }
6298     }
6299   }
6300
6301   if (NumLo <= 2 && NumHi <= 2) {
6302     // If no more than two elements come from either vector. This can be
6303     // implemented with two shuffles. First shuffle gather the elements.
6304     // The second shuffle, which takes the first shuffle as both of its
6305     // vector operands, put the elements into the right order.
6306     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6307
6308     int Mask2[] = { -1, -1, -1, -1 };
6309
6310     for (unsigned i = 0; i != 4; ++i)
6311       if (Locs[i].first != -1) {
6312         unsigned Idx = (i < 2) ? 0 : 4;
6313         Idx += Locs[i].first * 2 + Locs[i].second;
6314         Mask2[i] = Idx;
6315       }
6316
6317     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6318   }
6319
6320   if (NumLo == 3 || NumHi == 3) {
6321     // Otherwise, we must have three elements from one vector, call it X, and
6322     // one element from the other, call it Y.  First, use a shufps to build an
6323     // intermediate vector with the one element from Y and the element from X
6324     // that will be in the same half in the final destination (the indexes don't
6325     // matter). Then, use a shufps to build the final vector, taking the half
6326     // containing the element from Y from the intermediate, and the other half
6327     // from X.
6328     if (NumHi == 3) {
6329       // Normalize it so the 3 elements come from V1.
6330       CommuteVectorShuffleMask(PermMask, 4);
6331       std::swap(V1, V2);
6332     }
6333
6334     // Find the element from V2.
6335     unsigned HiIndex;
6336     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6337       int Val = PermMask[HiIndex];
6338       if (Val < 0)
6339         continue;
6340       if (Val >= 4)
6341         break;
6342     }
6343
6344     Mask1[0] = PermMask[HiIndex];
6345     Mask1[1] = -1;
6346     Mask1[2] = PermMask[HiIndex^1];
6347     Mask1[3] = -1;
6348     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6349
6350     if (HiIndex >= 2) {
6351       Mask1[0] = PermMask[0];
6352       Mask1[1] = PermMask[1];
6353       Mask1[2] = HiIndex & 1 ? 6 : 4;
6354       Mask1[3] = HiIndex & 1 ? 4 : 6;
6355       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6356     }
6357
6358     Mask1[0] = HiIndex & 1 ? 2 : 0;
6359     Mask1[1] = HiIndex & 1 ? 0 : 2;
6360     Mask1[2] = PermMask[2];
6361     Mask1[3] = PermMask[3];
6362     if (Mask1[2] >= 0)
6363       Mask1[2] += 4;
6364     if (Mask1[3] >= 0)
6365       Mask1[3] += 4;
6366     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6367   }
6368
6369   // Break it into (shuffle shuffle_hi, shuffle_lo).
6370   int LoMask[] = { -1, -1, -1, -1 };
6371   int HiMask[] = { -1, -1, -1, -1 };
6372
6373   int *MaskPtr = LoMask;
6374   unsigned MaskIdx = 0;
6375   unsigned LoIdx = 0;
6376   unsigned HiIdx = 2;
6377   for (unsigned i = 0; i != 4; ++i) {
6378     if (i == 2) {
6379       MaskPtr = HiMask;
6380       MaskIdx = 1;
6381       LoIdx = 0;
6382       HiIdx = 2;
6383     }
6384     int Idx = PermMask[i];
6385     if (Idx < 0) {
6386       Locs[i] = std::make_pair(-1, -1);
6387     } else if (Idx < 4) {
6388       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6389       MaskPtr[LoIdx] = Idx;
6390       LoIdx++;
6391     } else {
6392       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6393       MaskPtr[HiIdx] = Idx;
6394       HiIdx++;
6395     }
6396   }
6397
6398   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6399   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6400   int MaskOps[] = { -1, -1, -1, -1 };
6401   for (unsigned i = 0; i != 4; ++i)
6402     if (Locs[i].first != -1)
6403       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6404   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6405 }
6406
6407 static bool MayFoldVectorLoad(SDValue V) {
6408   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6409     V = V.getOperand(0);
6410   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6411     V = V.getOperand(0);
6412   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6413       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6414     // BUILD_VECTOR (load), undef
6415     V = V.getOperand(0);
6416   if (MayFoldLoad(V))
6417     return true;
6418   return false;
6419 }
6420
6421 // FIXME: the version above should always be used. Since there's
6422 // a bug where several vector shuffles can't be folded because the
6423 // DAG is not updated during lowering and a node claims to have two
6424 // uses while it only has one, use this version, and let isel match
6425 // another instruction if the load really happens to have more than
6426 // one use. Remove this version after this bug get fixed.
6427 // rdar://8434668, PR8156
6428 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6429   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6430     V = V.getOperand(0);
6431   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6432     V = V.getOperand(0);
6433   if (ISD::isNormalLoad(V.getNode()))
6434     return true;
6435   return false;
6436 }
6437
6438 static
6439 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6440   EVT VT = Op.getValueType();
6441
6442   // Canonizalize to v2f64.
6443   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6444   return DAG.getNode(ISD::BITCAST, dl, VT,
6445                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6446                                           V1, DAG));
6447 }
6448
6449 static
6450 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6451                         bool HasSSE2) {
6452   SDValue V1 = Op.getOperand(0);
6453   SDValue V2 = Op.getOperand(1);
6454   EVT VT = Op.getValueType();
6455
6456   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6457
6458   if (HasSSE2 && VT == MVT::v2f64)
6459     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6460
6461   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6462   return DAG.getNode(ISD::BITCAST, dl, VT,
6463                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6464                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6465                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6466 }
6467
6468 static
6469 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6470   SDValue V1 = Op.getOperand(0);
6471   SDValue V2 = Op.getOperand(1);
6472   EVT VT = Op.getValueType();
6473
6474   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6475          "unsupported shuffle type");
6476
6477   if (V2.getOpcode() == ISD::UNDEF)
6478     V2 = V1;
6479
6480   // v4i32 or v4f32
6481   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6482 }
6483
6484 static
6485 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6486   SDValue V1 = Op.getOperand(0);
6487   SDValue V2 = Op.getOperand(1);
6488   EVT VT = Op.getValueType();
6489   unsigned NumElems = VT.getVectorNumElements();
6490
6491   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6492   // operand of these instructions is only memory, so check if there's a
6493   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6494   // same masks.
6495   bool CanFoldLoad = false;
6496
6497   // Trivial case, when V2 comes from a load.
6498   if (MayFoldVectorLoad(V2))
6499     CanFoldLoad = true;
6500
6501   // When V1 is a load, it can be folded later into a store in isel, example:
6502   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6503   //    turns into:
6504   //  (MOVLPSmr addr:$src1, VR128:$src2)
6505   // So, recognize this potential and also use MOVLPS or MOVLPD
6506   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6507     CanFoldLoad = true;
6508
6509   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6510   if (CanFoldLoad) {
6511     if (HasSSE2 && NumElems == 2)
6512       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6513
6514     if (NumElems == 4)
6515       // If we don't care about the second element, proceed to use movss.
6516       if (SVOp->getMaskElt(1) != -1)
6517         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6518   }
6519
6520   // movl and movlp will both match v2i64, but v2i64 is never matched by
6521   // movl earlier because we make it strict to avoid messing with the movlp load
6522   // folding logic (see the code above getMOVLP call). Match it here then,
6523   // this is horrible, but will stay like this until we move all shuffle
6524   // matching to x86 specific nodes. Note that for the 1st condition all
6525   // types are matched with movsd.
6526   if (HasSSE2) {
6527     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6528     // as to remove this logic from here, as much as possible
6529     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6530       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6531     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6532   }
6533
6534   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6535
6536   // Invert the operand order and use SHUFPS to match it.
6537   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6538                               getShuffleSHUFImmediate(SVOp), DAG);
6539 }
6540
6541 SDValue
6542 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6543   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6544   EVT VT = Op.getValueType();
6545   DebugLoc dl = Op.getDebugLoc();
6546   SDValue V1 = Op.getOperand(0);
6547   SDValue V2 = Op.getOperand(1);
6548
6549   if (isZeroShuffle(SVOp))
6550     return getZeroVector(VT, Subtarget, DAG, dl);
6551
6552   // Handle splat operations
6553   if (SVOp->isSplat()) {
6554     unsigned NumElem = VT.getVectorNumElements();
6555     int Size = VT.getSizeInBits();
6556
6557     // Use vbroadcast whenever the splat comes from a foldable load
6558     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6559     if (Broadcast.getNode())
6560       return Broadcast;
6561
6562     // Handle splats by matching through known shuffle masks
6563     if ((Size == 128 && NumElem <= 4) ||
6564         (Size == 256 && NumElem < 8))
6565       return SDValue();
6566
6567     // All remaning splats are promoted to target supported vector shuffles.
6568     return PromoteSplat(SVOp, DAG);
6569   }
6570
6571   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6572   // do it!
6573   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6574       VT == MVT::v16i16 || VT == MVT::v32i8) {
6575     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6576     if (NewOp.getNode())
6577       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6578   } else if ((VT == MVT::v4i32 ||
6579              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6580     // FIXME: Figure out a cleaner way to do this.
6581     // Try to make use of movq to zero out the top part.
6582     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6583       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6584       if (NewOp.getNode()) {
6585         EVT NewVT = NewOp.getValueType();
6586         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6587                                NewVT, true, false))
6588           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6589                               DAG, Subtarget, dl);
6590       }
6591     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6592       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6593       if (NewOp.getNode()) {
6594         EVT NewVT = NewOp.getValueType();
6595         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6596           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6597                               DAG, Subtarget, dl);
6598       }
6599     }
6600   }
6601   return SDValue();
6602 }
6603
6604 SDValue
6605 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6606   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6607   SDValue V1 = Op.getOperand(0);
6608   SDValue V2 = Op.getOperand(1);
6609   EVT VT = Op.getValueType();
6610   DebugLoc dl = Op.getDebugLoc();
6611   unsigned NumElems = VT.getVectorNumElements();
6612   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6613   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6614   bool V1IsSplat = false;
6615   bool V2IsSplat = false;
6616   bool HasSSE2 = Subtarget->hasSSE2();
6617   bool HasAVX    = Subtarget->hasAVX();
6618   bool HasAVX2   = Subtarget->hasAVX2();
6619   MachineFunction &MF = DAG.getMachineFunction();
6620   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6621
6622   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6623
6624   if (V1IsUndef && V2IsUndef)
6625     return DAG.getUNDEF(VT);
6626
6627   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6628
6629   // Vector shuffle lowering takes 3 steps:
6630   //
6631   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6632   //    narrowing and commutation of operands should be handled.
6633   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6634   //    shuffle nodes.
6635   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6636   //    so the shuffle can be broken into other shuffles and the legalizer can
6637   //    try the lowering again.
6638   //
6639   // The general idea is that no vector_shuffle operation should be left to
6640   // be matched during isel, all of them must be converted to a target specific
6641   // node here.
6642
6643   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6644   // narrowing and commutation of operands should be handled. The actual code
6645   // doesn't include all of those, work in progress...
6646   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6647   if (NewOp.getNode())
6648     return NewOp;
6649
6650   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6651
6652   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6653   // unpckh_undef). Only use pshufd if speed is more important than size.
6654   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6655     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6656   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6657     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6658
6659   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6660       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6661     return getMOVDDup(Op, dl, V1, DAG);
6662
6663   if (isMOVHLPS_v_undef_Mask(M, VT))
6664     return getMOVHighToLow(Op, dl, DAG);
6665
6666   // Use to match splats
6667   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6668       (VT == MVT::v2f64 || VT == MVT::v2i64))
6669     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6670
6671   if (isPSHUFDMask(M, VT)) {
6672     // The actual implementation will match the mask in the if above and then
6673     // during isel it can match several different instructions, not only pshufd
6674     // as its name says, sad but true, emulate the behavior for now...
6675     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6676       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6677
6678     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6679
6680     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6681       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6682
6683     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6684       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6685
6686     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6687                                 TargetMask, DAG);
6688   }
6689
6690   // Check if this can be converted into a logical shift.
6691   bool isLeft = false;
6692   unsigned ShAmt = 0;
6693   SDValue ShVal;
6694   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6695   if (isShift && ShVal.hasOneUse()) {
6696     // If the shifted value has multiple uses, it may be cheaper to use
6697     // v_set0 + movlhps or movhlps, etc.
6698     EVT EltVT = VT.getVectorElementType();
6699     ShAmt *= EltVT.getSizeInBits();
6700     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6701   }
6702
6703   if (isMOVLMask(M, VT)) {
6704     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6705       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6706     if (!isMOVLPMask(M, VT)) {
6707       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6708         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6709
6710       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6711         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6712     }
6713   }
6714
6715   // FIXME: fold these into legal mask.
6716   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6717     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6718
6719   if (isMOVHLPSMask(M, VT))
6720     return getMOVHighToLow(Op, dl, DAG);
6721
6722   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6723     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6724
6725   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6726     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6727
6728   if (isMOVLPMask(M, VT))
6729     return getMOVLP(Op, dl, DAG, HasSSE2);
6730
6731   if (ShouldXformToMOVHLPS(M, VT) ||
6732       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6733     return CommuteVectorShuffle(SVOp, DAG);
6734
6735   if (isShift) {
6736     // No better options. Use a vshldq / vsrldq.
6737     EVT EltVT = VT.getVectorElementType();
6738     ShAmt *= EltVT.getSizeInBits();
6739     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6740   }
6741
6742   bool Commuted = false;
6743   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6744   // 1,1,1,1 -> v8i16 though.
6745   V1IsSplat = isSplatVector(V1.getNode());
6746   V2IsSplat = isSplatVector(V2.getNode());
6747
6748   // Canonicalize the splat or undef, if present, to be on the RHS.
6749   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6750     CommuteVectorShuffleMask(M, NumElems);
6751     std::swap(V1, V2);
6752     std::swap(V1IsSplat, V2IsSplat);
6753     Commuted = true;
6754   }
6755
6756   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6757     // Shuffling low element of v1 into undef, just return v1.
6758     if (V2IsUndef)
6759       return V1;
6760     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6761     // the instruction selector will not match, so get a canonical MOVL with
6762     // swapped operands to undo the commute.
6763     return getMOVL(DAG, dl, VT, V2, V1);
6764   }
6765
6766   if (isUNPCKLMask(M, VT, HasAVX2))
6767     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6768
6769   if (isUNPCKHMask(M, VT, HasAVX2))
6770     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6771
6772   if (V2IsSplat) {
6773     // Normalize mask so all entries that point to V2 points to its first
6774     // element then try to match unpck{h|l} again. If match, return a
6775     // new vector_shuffle with the corrected mask.p
6776     SmallVector<int, 8> NewMask(M.begin(), M.end());
6777     NormalizeMask(NewMask, NumElems);
6778     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6779       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6780     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6781       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6782   }
6783
6784   if (Commuted) {
6785     // Commute is back and try unpck* again.
6786     // FIXME: this seems wrong.
6787     CommuteVectorShuffleMask(M, NumElems);
6788     std::swap(V1, V2);
6789     std::swap(V1IsSplat, V2IsSplat);
6790     Commuted = false;
6791
6792     if (isUNPCKLMask(M, VT, HasAVX2))
6793       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6794
6795     if (isUNPCKHMask(M, VT, HasAVX2))
6796       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6797   }
6798
6799   // Normalize the node to match x86 shuffle ops if needed
6800   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6801     return CommuteVectorShuffle(SVOp, DAG);
6802
6803   // The checks below are all present in isShuffleMaskLegal, but they are
6804   // inlined here right now to enable us to directly emit target specific
6805   // nodes, and remove one by one until they don't return Op anymore.
6806
6807   if (isPALIGNRMask(M, VT, Subtarget))
6808     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6809                                 getShufflePALIGNRImmediate(SVOp),
6810                                 DAG);
6811
6812   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6813       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6814     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6815       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6816   }
6817
6818   if (isPSHUFHWMask(M, VT, HasAVX2))
6819     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6820                                 getShufflePSHUFHWImmediate(SVOp),
6821                                 DAG);
6822
6823   if (isPSHUFLWMask(M, VT, HasAVX2))
6824     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6825                                 getShufflePSHUFLWImmediate(SVOp),
6826                                 DAG);
6827
6828   if (isSHUFPMask(M, VT, HasAVX))
6829     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6830                                 getShuffleSHUFImmediate(SVOp), DAG);
6831
6832   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6833     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6834   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6835     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6836
6837   //===--------------------------------------------------------------------===//
6838   // Generate target specific nodes for 128 or 256-bit shuffles only
6839   // supported in the AVX instruction set.
6840   //
6841
6842   // Handle VMOVDDUPY permutations
6843   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6844     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6845
6846   // Handle VPERMILPS/D* permutations
6847   if (isVPERMILPMask(M, VT, HasAVX)) {
6848     if (HasAVX2 && VT == MVT::v8i32)
6849       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6850                                   getShuffleSHUFImmediate(SVOp), DAG);
6851     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6852                                 getShuffleSHUFImmediate(SVOp), DAG);
6853   }
6854
6855   // Handle VPERM2F128/VPERM2I128 permutations
6856   if (isVPERM2X128Mask(M, VT, HasAVX))
6857     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6858                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6859
6860   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6861   if (BlendOp.getNode())
6862     return BlendOp;
6863
6864   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6865     SmallVector<SDValue, 8> permclMask;
6866     for (unsigned i = 0; i != 8; ++i) {
6867       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6868     }
6869     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6870                                &permclMask[0], 8);
6871     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6872     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6873                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6874   }
6875
6876   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6877     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6878                                 getShuffleCLImmediate(SVOp), DAG);
6879
6880
6881   //===--------------------------------------------------------------------===//
6882   // Since no target specific shuffle was selected for this generic one,
6883   // lower it into other known shuffles. FIXME: this isn't true yet, but
6884   // this is the plan.
6885   //
6886
6887   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6888   if (VT == MVT::v8i16) {
6889     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6890     if (NewOp.getNode())
6891       return NewOp;
6892   }
6893
6894   if (VT == MVT::v16i8) {
6895     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6896     if (NewOp.getNode())
6897       return NewOp;
6898   }
6899
6900   if (VT == MVT::v32i8) {
6901     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6902     if (NewOp.getNode())
6903       return NewOp;
6904   }
6905
6906   // Handle all 128-bit wide vectors with 4 elements, and match them with
6907   // several different shuffle types.
6908   if (NumElems == 4 && VT.is128BitVector())
6909     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6910
6911   // Handle general 256-bit shuffles
6912   if (VT.is256BitVector())
6913     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6914
6915   return SDValue();
6916 }
6917
6918 SDValue
6919 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6920                                                 SelectionDAG &DAG) const {
6921   EVT VT = Op.getValueType();
6922   DebugLoc dl = Op.getDebugLoc();
6923
6924   if (!Op.getOperand(0).getValueType().is128BitVector())
6925     return SDValue();
6926
6927   if (VT.getSizeInBits() == 8) {
6928     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6929                                   Op.getOperand(0), Op.getOperand(1));
6930     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6931                                   DAG.getValueType(VT));
6932     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6933   }
6934
6935   if (VT.getSizeInBits() == 16) {
6936     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6937     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6938     if (Idx == 0)
6939       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6940                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6941                                      DAG.getNode(ISD::BITCAST, dl,
6942                                                  MVT::v4i32,
6943                                                  Op.getOperand(0)),
6944                                      Op.getOperand(1)));
6945     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6946                                   Op.getOperand(0), Op.getOperand(1));
6947     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6948                                   DAG.getValueType(VT));
6949     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6950   }
6951
6952   if (VT == MVT::f32) {
6953     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6954     // the result back to FR32 register. It's only worth matching if the
6955     // result has a single use which is a store or a bitcast to i32.  And in
6956     // the case of a store, it's not worth it if the index is a constant 0,
6957     // because a MOVSSmr can be used instead, which is smaller and faster.
6958     if (!Op.hasOneUse())
6959       return SDValue();
6960     SDNode *User = *Op.getNode()->use_begin();
6961     if ((User->getOpcode() != ISD::STORE ||
6962          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6963           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6964         (User->getOpcode() != ISD::BITCAST ||
6965          User->getValueType(0) != MVT::i32))
6966       return SDValue();
6967     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6968                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6969                                               Op.getOperand(0)),
6970                                               Op.getOperand(1));
6971     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6972   }
6973
6974   if (VT == MVT::i32 || VT == MVT::i64) {
6975     // ExtractPS/pextrq works with constant index.
6976     if (isa<ConstantSDNode>(Op.getOperand(1)))
6977       return Op;
6978   }
6979   return SDValue();
6980 }
6981
6982
6983 SDValue
6984 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6985                                            SelectionDAG &DAG) const {
6986   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6987     return SDValue();
6988
6989   SDValue Vec = Op.getOperand(0);
6990   EVT VecVT = Vec.getValueType();
6991
6992   // If this is a 256-bit vector result, first extract the 128-bit vector and
6993   // then extract the element from the 128-bit vector.
6994   if (VecVT.is256BitVector()) {
6995     DebugLoc dl = Op.getNode()->getDebugLoc();
6996     unsigned NumElems = VecVT.getVectorNumElements();
6997     SDValue Idx = Op.getOperand(1);
6998     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6999
7000     // Get the 128-bit vector.
7001     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7002
7003     if (IdxVal >= NumElems/2)
7004       IdxVal -= NumElems/2;
7005     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7006                        DAG.getConstant(IdxVal, MVT::i32));
7007   }
7008
7009   assert(VecVT.is128BitVector() && "Unexpected vector length");
7010
7011   if (Subtarget->hasSSE41()) {
7012     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7013     if (Res.getNode())
7014       return Res;
7015   }
7016
7017   EVT VT = Op.getValueType();
7018   DebugLoc dl = Op.getDebugLoc();
7019   // TODO: handle v16i8.
7020   if (VT.getSizeInBits() == 16) {
7021     SDValue Vec = Op.getOperand(0);
7022     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7023     if (Idx == 0)
7024       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7025                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7026                                      DAG.getNode(ISD::BITCAST, dl,
7027                                                  MVT::v4i32, Vec),
7028                                      Op.getOperand(1)));
7029     // Transform it so it match pextrw which produces a 32-bit result.
7030     EVT EltVT = MVT::i32;
7031     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7032                                   Op.getOperand(0), Op.getOperand(1));
7033     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7034                                   DAG.getValueType(VT));
7035     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7036   }
7037
7038   if (VT.getSizeInBits() == 32) {
7039     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7040     if (Idx == 0)
7041       return Op;
7042
7043     // SHUFPS the element to the lowest double word, then movss.
7044     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7045     EVT VVT = Op.getOperand(0).getValueType();
7046     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7047                                        DAG.getUNDEF(VVT), Mask);
7048     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7049                        DAG.getIntPtrConstant(0));
7050   }
7051
7052   if (VT.getSizeInBits() == 64) {
7053     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7054     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7055     //        to match extract_elt for f64.
7056     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7057     if (Idx == 0)
7058       return Op;
7059
7060     // UNPCKHPD the element to the lowest double word, then movsd.
7061     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7062     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7063     int Mask[2] = { 1, -1 };
7064     EVT VVT = Op.getOperand(0).getValueType();
7065     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7066                                        DAG.getUNDEF(VVT), Mask);
7067     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7068                        DAG.getIntPtrConstant(0));
7069   }
7070
7071   return SDValue();
7072 }
7073
7074 SDValue
7075 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7076                                                SelectionDAG &DAG) const {
7077   EVT VT = Op.getValueType();
7078   EVT EltVT = VT.getVectorElementType();
7079   DebugLoc dl = Op.getDebugLoc();
7080
7081   SDValue N0 = Op.getOperand(0);
7082   SDValue N1 = Op.getOperand(1);
7083   SDValue N2 = Op.getOperand(2);
7084
7085   if (!VT.is128BitVector())
7086     return SDValue();
7087
7088   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7089       isa<ConstantSDNode>(N2)) {
7090     unsigned Opc;
7091     if (VT == MVT::v8i16)
7092       Opc = X86ISD::PINSRW;
7093     else if (VT == MVT::v16i8)
7094       Opc = X86ISD::PINSRB;
7095     else
7096       Opc = X86ISD::PINSRB;
7097
7098     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7099     // argument.
7100     if (N1.getValueType() != MVT::i32)
7101       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7102     if (N2.getValueType() != MVT::i32)
7103       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7104     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7105   }
7106
7107   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7108     // Bits [7:6] of the constant are the source select.  This will always be
7109     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7110     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7111     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7112     // Bits [5:4] of the constant are the destination select.  This is the
7113     //  value of the incoming immediate.
7114     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7115     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7116     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7117     // Create this as a scalar to vector..
7118     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7119     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7120   }
7121
7122   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7123     // PINSR* works with constant index.
7124     return Op;
7125   }
7126   return SDValue();
7127 }
7128
7129 SDValue
7130 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7131   EVT VT = Op.getValueType();
7132   EVT EltVT = VT.getVectorElementType();
7133
7134   DebugLoc dl = Op.getDebugLoc();
7135   SDValue N0 = Op.getOperand(0);
7136   SDValue N1 = Op.getOperand(1);
7137   SDValue N2 = Op.getOperand(2);
7138
7139   // If this is a 256-bit vector result, first extract the 128-bit vector,
7140   // insert the element into the extracted half and then place it back.
7141   if (VT.is256BitVector()) {
7142     if (!isa<ConstantSDNode>(N2))
7143       return SDValue();
7144
7145     // Get the desired 128-bit vector half.
7146     unsigned NumElems = VT.getVectorNumElements();
7147     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7148     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7149
7150     // Insert the element into the desired half.
7151     bool Upper = IdxVal >= NumElems/2;
7152     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7153                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7154
7155     // Insert the changed part back to the 256-bit vector
7156     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7157   }
7158
7159   if (Subtarget->hasSSE41())
7160     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7161
7162   if (EltVT == MVT::i8)
7163     return SDValue();
7164
7165   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7166     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7167     // as its second argument.
7168     if (N1.getValueType() != MVT::i32)
7169       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7170     if (N2.getValueType() != MVT::i32)
7171       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7172     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7173   }
7174   return SDValue();
7175 }
7176
7177 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7178   LLVMContext *Context = DAG.getContext();
7179   DebugLoc dl = Op.getDebugLoc();
7180   EVT OpVT = Op.getValueType();
7181
7182   // If this is a 256-bit vector result, first insert into a 128-bit
7183   // vector and then insert into the 256-bit vector.
7184   if (!OpVT.is128BitVector()) {
7185     // Insert into a 128-bit vector.
7186     EVT VT128 = EVT::getVectorVT(*Context,
7187                                  OpVT.getVectorElementType(),
7188                                  OpVT.getVectorNumElements() / 2);
7189
7190     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7191
7192     // Insert the 128-bit vector.
7193     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7194   }
7195
7196   if (OpVT == MVT::v1i64 &&
7197       Op.getOperand(0).getValueType() == MVT::i64)
7198     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7199
7200   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7201   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7202   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7203                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7204 }
7205
7206 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7207 // a simple subregister reference or explicit instructions to grab
7208 // upper bits of a vector.
7209 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7210                                       SelectionDAG &DAG) {
7211   if (Subtarget->hasAVX()) {
7212     DebugLoc dl = Op.getNode()->getDebugLoc();
7213     SDValue Vec = Op.getNode()->getOperand(0);
7214     SDValue Idx = Op.getNode()->getOperand(1);
7215
7216     if (Op.getNode()->getValueType(0).is128BitVector() &&
7217         Vec.getNode()->getValueType(0).is256BitVector() &&
7218         isa<ConstantSDNode>(Idx)) {
7219       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7220       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7221     }
7222   }
7223   return SDValue();
7224 }
7225
7226 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7227 // simple superregister reference or explicit instructions to insert
7228 // the upper bits of a vector.
7229 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7230                                      SelectionDAG &DAG) {
7231   if (Subtarget->hasAVX()) {
7232     DebugLoc dl = Op.getNode()->getDebugLoc();
7233     SDValue Vec = Op.getNode()->getOperand(0);
7234     SDValue SubVec = Op.getNode()->getOperand(1);
7235     SDValue Idx = Op.getNode()->getOperand(2);
7236
7237     if (Op.getNode()->getValueType(0).is256BitVector() &&
7238         SubVec.getNode()->getValueType(0).is128BitVector() &&
7239         isa<ConstantSDNode>(Idx)) {
7240       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7241       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7242     }
7243   }
7244   return SDValue();
7245 }
7246
7247 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7248 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7249 // one of the above mentioned nodes. It has to be wrapped because otherwise
7250 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7251 // be used to form addressing mode. These wrapped nodes will be selected
7252 // into MOV32ri.
7253 SDValue
7254 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7255   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7256
7257   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7258   // global base reg.
7259   unsigned char OpFlag = 0;
7260   unsigned WrapperKind = X86ISD::Wrapper;
7261   CodeModel::Model M = getTargetMachine().getCodeModel();
7262
7263   if (Subtarget->isPICStyleRIPRel() &&
7264       (M == CodeModel::Small || M == CodeModel::Kernel))
7265     WrapperKind = X86ISD::WrapperRIP;
7266   else if (Subtarget->isPICStyleGOT())
7267     OpFlag = X86II::MO_GOTOFF;
7268   else if (Subtarget->isPICStyleStubPIC())
7269     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7270
7271   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7272                                              CP->getAlignment(),
7273                                              CP->getOffset(), OpFlag);
7274   DebugLoc DL = CP->getDebugLoc();
7275   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7276   // With PIC, the address is actually $g + Offset.
7277   if (OpFlag) {
7278     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7279                          DAG.getNode(X86ISD::GlobalBaseReg,
7280                                      DebugLoc(), getPointerTy()),
7281                          Result);
7282   }
7283
7284   return Result;
7285 }
7286
7287 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7288   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7289
7290   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7291   // global base reg.
7292   unsigned char OpFlag = 0;
7293   unsigned WrapperKind = X86ISD::Wrapper;
7294   CodeModel::Model M = getTargetMachine().getCodeModel();
7295
7296   if (Subtarget->isPICStyleRIPRel() &&
7297       (M == CodeModel::Small || M == CodeModel::Kernel))
7298     WrapperKind = X86ISD::WrapperRIP;
7299   else if (Subtarget->isPICStyleGOT())
7300     OpFlag = X86II::MO_GOTOFF;
7301   else if (Subtarget->isPICStyleStubPIC())
7302     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7303
7304   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7305                                           OpFlag);
7306   DebugLoc DL = JT->getDebugLoc();
7307   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7308
7309   // With PIC, the address is actually $g + Offset.
7310   if (OpFlag)
7311     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7312                          DAG.getNode(X86ISD::GlobalBaseReg,
7313                                      DebugLoc(), getPointerTy()),
7314                          Result);
7315
7316   return Result;
7317 }
7318
7319 SDValue
7320 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7321   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7322
7323   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7324   // global base reg.
7325   unsigned char OpFlag = 0;
7326   unsigned WrapperKind = X86ISD::Wrapper;
7327   CodeModel::Model M = getTargetMachine().getCodeModel();
7328
7329   if (Subtarget->isPICStyleRIPRel() &&
7330       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7331     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7332       OpFlag = X86II::MO_GOTPCREL;
7333     WrapperKind = X86ISD::WrapperRIP;
7334   } else if (Subtarget->isPICStyleGOT()) {
7335     OpFlag = X86II::MO_GOT;
7336   } else if (Subtarget->isPICStyleStubPIC()) {
7337     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7338   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7339     OpFlag = X86II::MO_DARWIN_NONLAZY;
7340   }
7341
7342   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7343
7344   DebugLoc DL = Op.getDebugLoc();
7345   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7346
7347
7348   // With PIC, the address is actually $g + Offset.
7349   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7350       !Subtarget->is64Bit()) {
7351     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7352                          DAG.getNode(X86ISD::GlobalBaseReg,
7353                                      DebugLoc(), getPointerTy()),
7354                          Result);
7355   }
7356
7357   // For symbols that require a load from a stub to get the address, emit the
7358   // load.
7359   if (isGlobalStubReference(OpFlag))
7360     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7361                          MachinePointerInfo::getGOT(), false, false, false, 0);
7362
7363   return Result;
7364 }
7365
7366 SDValue
7367 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7368   // Create the TargetBlockAddressAddress node.
7369   unsigned char OpFlags =
7370     Subtarget->ClassifyBlockAddressReference();
7371   CodeModel::Model M = getTargetMachine().getCodeModel();
7372   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7373   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7374   DebugLoc dl = Op.getDebugLoc();
7375   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7376                                              OpFlags);
7377
7378   if (Subtarget->isPICStyleRIPRel() &&
7379       (M == CodeModel::Small || M == CodeModel::Kernel))
7380     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7381   else
7382     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7383
7384   // With PIC, the address is actually $g + Offset.
7385   if (isGlobalRelativeToPICBase(OpFlags)) {
7386     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7387                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7388                          Result);
7389   }
7390
7391   return Result;
7392 }
7393
7394 SDValue
7395 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7396                                       int64_t Offset,
7397                                       SelectionDAG &DAG) const {
7398   // Create the TargetGlobalAddress node, folding in the constant
7399   // offset if it is legal.
7400   unsigned char OpFlags =
7401     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7402   CodeModel::Model M = getTargetMachine().getCodeModel();
7403   SDValue Result;
7404   if (OpFlags == X86II::MO_NO_FLAG &&
7405       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7406     // A direct static reference to a global.
7407     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7408     Offset = 0;
7409   } else {
7410     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7411   }
7412
7413   if (Subtarget->isPICStyleRIPRel() &&
7414       (M == CodeModel::Small || M == CodeModel::Kernel))
7415     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7416   else
7417     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7418
7419   // With PIC, the address is actually $g + Offset.
7420   if (isGlobalRelativeToPICBase(OpFlags)) {
7421     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7422                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7423                          Result);
7424   }
7425
7426   // For globals that require a load from a stub to get the address, emit the
7427   // load.
7428   if (isGlobalStubReference(OpFlags))
7429     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7430                          MachinePointerInfo::getGOT(), false, false, false, 0);
7431
7432   // If there was a non-zero offset that we didn't fold, create an explicit
7433   // addition for it.
7434   if (Offset != 0)
7435     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7436                          DAG.getConstant(Offset, getPointerTy()));
7437
7438   return Result;
7439 }
7440
7441 SDValue
7442 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7443   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7444   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7445   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7446 }
7447
7448 static SDValue
7449 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7450            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7451            unsigned char OperandFlags, bool LocalDynamic = false) {
7452   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7453   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7454   DebugLoc dl = GA->getDebugLoc();
7455   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7456                                            GA->getValueType(0),
7457                                            GA->getOffset(),
7458                                            OperandFlags);
7459
7460   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7461                                            : X86ISD::TLSADDR;
7462
7463   if (InFlag) {
7464     SDValue Ops[] = { Chain,  TGA, *InFlag };
7465     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7466   } else {
7467     SDValue Ops[]  = { Chain, TGA };
7468     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7469   }
7470
7471   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7472   MFI->setAdjustsStack(true);
7473
7474   SDValue Flag = Chain.getValue(1);
7475   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7476 }
7477
7478 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7479 static SDValue
7480 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7481                                 const EVT PtrVT) {
7482   SDValue InFlag;
7483   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7484   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7485                                    DAG.getNode(X86ISD::GlobalBaseReg,
7486                                                DebugLoc(), PtrVT), InFlag);
7487   InFlag = Chain.getValue(1);
7488
7489   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7490 }
7491
7492 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7493 static SDValue
7494 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7495                                 const EVT PtrVT) {
7496   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7497                     X86::RAX, X86II::MO_TLSGD);
7498 }
7499
7500 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7501                                            SelectionDAG &DAG,
7502                                            const EVT PtrVT,
7503                                            bool is64Bit) {
7504   DebugLoc dl = GA->getDebugLoc();
7505
7506   // Get the start address of the TLS block for this module.
7507   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7508       .getInfo<X86MachineFunctionInfo>();
7509   MFI->incNumLocalDynamicTLSAccesses();
7510
7511   SDValue Base;
7512   if (is64Bit) {
7513     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7514                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7515   } else {
7516     SDValue InFlag;
7517     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7518         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7519     InFlag = Chain.getValue(1);
7520     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7521                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7522   }
7523
7524   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7525   // of Base.
7526
7527   // Build x@dtpoff.
7528   unsigned char OperandFlags = X86II::MO_DTPOFF;
7529   unsigned WrapperKind = X86ISD::Wrapper;
7530   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7531                                            GA->getValueType(0),
7532                                            GA->getOffset(), OperandFlags);
7533   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7534
7535   // Add x@dtpoff with the base.
7536   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7537 }
7538
7539 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7540 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7541                                    const EVT PtrVT, TLSModel::Model model,
7542                                    bool is64Bit, bool isPIC) {
7543   DebugLoc dl = GA->getDebugLoc();
7544
7545   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7546   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7547                                                          is64Bit ? 257 : 256));
7548
7549   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7550                                       DAG.getIntPtrConstant(0),
7551                                       MachinePointerInfo(Ptr),
7552                                       false, false, false, 0);
7553
7554   unsigned char OperandFlags = 0;
7555   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7556   // initialexec.
7557   unsigned WrapperKind = X86ISD::Wrapper;
7558   if (model == TLSModel::LocalExec) {
7559     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7560   } else if (model == TLSModel::InitialExec) {
7561     if (is64Bit) {
7562       OperandFlags = X86II::MO_GOTTPOFF;
7563       WrapperKind = X86ISD::WrapperRIP;
7564     } else {
7565       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7566     }
7567   } else {
7568     llvm_unreachable("Unexpected model");
7569   }
7570
7571   // emit "addl x@ntpoff,%eax" (local exec)
7572   // or "addl x@indntpoff,%eax" (initial exec)
7573   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7574   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7575                                            GA->getValueType(0),
7576                                            GA->getOffset(), OperandFlags);
7577   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7578
7579   if (model == TLSModel::InitialExec) {
7580     if (isPIC && !is64Bit) {
7581       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7582                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7583                            Offset);
7584     }
7585
7586     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7587                          MachinePointerInfo::getGOT(), false, false, false,
7588                          0);
7589   }
7590
7591   // The address of the thread local variable is the add of the thread
7592   // pointer with the offset of the variable.
7593   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7594 }
7595
7596 SDValue
7597 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7598
7599   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7600   const GlobalValue *GV = GA->getGlobal();
7601
7602   if (Subtarget->isTargetELF()) {
7603     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7604
7605     switch (model) {
7606       case TLSModel::GeneralDynamic:
7607         if (Subtarget->is64Bit())
7608           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7609         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7610       case TLSModel::LocalDynamic:
7611         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7612                                            Subtarget->is64Bit());
7613       case TLSModel::InitialExec:
7614       case TLSModel::LocalExec:
7615         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7616                                    Subtarget->is64Bit(),
7617                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7618     }
7619     llvm_unreachable("Unknown TLS model.");
7620   }
7621
7622   if (Subtarget->isTargetDarwin()) {
7623     // Darwin only has one model of TLS.  Lower to that.
7624     unsigned char OpFlag = 0;
7625     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7626                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7627
7628     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7629     // global base reg.
7630     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7631                   !Subtarget->is64Bit();
7632     if (PIC32)
7633       OpFlag = X86II::MO_TLVP_PIC_BASE;
7634     else
7635       OpFlag = X86II::MO_TLVP;
7636     DebugLoc DL = Op.getDebugLoc();
7637     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7638                                                 GA->getValueType(0),
7639                                                 GA->getOffset(), OpFlag);
7640     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7641
7642     // With PIC32, the address is actually $g + Offset.
7643     if (PIC32)
7644       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7645                            DAG.getNode(X86ISD::GlobalBaseReg,
7646                                        DebugLoc(), getPointerTy()),
7647                            Offset);
7648
7649     // Lowering the machine isd will make sure everything is in the right
7650     // location.
7651     SDValue Chain = DAG.getEntryNode();
7652     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7653     SDValue Args[] = { Chain, Offset };
7654     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7655
7656     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7657     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7658     MFI->setAdjustsStack(true);
7659
7660     // And our return value (tls address) is in the standard call return value
7661     // location.
7662     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7663     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7664                               Chain.getValue(1));
7665   }
7666
7667   if (Subtarget->isTargetWindows()) {
7668     // Just use the implicit TLS architecture
7669     // Need to generate someting similar to:
7670     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7671     //                                  ; from TEB
7672     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7673     //   mov     rcx, qword [rdx+rcx*8]
7674     //   mov     eax, .tls$:tlsvar
7675     //   [rax+rcx] contains the address
7676     // Windows 64bit: gs:0x58
7677     // Windows 32bit: fs:__tls_array
7678
7679     // If GV is an alias then use the aliasee for determining
7680     // thread-localness.
7681     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7682       GV = GA->resolveAliasedGlobal(false);
7683     DebugLoc dl = GA->getDebugLoc();
7684     SDValue Chain = DAG.getEntryNode();
7685
7686     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7687     // %gs:0x58 (64-bit).
7688     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7689                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7690                                                              256)
7691                                         : Type::getInt32PtrTy(*DAG.getContext(),
7692                                                               257));
7693
7694     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7695                                         Subtarget->is64Bit()
7696                                         ? DAG.getIntPtrConstant(0x58)
7697                                         : DAG.getExternalSymbol("_tls_array",
7698                                                                 getPointerTy()),
7699                                         MachinePointerInfo(Ptr),
7700                                         false, false, false, 0);
7701
7702     // Load the _tls_index variable
7703     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7704     if (Subtarget->is64Bit())
7705       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7706                            IDX, MachinePointerInfo(), MVT::i32,
7707                            false, false, 0);
7708     else
7709       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7710                         false, false, false, 0);
7711
7712     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7713                                     getPointerTy());
7714     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7715
7716     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7717     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7718                       false, false, false, 0);
7719
7720     // Get the offset of start of .tls section
7721     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7722                                              GA->getValueType(0),
7723                                              GA->getOffset(), X86II::MO_SECREL);
7724     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7725
7726     // The address of the thread local variable is the add of the thread
7727     // pointer with the offset of the variable.
7728     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7729   }
7730
7731   llvm_unreachable("TLS not implemented for this target.");
7732 }
7733
7734
7735 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7736 /// and take a 2 x i32 value to shift plus a shift amount.
7737 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7738   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7739   EVT VT = Op.getValueType();
7740   unsigned VTBits = VT.getSizeInBits();
7741   DebugLoc dl = Op.getDebugLoc();
7742   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7743   SDValue ShOpLo = Op.getOperand(0);
7744   SDValue ShOpHi = Op.getOperand(1);
7745   SDValue ShAmt  = Op.getOperand(2);
7746   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7747                                      DAG.getConstant(VTBits - 1, MVT::i8))
7748                        : DAG.getConstant(0, VT);
7749
7750   SDValue Tmp2, Tmp3;
7751   if (Op.getOpcode() == ISD::SHL_PARTS) {
7752     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7753     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7754   } else {
7755     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7756     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7757   }
7758
7759   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7760                                 DAG.getConstant(VTBits, MVT::i8));
7761   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7762                              AndNode, DAG.getConstant(0, MVT::i8));
7763
7764   SDValue Hi, Lo;
7765   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7766   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7767   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7768
7769   if (Op.getOpcode() == ISD::SHL_PARTS) {
7770     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7771     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7772   } else {
7773     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7774     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7775   }
7776
7777   SDValue Ops[2] = { Lo, Hi };
7778   return DAG.getMergeValues(Ops, 2, dl);
7779 }
7780
7781 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7782                                            SelectionDAG &DAG) const {
7783   EVT SrcVT = Op.getOperand(0).getValueType();
7784
7785   if (SrcVT.isVector())
7786     return SDValue();
7787
7788   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7789          "Unknown SINT_TO_FP to lower!");
7790
7791   // These are really Legal; return the operand so the caller accepts it as
7792   // Legal.
7793   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7794     return Op;
7795   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7796       Subtarget->is64Bit()) {
7797     return Op;
7798   }
7799
7800   DebugLoc dl = Op.getDebugLoc();
7801   unsigned Size = SrcVT.getSizeInBits()/8;
7802   MachineFunction &MF = DAG.getMachineFunction();
7803   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7804   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7805   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7806                                StackSlot,
7807                                MachinePointerInfo::getFixedStack(SSFI),
7808                                false, false, 0);
7809   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7810 }
7811
7812 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7813                                      SDValue StackSlot,
7814                                      SelectionDAG &DAG) const {
7815   // Build the FILD
7816   DebugLoc DL = Op.getDebugLoc();
7817   SDVTList Tys;
7818   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7819   if (useSSE)
7820     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7821   else
7822     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7823
7824   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7825
7826   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7827   MachineMemOperand *MMO;
7828   if (FI) {
7829     int SSFI = FI->getIndex();
7830     MMO =
7831       DAG.getMachineFunction()
7832       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7833                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7834   } else {
7835     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7836     StackSlot = StackSlot.getOperand(1);
7837   }
7838   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7839   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7840                                            X86ISD::FILD, DL,
7841                                            Tys, Ops, array_lengthof(Ops),
7842                                            SrcVT, MMO);
7843
7844   if (useSSE) {
7845     Chain = Result.getValue(1);
7846     SDValue InFlag = Result.getValue(2);
7847
7848     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7849     // shouldn't be necessary except that RFP cannot be live across
7850     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7851     MachineFunction &MF = DAG.getMachineFunction();
7852     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7853     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7854     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7855     Tys = DAG.getVTList(MVT::Other);
7856     SDValue Ops[] = {
7857       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7858     };
7859     MachineMemOperand *MMO =
7860       DAG.getMachineFunction()
7861       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7862                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7863
7864     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7865                                     Ops, array_lengthof(Ops),
7866                                     Op.getValueType(), MMO);
7867     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7868                          MachinePointerInfo::getFixedStack(SSFI),
7869                          false, false, false, 0);
7870   }
7871
7872   return Result;
7873 }
7874
7875 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7876 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7877                                                SelectionDAG &DAG) const {
7878   // This algorithm is not obvious. Here it is what we're trying to output:
7879   /*
7880      movq       %rax,  %xmm0
7881      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7882      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7883      #ifdef __SSE3__
7884        haddpd   %xmm0, %xmm0
7885      #else
7886        pshufd   $0x4e, %xmm0, %xmm1
7887        addpd    %xmm1, %xmm0
7888      #endif
7889   */
7890
7891   DebugLoc dl = Op.getDebugLoc();
7892   LLVMContext *Context = DAG.getContext();
7893
7894   // Build some magic constants.
7895   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7896   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7897   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7898
7899   SmallVector<Constant*,2> CV1;
7900   CV1.push_back(
7901         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7902   CV1.push_back(
7903         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7904   Constant *C1 = ConstantVector::get(CV1);
7905   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7906
7907   // Load the 64-bit value into an XMM register.
7908   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7909                             Op.getOperand(0));
7910   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7911                               MachinePointerInfo::getConstantPool(),
7912                               false, false, false, 16);
7913   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7914                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7915                               CLod0);
7916
7917   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7918                               MachinePointerInfo::getConstantPool(),
7919                               false, false, false, 16);
7920   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7921   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7922   SDValue Result;
7923
7924   if (Subtarget->hasSSE3()) {
7925     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7926     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7927   } else {
7928     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7929     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7930                                            S2F, 0x4E, DAG);
7931     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7932                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7933                          Sub);
7934   }
7935
7936   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7937                      DAG.getIntPtrConstant(0));
7938 }
7939
7940 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7941 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7942                                                SelectionDAG &DAG) const {
7943   DebugLoc dl = Op.getDebugLoc();
7944   // FP constant to bias correct the final result.
7945   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7946                                    MVT::f64);
7947
7948   // Load the 32-bit value into an XMM register.
7949   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7950                              Op.getOperand(0));
7951
7952   // Zero out the upper parts of the register.
7953   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7954
7955   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7956                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7957                      DAG.getIntPtrConstant(0));
7958
7959   // Or the load with the bias.
7960   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7961                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7962                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7963                                                    MVT::v2f64, Load)),
7964                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7965                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7966                                                    MVT::v2f64, Bias)));
7967   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7968                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7969                    DAG.getIntPtrConstant(0));
7970
7971   // Subtract the bias.
7972   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7973
7974   // Handle final rounding.
7975   EVT DestVT = Op.getValueType();
7976
7977   if (DestVT.bitsLT(MVT::f64))
7978     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7979                        DAG.getIntPtrConstant(0));
7980   if (DestVT.bitsGT(MVT::f64))
7981     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7982
7983   // Handle final rounding.
7984   return Sub;
7985 }
7986
7987 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7988                                            SelectionDAG &DAG) const {
7989   SDValue N0 = Op.getOperand(0);
7990   DebugLoc dl = Op.getDebugLoc();
7991
7992   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7993   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7994   // the optimization here.
7995   if (DAG.SignBitIsZero(N0))
7996     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7997
7998   EVT SrcVT = N0.getValueType();
7999   EVT DstVT = Op.getValueType();
8000   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8001     return LowerUINT_TO_FP_i64(Op, DAG);
8002   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8003     return LowerUINT_TO_FP_i32(Op, DAG);
8004   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8005     return SDValue();
8006
8007   // Make a 64-bit buffer, and use it to build an FILD.
8008   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8009   if (SrcVT == MVT::i32) {
8010     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8011     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8012                                      getPointerTy(), StackSlot, WordOff);
8013     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8014                                   StackSlot, MachinePointerInfo(),
8015                                   false, false, 0);
8016     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8017                                   OffsetSlot, MachinePointerInfo(),
8018                                   false, false, 0);
8019     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8020     return Fild;
8021   }
8022
8023   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8024   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8025                                StackSlot, MachinePointerInfo(),
8026                                false, false, 0);
8027   // For i64 source, we need to add the appropriate power of 2 if the input
8028   // was negative.  This is the same as the optimization in
8029   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8030   // we must be careful to do the computation in x87 extended precision, not
8031   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8032   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8033   MachineMemOperand *MMO =
8034     DAG.getMachineFunction()
8035     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8036                           MachineMemOperand::MOLoad, 8, 8);
8037
8038   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8039   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8040   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8041                                          MVT::i64, MMO);
8042
8043   APInt FF(32, 0x5F800000ULL);
8044
8045   // Check whether the sign bit is set.
8046   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8047                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8048                                  ISD::SETLT);
8049
8050   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8051   SDValue FudgePtr = DAG.getConstantPool(
8052                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8053                                          getPointerTy());
8054
8055   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8056   SDValue Zero = DAG.getIntPtrConstant(0);
8057   SDValue Four = DAG.getIntPtrConstant(4);
8058   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8059                                Zero, Four);
8060   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8061
8062   // Load the value out, extending it from f32 to f80.
8063   // FIXME: Avoid the extend by constructing the right constant pool?
8064   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8065                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8066                                  MVT::f32, false, false, 4);
8067   // Extend everything to 80 bits to force it to be done on x87.
8068   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8069   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8070 }
8071
8072 std::pair<SDValue,SDValue> X86TargetLowering::
8073 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8074   DebugLoc DL = Op.getDebugLoc();
8075
8076   EVT DstTy = Op.getValueType();
8077
8078   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8079     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8080     DstTy = MVT::i64;
8081   }
8082
8083   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8084          DstTy.getSimpleVT() >= MVT::i16 &&
8085          "Unknown FP_TO_INT to lower!");
8086
8087   // These are really Legal.
8088   if (DstTy == MVT::i32 &&
8089       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8090     return std::make_pair(SDValue(), SDValue());
8091   if (Subtarget->is64Bit() &&
8092       DstTy == MVT::i64 &&
8093       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8094     return std::make_pair(SDValue(), SDValue());
8095
8096   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8097   // stack slot, or into the FTOL runtime function.
8098   MachineFunction &MF = DAG.getMachineFunction();
8099   unsigned MemSize = DstTy.getSizeInBits()/8;
8100   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8101   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8102
8103   unsigned Opc;
8104   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8105     Opc = X86ISD::WIN_FTOL;
8106   else
8107     switch (DstTy.getSimpleVT().SimpleTy) {
8108     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8109     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8110     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8111     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8112     }
8113
8114   SDValue Chain = DAG.getEntryNode();
8115   SDValue Value = Op.getOperand(0);
8116   EVT TheVT = Op.getOperand(0).getValueType();
8117   // FIXME This causes a redundant load/store if the SSE-class value is already
8118   // in memory, such as if it is on the callstack.
8119   if (isScalarFPTypeInSSEReg(TheVT)) {
8120     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8121     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8122                          MachinePointerInfo::getFixedStack(SSFI),
8123                          false, false, 0);
8124     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8125     SDValue Ops[] = {
8126       Chain, StackSlot, DAG.getValueType(TheVT)
8127     };
8128
8129     MachineMemOperand *MMO =
8130       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8131                               MachineMemOperand::MOLoad, MemSize, MemSize);
8132     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8133                                     DstTy, MMO);
8134     Chain = Value.getValue(1);
8135     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8136     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8137   }
8138
8139   MachineMemOperand *MMO =
8140     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8141                             MachineMemOperand::MOStore, MemSize, MemSize);
8142
8143   if (Opc != X86ISD::WIN_FTOL) {
8144     // Build the FP_TO_INT*_IN_MEM
8145     SDValue Ops[] = { Chain, Value, StackSlot };
8146     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8147                                            Ops, 3, DstTy, MMO);
8148     return std::make_pair(FIST, StackSlot);
8149   } else {
8150     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8151       DAG.getVTList(MVT::Other, MVT::Glue),
8152       Chain, Value);
8153     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8154       MVT::i32, ftol.getValue(1));
8155     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8156       MVT::i32, eax.getValue(2));
8157     SDValue Ops[] = { eax, edx };
8158     SDValue pair = IsReplace
8159       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8160       : DAG.getMergeValues(Ops, 2, DL);
8161     return std::make_pair(pair, SDValue());
8162   }
8163 }
8164
8165 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8166                                            SelectionDAG &DAG) const {
8167   if (Op.getValueType().isVector())
8168     return SDValue();
8169
8170   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8171     /*IsSigned=*/ true, /*IsReplace=*/ false);
8172   SDValue FIST = Vals.first, StackSlot = Vals.second;
8173   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8174   if (FIST.getNode() == 0) return Op;
8175
8176   if (StackSlot.getNode())
8177     // Load the result.
8178     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8179                        FIST, StackSlot, MachinePointerInfo(),
8180                        false, false, false, 0);
8181
8182   // The node is the result.
8183   return FIST;
8184 }
8185
8186 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8187                                            SelectionDAG &DAG) const {
8188   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8189     /*IsSigned=*/ false, /*IsReplace=*/ false);
8190   SDValue FIST = Vals.first, StackSlot = Vals.second;
8191   assert(FIST.getNode() && "Unexpected failure");
8192
8193   if (StackSlot.getNode())
8194     // Load the result.
8195     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8196                        FIST, StackSlot, MachinePointerInfo(),
8197                        false, false, false, 0);
8198
8199   // The node is the result.
8200   return FIST;
8201 }
8202
8203 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8204   LLVMContext *Context = DAG.getContext();
8205   DebugLoc dl = Op.getDebugLoc();
8206   EVT VT = Op.getValueType();
8207   EVT EltVT = VT;
8208   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8209   if (VT.isVector()) {
8210     EltVT = VT.getVectorElementType();
8211     NumElts = VT.getVectorNumElements();
8212   }
8213   Constant *C;
8214   if (EltVT == MVT::f64)
8215     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8216   else
8217     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8218   C = ConstantVector::getSplat(NumElts, C);
8219   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8220   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8221   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8222                              MachinePointerInfo::getConstantPool(),
8223                              false, false, false, Alignment);
8224   if (VT.isVector()) {
8225     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8226     return DAG.getNode(ISD::BITCAST, dl, VT,
8227                        DAG.getNode(ISD::AND, dl, ANDVT,
8228                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8229                                                Op.getOperand(0)),
8230                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8231   }
8232   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8233 }
8234
8235 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8236   LLVMContext *Context = DAG.getContext();
8237   DebugLoc dl = Op.getDebugLoc();
8238   EVT VT = Op.getValueType();
8239   EVT EltVT = VT;
8240   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8241   if (VT.isVector()) {
8242     EltVT = VT.getVectorElementType();
8243     NumElts = VT.getVectorNumElements();
8244   }
8245   Constant *C;
8246   if (EltVT == MVT::f64)
8247     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8248   else
8249     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8250   C = ConstantVector::getSplat(NumElts, C);
8251   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8252   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8253   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8254                              MachinePointerInfo::getConstantPool(),
8255                              false, false, false, Alignment);
8256   if (VT.isVector()) {
8257     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8258     return DAG.getNode(ISD::BITCAST, dl, VT,
8259                        DAG.getNode(ISD::XOR, dl, XORVT,
8260                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8261                                                Op.getOperand(0)),
8262                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8263   }
8264
8265   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8266 }
8267
8268 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8269   LLVMContext *Context = DAG.getContext();
8270   SDValue Op0 = Op.getOperand(0);
8271   SDValue Op1 = Op.getOperand(1);
8272   DebugLoc dl = Op.getDebugLoc();
8273   EVT VT = Op.getValueType();
8274   EVT SrcVT = Op1.getValueType();
8275
8276   // If second operand is smaller, extend it first.
8277   if (SrcVT.bitsLT(VT)) {
8278     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8279     SrcVT = VT;
8280   }
8281   // And if it is bigger, shrink it first.
8282   if (SrcVT.bitsGT(VT)) {
8283     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8284     SrcVT = VT;
8285   }
8286
8287   // At this point the operands and the result should have the same
8288   // type, and that won't be f80 since that is not custom lowered.
8289
8290   // First get the sign bit of second operand.
8291   SmallVector<Constant*,4> CV;
8292   if (SrcVT == MVT::f64) {
8293     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8294     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8295   } else {
8296     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8297     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8298     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8299     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8300   }
8301   Constant *C = ConstantVector::get(CV);
8302   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8303   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8304                               MachinePointerInfo::getConstantPool(),
8305                               false, false, false, 16);
8306   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8307
8308   // Shift sign bit right or left if the two operands have different types.
8309   if (SrcVT.bitsGT(VT)) {
8310     // Op0 is MVT::f32, Op1 is MVT::f64.
8311     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8312     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8313                           DAG.getConstant(32, MVT::i32));
8314     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8315     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8316                           DAG.getIntPtrConstant(0));
8317   }
8318
8319   // Clear first operand sign bit.
8320   CV.clear();
8321   if (VT == MVT::f64) {
8322     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8323     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8324   } else {
8325     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8326     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8327     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8328     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8329   }
8330   C = ConstantVector::get(CV);
8331   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8332   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8333                               MachinePointerInfo::getConstantPool(),
8334                               false, false, false, 16);
8335   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8336
8337   // Or the value with the sign bit.
8338   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8339 }
8340
8341 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8342   SDValue N0 = Op.getOperand(0);
8343   DebugLoc dl = Op.getDebugLoc();
8344   EVT VT = Op.getValueType();
8345
8346   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8347   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8348                                   DAG.getConstant(1, VT));
8349   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8350 }
8351
8352 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8353 //
8354 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8355   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8356
8357   if (!Subtarget->hasSSE41())
8358     return SDValue();
8359
8360   if (!Op->hasOneUse())
8361     return SDValue();
8362
8363   SDNode *N = Op.getNode();
8364   DebugLoc DL = N->getDebugLoc();
8365
8366   SmallVector<SDValue, 8> Opnds;
8367   DenseMap<SDValue, unsigned> VecInMap;
8368   EVT VT = MVT::Other;
8369
8370   // Recognize a special case where a vector is casted into wide integer to
8371   // test all 0s.
8372   Opnds.push_back(N->getOperand(0));
8373   Opnds.push_back(N->getOperand(1));
8374
8375   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8376     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8377     // BFS traverse all OR'd operands.
8378     if (I->getOpcode() == ISD::OR) {
8379       Opnds.push_back(I->getOperand(0));
8380       Opnds.push_back(I->getOperand(1));
8381       // Re-evaluate the number of nodes to be traversed.
8382       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8383       continue;
8384     }
8385
8386     // Quit if a non-EXTRACT_VECTOR_ELT
8387     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8388       return SDValue();
8389
8390     // Quit if without a constant index.
8391     SDValue Idx = I->getOperand(1);
8392     if (!isa<ConstantSDNode>(Idx))
8393       return SDValue();
8394
8395     SDValue ExtractedFromVec = I->getOperand(0);
8396     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8397     if (M == VecInMap.end()) {
8398       VT = ExtractedFromVec.getValueType();
8399       // Quit if not 128/256-bit vector.
8400       if (!VT.is128BitVector() && !VT.is256BitVector())
8401         return SDValue();
8402       // Quit if not the same type.
8403       if (VecInMap.begin() != VecInMap.end() &&
8404           VT != VecInMap.begin()->first.getValueType())
8405         return SDValue();
8406       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8407     }
8408     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8409   }
8410
8411   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8412          "Not extracted from 128-/256-bit vector.");
8413
8414   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8415   SmallVector<SDValue, 8> VecIns;
8416
8417   for (DenseMap<SDValue, unsigned>::const_iterator
8418         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8419     // Quit if not all elements are used.
8420     if (I->second != FullMask)
8421       return SDValue();
8422     VecIns.push_back(I->first);
8423   }
8424
8425   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8426
8427   // Cast all vectors into TestVT for PTEST.
8428   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8429     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8430
8431   // If more than one full vectors are evaluated, OR them first before PTEST.
8432   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8433     // Each iteration will OR 2 nodes and append the result until there is only
8434     // 1 node left, i.e. the final OR'd value of all vectors.
8435     SDValue LHS = VecIns[Slot];
8436     SDValue RHS = VecIns[Slot + 1];
8437     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8438   }
8439
8440   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8441                      VecIns.back(), VecIns.back());
8442 }
8443
8444 /// Emit nodes that will be selected as "test Op0,Op0", or something
8445 /// equivalent.
8446 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8447                                     SelectionDAG &DAG) const {
8448   DebugLoc dl = Op.getDebugLoc();
8449
8450   // CF and OF aren't always set the way we want. Determine which
8451   // of these we need.
8452   bool NeedCF = false;
8453   bool NeedOF = false;
8454   switch (X86CC) {
8455   default: break;
8456   case X86::COND_A: case X86::COND_AE:
8457   case X86::COND_B: case X86::COND_BE:
8458     NeedCF = true;
8459     break;
8460   case X86::COND_G: case X86::COND_GE:
8461   case X86::COND_L: case X86::COND_LE:
8462   case X86::COND_O: case X86::COND_NO:
8463     NeedOF = true;
8464     break;
8465   }
8466
8467   // See if we can use the EFLAGS value from the operand instead of
8468   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8469   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8470   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8471     // Emit a CMP with 0, which is the TEST pattern.
8472     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8473                        DAG.getConstant(0, Op.getValueType()));
8474
8475   unsigned Opcode = 0;
8476   unsigned NumOperands = 0;
8477
8478   // Truncate operations may prevent the merge of the SETCC instruction
8479   // and the arithmetic intruction before it. Attempt to truncate the operands
8480   // of the arithmetic instruction and use a reduced bit-width instruction.
8481   bool NeedTruncation = false;
8482   SDValue ArithOp = Op;
8483   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8484     SDValue Arith = Op->getOperand(0);
8485     // Both the trunc and the arithmetic op need to have one user each.
8486     if (Arith->hasOneUse())
8487       switch (Arith.getOpcode()) {
8488         default: break;
8489         case ISD::ADD:
8490         case ISD::SUB:
8491         case ISD::AND:
8492         case ISD::OR:
8493         case ISD::XOR: {
8494           NeedTruncation = true;
8495           ArithOp = Arith;
8496         }
8497       }
8498   }
8499
8500   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8501   // which may be the result of a CAST.  We use the variable 'Op', which is the
8502   // non-casted variable when we check for possible users.
8503   switch (ArithOp.getOpcode()) {
8504   case ISD::ADD:
8505     // Due to an isel shortcoming, be conservative if this add is likely to be
8506     // selected as part of a load-modify-store instruction. When the root node
8507     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8508     // uses of other nodes in the match, such as the ADD in this case. This
8509     // leads to the ADD being left around and reselected, with the result being
8510     // two adds in the output.  Alas, even if none our users are stores, that
8511     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8512     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8513     // climbing the DAG back to the root, and it doesn't seem to be worth the
8514     // effort.
8515     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8516          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8517       if (UI->getOpcode() != ISD::CopyToReg &&
8518           UI->getOpcode() != ISD::SETCC &&
8519           UI->getOpcode() != ISD::STORE)
8520         goto default_case;
8521
8522     if (ConstantSDNode *C =
8523         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8524       // An add of one will be selected as an INC.
8525       if (C->getAPIntValue() == 1) {
8526         Opcode = X86ISD::INC;
8527         NumOperands = 1;
8528         break;
8529       }
8530
8531       // An add of negative one (subtract of one) will be selected as a DEC.
8532       if (C->getAPIntValue().isAllOnesValue()) {
8533         Opcode = X86ISD::DEC;
8534         NumOperands = 1;
8535         break;
8536       }
8537     }
8538
8539     // Otherwise use a regular EFLAGS-setting add.
8540     Opcode = X86ISD::ADD;
8541     NumOperands = 2;
8542     break;
8543   case ISD::AND: {
8544     // If the primary and result isn't used, don't bother using X86ISD::AND,
8545     // because a TEST instruction will be better.
8546     bool NonFlagUse = false;
8547     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8548            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8549       SDNode *User = *UI;
8550       unsigned UOpNo = UI.getOperandNo();
8551       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8552         // Look pass truncate.
8553         UOpNo = User->use_begin().getOperandNo();
8554         User = *User->use_begin();
8555       }
8556
8557       if (User->getOpcode() != ISD::BRCOND &&
8558           User->getOpcode() != ISD::SETCC &&
8559           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8560         NonFlagUse = true;
8561         break;
8562       }
8563     }
8564
8565     if (!NonFlagUse)
8566       break;
8567   }
8568     // FALL THROUGH
8569   case ISD::SUB:
8570   case ISD::OR:
8571   case ISD::XOR:
8572     // Due to the ISEL shortcoming noted above, be conservative if this op is
8573     // likely to be selected as part of a load-modify-store instruction.
8574     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8575            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8576       if (UI->getOpcode() == ISD::STORE)
8577         goto default_case;
8578
8579     // Otherwise use a regular EFLAGS-setting instruction.
8580     switch (ArithOp.getOpcode()) {
8581     default: llvm_unreachable("unexpected operator!");
8582     case ISD::SUB: Opcode = X86ISD::SUB; break;
8583     case ISD::XOR: Opcode = X86ISD::XOR; break;
8584     case ISD::AND: Opcode = X86ISD::AND; break;
8585     case ISD::OR: {
8586       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8587         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8588         if (EFLAGS.getNode())
8589           return EFLAGS;
8590       }
8591       Opcode = X86ISD::OR;
8592       break;
8593     }
8594     }
8595
8596     NumOperands = 2;
8597     break;
8598   case X86ISD::ADD:
8599   case X86ISD::SUB:
8600   case X86ISD::INC:
8601   case X86ISD::DEC:
8602   case X86ISD::OR:
8603   case X86ISD::XOR:
8604   case X86ISD::AND:
8605     return SDValue(Op.getNode(), 1);
8606   default:
8607   default_case:
8608     break;
8609   }
8610
8611   // If we found that truncation is beneficial, perform the truncation and
8612   // update 'Op'.
8613   if (NeedTruncation) {
8614     EVT VT = Op.getValueType();
8615     SDValue WideVal = Op->getOperand(0);
8616     EVT WideVT = WideVal.getValueType();
8617     unsigned ConvertedOp = 0;
8618     // Use a target machine opcode to prevent further DAGCombine
8619     // optimizations that may separate the arithmetic operations
8620     // from the setcc node.
8621     switch (WideVal.getOpcode()) {
8622       default: break;
8623       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8624       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8625       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8626       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8627       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8628     }
8629
8630     if (ConvertedOp) {
8631       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8632       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8633         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8634         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8635         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8636       }
8637     }
8638   }
8639
8640   if (Opcode == 0)
8641     // Emit a CMP with 0, which is the TEST pattern.
8642     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8643                        DAG.getConstant(0, Op.getValueType()));
8644
8645   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8646   SmallVector<SDValue, 4> Ops;
8647   for (unsigned i = 0; i != NumOperands; ++i)
8648     Ops.push_back(Op.getOperand(i));
8649
8650   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8651   DAG.ReplaceAllUsesWith(Op, New);
8652   return SDValue(New.getNode(), 1);
8653 }
8654
8655 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8656 /// equivalent.
8657 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8658                                    SelectionDAG &DAG) const {
8659   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8660     if (C->getAPIntValue() == 0)
8661       return EmitTest(Op0, X86CC, DAG);
8662
8663   DebugLoc dl = Op0.getDebugLoc();
8664   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8665        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8666     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8667     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8668     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8669                               Op0, Op1);
8670     return SDValue(Sub.getNode(), 1);
8671   }
8672   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8673 }
8674
8675 /// Convert a comparison if required by the subtarget.
8676 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8677                                                  SelectionDAG &DAG) const {
8678   // If the subtarget does not support the FUCOMI instruction, floating-point
8679   // comparisons have to be converted.
8680   if (Subtarget->hasCMov() ||
8681       Cmp.getOpcode() != X86ISD::CMP ||
8682       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8683       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8684     return Cmp;
8685
8686   // The instruction selector will select an FUCOM instruction instead of
8687   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8688   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8689   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8690   DebugLoc dl = Cmp.getDebugLoc();
8691   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8692   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8693   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8694                             DAG.getConstant(8, MVT::i8));
8695   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8696   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8697 }
8698
8699 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8700 /// if it's possible.
8701 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8702                                      DebugLoc dl, SelectionDAG &DAG) const {
8703   SDValue Op0 = And.getOperand(0);
8704   SDValue Op1 = And.getOperand(1);
8705   if (Op0.getOpcode() == ISD::TRUNCATE)
8706     Op0 = Op0.getOperand(0);
8707   if (Op1.getOpcode() == ISD::TRUNCATE)
8708     Op1 = Op1.getOperand(0);
8709
8710   SDValue LHS, RHS;
8711   if (Op1.getOpcode() == ISD::SHL)
8712     std::swap(Op0, Op1);
8713   if (Op0.getOpcode() == ISD::SHL) {
8714     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8715       if (And00C->getZExtValue() == 1) {
8716         // If we looked past a truncate, check that it's only truncating away
8717         // known zeros.
8718         unsigned BitWidth = Op0.getValueSizeInBits();
8719         unsigned AndBitWidth = And.getValueSizeInBits();
8720         if (BitWidth > AndBitWidth) {
8721           APInt Zeros, Ones;
8722           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8723           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8724             return SDValue();
8725         }
8726         LHS = Op1;
8727         RHS = Op0.getOperand(1);
8728       }
8729   } else if (Op1.getOpcode() == ISD::Constant) {
8730     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8731     uint64_t AndRHSVal = AndRHS->getZExtValue();
8732     SDValue AndLHS = Op0;
8733
8734     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8735       LHS = AndLHS.getOperand(0);
8736       RHS = AndLHS.getOperand(1);
8737     }
8738
8739     // Use BT if the immediate can't be encoded in a TEST instruction.
8740     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8741       LHS = AndLHS;
8742       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8743     }
8744   }
8745
8746   if (LHS.getNode()) {
8747     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8748     // instruction.  Since the shift amount is in-range-or-undefined, we know
8749     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8750     // the encoding for the i16 version is larger than the i32 version.
8751     // Also promote i16 to i32 for performance / code size reason.
8752     if (LHS.getValueType() == MVT::i8 ||
8753         LHS.getValueType() == MVT::i16)
8754       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8755
8756     // If the operand types disagree, extend the shift amount to match.  Since
8757     // BT ignores high bits (like shifts) we can use anyextend.
8758     if (LHS.getValueType() != RHS.getValueType())
8759       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8760
8761     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8762     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8763     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8764                        DAG.getConstant(Cond, MVT::i8), BT);
8765   }
8766
8767   return SDValue();
8768 }
8769
8770 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8771
8772   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8773
8774   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8775   SDValue Op0 = Op.getOperand(0);
8776   SDValue Op1 = Op.getOperand(1);
8777   DebugLoc dl = Op.getDebugLoc();
8778   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8779
8780   // Optimize to BT if possible.
8781   // Lower (X & (1 << N)) == 0 to BT(X, N).
8782   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8783   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8784   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8785       Op1.getOpcode() == ISD::Constant &&
8786       cast<ConstantSDNode>(Op1)->isNullValue() &&
8787       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8788     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8789     if (NewSetCC.getNode())
8790       return NewSetCC;
8791   }
8792
8793   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8794   // these.
8795   if (Op1.getOpcode() == ISD::Constant &&
8796       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8797        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8798       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8799
8800     // If the input is a setcc, then reuse the input setcc or use a new one with
8801     // the inverted condition.
8802     if (Op0.getOpcode() == X86ISD::SETCC) {
8803       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8804       bool Invert = (CC == ISD::SETNE) ^
8805         cast<ConstantSDNode>(Op1)->isNullValue();
8806       if (!Invert) return Op0;
8807
8808       CCode = X86::GetOppositeBranchCondition(CCode);
8809       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8810                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8811     }
8812   }
8813
8814   bool isFP = Op1.getValueType().isFloatingPoint();
8815   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8816   if (X86CC == X86::COND_INVALID)
8817     return SDValue();
8818
8819   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8820   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8821   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8822                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8823 }
8824
8825 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8826 // ones, and then concatenate the result back.
8827 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8828   EVT VT = Op.getValueType();
8829
8830   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8831          "Unsupported value type for operation");
8832
8833   unsigned NumElems = VT.getVectorNumElements();
8834   DebugLoc dl = Op.getDebugLoc();
8835   SDValue CC = Op.getOperand(2);
8836
8837   // Extract the LHS vectors
8838   SDValue LHS = Op.getOperand(0);
8839   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8840   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8841
8842   // Extract the RHS vectors
8843   SDValue RHS = Op.getOperand(1);
8844   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8845   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8846
8847   // Issue the operation on the smaller types and concatenate the result back
8848   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8849   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8850   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8851                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8852                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8853 }
8854
8855
8856 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8857   SDValue Cond;
8858   SDValue Op0 = Op.getOperand(0);
8859   SDValue Op1 = Op.getOperand(1);
8860   SDValue CC = Op.getOperand(2);
8861   EVT VT = Op.getValueType();
8862   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8863   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8864   DebugLoc dl = Op.getDebugLoc();
8865
8866   if (isFP) {
8867 #ifndef NDEBUG
8868     EVT EltVT = Op0.getValueType().getVectorElementType();
8869     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8870 #endif
8871
8872     unsigned SSECC;
8873     bool Swap = false;
8874
8875     // SSE Condition code mapping:
8876     //  0 - EQ
8877     //  1 - LT
8878     //  2 - LE
8879     //  3 - UNORD
8880     //  4 - NEQ
8881     //  5 - NLT
8882     //  6 - NLE
8883     //  7 - ORD
8884     switch (SetCCOpcode) {
8885     default: llvm_unreachable("Unexpected SETCC condition");
8886     case ISD::SETOEQ:
8887     case ISD::SETEQ:  SSECC = 0; break;
8888     case ISD::SETOGT:
8889     case ISD::SETGT: Swap = true; // Fallthrough
8890     case ISD::SETLT:
8891     case ISD::SETOLT: SSECC = 1; break;
8892     case ISD::SETOGE:
8893     case ISD::SETGE: Swap = true; // Fallthrough
8894     case ISD::SETLE:
8895     case ISD::SETOLE: SSECC = 2; break;
8896     case ISD::SETUO:  SSECC = 3; break;
8897     case ISD::SETUNE:
8898     case ISD::SETNE:  SSECC = 4; break;
8899     case ISD::SETULE: Swap = true; // Fallthrough
8900     case ISD::SETUGE: SSECC = 5; break;
8901     case ISD::SETULT: Swap = true; // Fallthrough
8902     case ISD::SETUGT: SSECC = 6; break;
8903     case ISD::SETO:   SSECC = 7; break;
8904     case ISD::SETUEQ:
8905     case ISD::SETONE: SSECC = 8; break;
8906     }
8907     if (Swap)
8908       std::swap(Op0, Op1);
8909
8910     // In the two special cases we can't handle, emit two comparisons.
8911     if (SSECC == 8) {
8912       unsigned CC0, CC1;
8913       unsigned CombineOpc;
8914       if (SetCCOpcode == ISD::SETUEQ) {
8915         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8916       } else {
8917         assert(SetCCOpcode == ISD::SETONE);
8918         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8919       }
8920
8921       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8922                                  DAG.getConstant(CC0, MVT::i8));
8923       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8924                                  DAG.getConstant(CC1, MVT::i8));
8925       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8926     }
8927     // Handle all other FP comparisons here.
8928     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8929                        DAG.getConstant(SSECC, MVT::i8));
8930   }
8931
8932   // Break 256-bit integer vector compare into smaller ones.
8933   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8934     return Lower256IntVSETCC(Op, DAG);
8935
8936   // We are handling one of the integer comparisons here.  Since SSE only has
8937   // GT and EQ comparisons for integer, swapping operands and multiple
8938   // operations may be required for some comparisons.
8939   unsigned Opc;
8940   bool Swap = false, Invert = false, FlipSigns = false;
8941
8942   switch (SetCCOpcode) {
8943   default: llvm_unreachable("Unexpected SETCC condition");
8944   case ISD::SETNE:  Invert = true;
8945   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8946   case ISD::SETLT:  Swap = true;
8947   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8948   case ISD::SETGE:  Swap = true;
8949   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8950   case ISD::SETULT: Swap = true;
8951   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8952   case ISD::SETUGE: Swap = true;
8953   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8954   }
8955   if (Swap)
8956     std::swap(Op0, Op1);
8957
8958   // Check that the operation in question is available (most are plain SSE2,
8959   // but PCMPGTQ and PCMPEQQ have different requirements).
8960   if (VT == MVT::v2i64) {
8961     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8962       return SDValue();
8963     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8964       return SDValue();
8965   }
8966
8967   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8968   // bits of the inputs before performing those operations.
8969   if (FlipSigns) {
8970     EVT EltVT = VT.getVectorElementType();
8971     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8972                                       EltVT);
8973     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8974     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8975                                     SignBits.size());
8976     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8977     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8978   }
8979
8980   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8981
8982   // If the logical-not of the result is required, perform that now.
8983   if (Invert)
8984     Result = DAG.getNOT(dl, Result, VT);
8985
8986   return Result;
8987 }
8988
8989 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8990 static bool isX86LogicalCmp(SDValue Op) {
8991   unsigned Opc = Op.getNode()->getOpcode();
8992   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8993       Opc == X86ISD::SAHF)
8994     return true;
8995   if (Op.getResNo() == 1 &&
8996       (Opc == X86ISD::ADD ||
8997        Opc == X86ISD::SUB ||
8998        Opc == X86ISD::ADC ||
8999        Opc == X86ISD::SBB ||
9000        Opc == X86ISD::SMUL ||
9001        Opc == X86ISD::UMUL ||
9002        Opc == X86ISD::INC ||
9003        Opc == X86ISD::DEC ||
9004        Opc == X86ISD::OR ||
9005        Opc == X86ISD::XOR ||
9006        Opc == X86ISD::AND))
9007     return true;
9008
9009   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9010     return true;
9011
9012   return false;
9013 }
9014
9015 static bool isZero(SDValue V) {
9016   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9017   return C && C->isNullValue();
9018 }
9019
9020 static bool isAllOnes(SDValue V) {
9021   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9022   return C && C->isAllOnesValue();
9023 }
9024
9025 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9026   if (V.getOpcode() != ISD::TRUNCATE)
9027     return false;
9028
9029   SDValue VOp0 = V.getOperand(0);
9030   unsigned InBits = VOp0.getValueSizeInBits();
9031   unsigned Bits = V.getValueSizeInBits();
9032   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9033 }
9034
9035 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9036   bool addTest = true;
9037   SDValue Cond  = Op.getOperand(0);
9038   SDValue Op1 = Op.getOperand(1);
9039   SDValue Op2 = Op.getOperand(2);
9040   DebugLoc DL = Op.getDebugLoc();
9041   SDValue CC;
9042
9043   if (Cond.getOpcode() == ISD::SETCC) {
9044     SDValue NewCond = LowerSETCC(Cond, DAG);
9045     if (NewCond.getNode())
9046       Cond = NewCond;
9047   }
9048
9049   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9050   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9051   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9052   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9053   if (Cond.getOpcode() == X86ISD::SETCC &&
9054       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9055       isZero(Cond.getOperand(1).getOperand(1))) {
9056     SDValue Cmp = Cond.getOperand(1);
9057
9058     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9059
9060     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9061         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9062       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9063
9064       SDValue CmpOp0 = Cmp.getOperand(0);
9065       // Apply further optimizations for special cases
9066       // (select (x != 0), -1, 0) -> neg & sbb
9067       // (select (x == 0), 0, -1) -> neg & sbb
9068       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9069         if (YC->isNullValue() &&
9070             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9071           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9072           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9073                                     DAG.getConstant(0, CmpOp0.getValueType()),
9074                                     CmpOp0);
9075           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9076                                     DAG.getConstant(X86::COND_B, MVT::i8),
9077                                     SDValue(Neg.getNode(), 1));
9078           return Res;
9079         }
9080
9081       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9082                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9083       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9084
9085       SDValue Res =   // Res = 0 or -1.
9086         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9087                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9088
9089       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9090         Res = DAG.getNOT(DL, Res, Res.getValueType());
9091
9092       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9093       if (N2C == 0 || !N2C->isNullValue())
9094         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9095       return Res;
9096     }
9097   }
9098
9099   // Look past (and (setcc_carry (cmp ...)), 1).
9100   if (Cond.getOpcode() == ISD::AND &&
9101       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9102     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9103     if (C && C->getAPIntValue() == 1)
9104       Cond = Cond.getOperand(0);
9105   }
9106
9107   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9108   // setting operand in place of the X86ISD::SETCC.
9109   unsigned CondOpcode = Cond.getOpcode();
9110   if (CondOpcode == X86ISD::SETCC ||
9111       CondOpcode == X86ISD::SETCC_CARRY) {
9112     CC = Cond.getOperand(0);
9113
9114     SDValue Cmp = Cond.getOperand(1);
9115     unsigned Opc = Cmp.getOpcode();
9116     EVT VT = Op.getValueType();
9117
9118     bool IllegalFPCMov = false;
9119     if (VT.isFloatingPoint() && !VT.isVector() &&
9120         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9121       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9122
9123     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9124         Opc == X86ISD::BT) { // FIXME
9125       Cond = Cmp;
9126       addTest = false;
9127     }
9128   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9129              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9130              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9131               Cond.getOperand(0).getValueType() != MVT::i8)) {
9132     SDValue LHS = Cond.getOperand(0);
9133     SDValue RHS = Cond.getOperand(1);
9134     unsigned X86Opcode;
9135     unsigned X86Cond;
9136     SDVTList VTs;
9137     switch (CondOpcode) {
9138     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9139     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9140     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9141     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9142     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9143     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9144     default: llvm_unreachable("unexpected overflowing operator");
9145     }
9146     if (CondOpcode == ISD::UMULO)
9147       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9148                           MVT::i32);
9149     else
9150       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9151
9152     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9153
9154     if (CondOpcode == ISD::UMULO)
9155       Cond = X86Op.getValue(2);
9156     else
9157       Cond = X86Op.getValue(1);
9158
9159     CC = DAG.getConstant(X86Cond, MVT::i8);
9160     addTest = false;
9161   }
9162
9163   if (addTest) {
9164     // Look pass the truncate if the high bits are known zero.
9165     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9166         Cond = Cond.getOperand(0);
9167
9168     // We know the result of AND is compared against zero. Try to match
9169     // it to BT.
9170     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9171       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9172       if (NewSetCC.getNode()) {
9173         CC = NewSetCC.getOperand(0);
9174         Cond = NewSetCC.getOperand(1);
9175         addTest = false;
9176       }
9177     }
9178   }
9179
9180   if (addTest) {
9181     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9182     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9183   }
9184
9185   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9186   // a <  b ?  0 : -1 -> RES = setcc_carry
9187   // a >= b ? -1 :  0 -> RES = setcc_carry
9188   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9189   if (Cond.getOpcode() == X86ISD::SUB) {
9190     Cond = ConvertCmpIfNecessary(Cond, DAG);
9191     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9192
9193     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9194         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9195       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9196                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9197       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9198         return DAG.getNOT(DL, Res, Res.getValueType());
9199       return Res;
9200     }
9201   }
9202
9203   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9204   // condition is true.
9205   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9206   SDValue Ops[] = { Op2, Op1, CC, Cond };
9207   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9208 }
9209
9210 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9211 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9212 // from the AND / OR.
9213 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9214   Opc = Op.getOpcode();
9215   if (Opc != ISD::OR && Opc != ISD::AND)
9216     return false;
9217   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9218           Op.getOperand(0).hasOneUse() &&
9219           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9220           Op.getOperand(1).hasOneUse());
9221 }
9222
9223 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9224 // 1 and that the SETCC node has a single use.
9225 static bool isXor1OfSetCC(SDValue Op) {
9226   if (Op.getOpcode() != ISD::XOR)
9227     return false;
9228   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9229   if (N1C && N1C->getAPIntValue() == 1) {
9230     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9231       Op.getOperand(0).hasOneUse();
9232   }
9233   return false;
9234 }
9235
9236 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9237   bool addTest = true;
9238   SDValue Chain = Op.getOperand(0);
9239   SDValue Cond  = Op.getOperand(1);
9240   SDValue Dest  = Op.getOperand(2);
9241   DebugLoc dl = Op.getDebugLoc();
9242   SDValue CC;
9243   bool Inverted = false;
9244
9245   if (Cond.getOpcode() == ISD::SETCC) {
9246     // Check for setcc([su]{add,sub,mul}o == 0).
9247     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9248         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9249         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9250         Cond.getOperand(0).getResNo() == 1 &&
9251         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9252          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9253          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9254          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9255          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9256          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9257       Inverted = true;
9258       Cond = Cond.getOperand(0);
9259     } else {
9260       SDValue NewCond = LowerSETCC(Cond, DAG);
9261       if (NewCond.getNode())
9262         Cond = NewCond;
9263     }
9264   }
9265 #if 0
9266   // FIXME: LowerXALUO doesn't handle these!!
9267   else if (Cond.getOpcode() == X86ISD::ADD  ||
9268            Cond.getOpcode() == X86ISD::SUB  ||
9269            Cond.getOpcode() == X86ISD::SMUL ||
9270            Cond.getOpcode() == X86ISD::UMUL)
9271     Cond = LowerXALUO(Cond, DAG);
9272 #endif
9273
9274   // Look pass (and (setcc_carry (cmp ...)), 1).
9275   if (Cond.getOpcode() == ISD::AND &&
9276       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9277     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9278     if (C && C->getAPIntValue() == 1)
9279       Cond = Cond.getOperand(0);
9280   }
9281
9282   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9283   // setting operand in place of the X86ISD::SETCC.
9284   unsigned CondOpcode = Cond.getOpcode();
9285   if (CondOpcode == X86ISD::SETCC ||
9286       CondOpcode == X86ISD::SETCC_CARRY) {
9287     CC = Cond.getOperand(0);
9288
9289     SDValue Cmp = Cond.getOperand(1);
9290     unsigned Opc = Cmp.getOpcode();
9291     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9292     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9293       Cond = Cmp;
9294       addTest = false;
9295     } else {
9296       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9297       default: break;
9298       case X86::COND_O:
9299       case X86::COND_B:
9300         // These can only come from an arithmetic instruction with overflow,
9301         // e.g. SADDO, UADDO.
9302         Cond = Cond.getNode()->getOperand(1);
9303         addTest = false;
9304         break;
9305       }
9306     }
9307   }
9308   CondOpcode = Cond.getOpcode();
9309   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9310       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9311       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9312        Cond.getOperand(0).getValueType() != MVT::i8)) {
9313     SDValue LHS = Cond.getOperand(0);
9314     SDValue RHS = Cond.getOperand(1);
9315     unsigned X86Opcode;
9316     unsigned X86Cond;
9317     SDVTList VTs;
9318     switch (CondOpcode) {
9319     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9320     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9321     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9322     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9323     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9324     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9325     default: llvm_unreachable("unexpected overflowing operator");
9326     }
9327     if (Inverted)
9328       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9329     if (CondOpcode == ISD::UMULO)
9330       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9331                           MVT::i32);
9332     else
9333       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9334
9335     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9336
9337     if (CondOpcode == ISD::UMULO)
9338       Cond = X86Op.getValue(2);
9339     else
9340       Cond = X86Op.getValue(1);
9341
9342     CC = DAG.getConstant(X86Cond, MVT::i8);
9343     addTest = false;
9344   } else {
9345     unsigned CondOpc;
9346     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9347       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9348       if (CondOpc == ISD::OR) {
9349         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9350         // two branches instead of an explicit OR instruction with a
9351         // separate test.
9352         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9353             isX86LogicalCmp(Cmp)) {
9354           CC = Cond.getOperand(0).getOperand(0);
9355           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9356                               Chain, Dest, CC, Cmp);
9357           CC = Cond.getOperand(1).getOperand(0);
9358           Cond = Cmp;
9359           addTest = false;
9360         }
9361       } else { // ISD::AND
9362         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9363         // two branches instead of an explicit AND instruction with a
9364         // separate test. However, we only do this if this block doesn't
9365         // have a fall-through edge, because this requires an explicit
9366         // jmp when the condition is false.
9367         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9368             isX86LogicalCmp(Cmp) &&
9369             Op.getNode()->hasOneUse()) {
9370           X86::CondCode CCode =
9371             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9372           CCode = X86::GetOppositeBranchCondition(CCode);
9373           CC = DAG.getConstant(CCode, MVT::i8);
9374           SDNode *User = *Op.getNode()->use_begin();
9375           // Look for an unconditional branch following this conditional branch.
9376           // We need this because we need to reverse the successors in order
9377           // to implement FCMP_OEQ.
9378           if (User->getOpcode() == ISD::BR) {
9379             SDValue FalseBB = User->getOperand(1);
9380             SDNode *NewBR =
9381               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9382             assert(NewBR == User);
9383             (void)NewBR;
9384             Dest = FalseBB;
9385
9386             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9387                                 Chain, Dest, CC, Cmp);
9388             X86::CondCode CCode =
9389               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9390             CCode = X86::GetOppositeBranchCondition(CCode);
9391             CC = DAG.getConstant(CCode, MVT::i8);
9392             Cond = Cmp;
9393             addTest = false;
9394           }
9395         }
9396       }
9397     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9398       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9399       // It should be transformed during dag combiner except when the condition
9400       // is set by a arithmetics with overflow node.
9401       X86::CondCode CCode =
9402         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9403       CCode = X86::GetOppositeBranchCondition(CCode);
9404       CC = DAG.getConstant(CCode, MVT::i8);
9405       Cond = Cond.getOperand(0).getOperand(1);
9406       addTest = false;
9407     } else if (Cond.getOpcode() == ISD::SETCC &&
9408                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9409       // For FCMP_OEQ, we can emit
9410       // two branches instead of an explicit AND instruction with a
9411       // separate test. However, we only do this if this block doesn't
9412       // have a fall-through edge, because this requires an explicit
9413       // jmp when the condition is false.
9414       if (Op.getNode()->hasOneUse()) {
9415         SDNode *User = *Op.getNode()->use_begin();
9416         // Look for an unconditional branch following this conditional branch.
9417         // We need this because we need to reverse the successors in order
9418         // to implement FCMP_OEQ.
9419         if (User->getOpcode() == ISD::BR) {
9420           SDValue FalseBB = User->getOperand(1);
9421           SDNode *NewBR =
9422             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9423           assert(NewBR == User);
9424           (void)NewBR;
9425           Dest = FalseBB;
9426
9427           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9428                                     Cond.getOperand(0), Cond.getOperand(1));
9429           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9430           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9431           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9432                               Chain, Dest, CC, Cmp);
9433           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9434           Cond = Cmp;
9435           addTest = false;
9436         }
9437       }
9438     } else if (Cond.getOpcode() == ISD::SETCC &&
9439                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9440       // For FCMP_UNE, we can emit
9441       // two branches instead of an explicit AND instruction with a
9442       // separate test. However, we only do this if this block doesn't
9443       // have a fall-through edge, because this requires an explicit
9444       // jmp when the condition is false.
9445       if (Op.getNode()->hasOneUse()) {
9446         SDNode *User = *Op.getNode()->use_begin();
9447         // Look for an unconditional branch following this conditional branch.
9448         // We need this because we need to reverse the successors in order
9449         // to implement FCMP_UNE.
9450         if (User->getOpcode() == ISD::BR) {
9451           SDValue FalseBB = User->getOperand(1);
9452           SDNode *NewBR =
9453             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9454           assert(NewBR == User);
9455           (void)NewBR;
9456
9457           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9458                                     Cond.getOperand(0), Cond.getOperand(1));
9459           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9460           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9461           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9462                               Chain, Dest, CC, Cmp);
9463           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9464           Cond = Cmp;
9465           addTest = false;
9466           Dest = FalseBB;
9467         }
9468       }
9469     }
9470   }
9471
9472   if (addTest) {
9473     // Look pass the truncate if the high bits are known zero.
9474     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9475         Cond = Cond.getOperand(0);
9476
9477     // We know the result of AND is compared against zero. Try to match
9478     // it to BT.
9479     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9480       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9481       if (NewSetCC.getNode()) {
9482         CC = NewSetCC.getOperand(0);
9483         Cond = NewSetCC.getOperand(1);
9484         addTest = false;
9485       }
9486     }
9487   }
9488
9489   if (addTest) {
9490     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9491     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9492   }
9493   Cond = ConvertCmpIfNecessary(Cond, DAG);
9494   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9495                      Chain, Dest, CC, Cond);
9496 }
9497
9498
9499 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9500 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9501 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9502 // that the guard pages used by the OS virtual memory manager are allocated in
9503 // correct sequence.
9504 SDValue
9505 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9506                                            SelectionDAG &DAG) const {
9507   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9508           getTargetMachine().Options.EnableSegmentedStacks) &&
9509          "This should be used only on Windows targets or when segmented stacks "
9510          "are being used");
9511   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9512   DebugLoc dl = Op.getDebugLoc();
9513
9514   // Get the inputs.
9515   SDValue Chain = Op.getOperand(0);
9516   SDValue Size  = Op.getOperand(1);
9517   // FIXME: Ensure alignment here
9518
9519   bool Is64Bit = Subtarget->is64Bit();
9520   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9521
9522   if (getTargetMachine().Options.EnableSegmentedStacks) {
9523     MachineFunction &MF = DAG.getMachineFunction();
9524     MachineRegisterInfo &MRI = MF.getRegInfo();
9525
9526     if (Is64Bit) {
9527       // The 64 bit implementation of segmented stacks needs to clobber both r10
9528       // r11. This makes it impossible to use it along with nested parameters.
9529       const Function *F = MF.getFunction();
9530
9531       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9532            I != E; ++I)
9533         if (I->hasNestAttr())
9534           report_fatal_error("Cannot use segmented stacks with functions that "
9535                              "have nested arguments.");
9536     }
9537
9538     const TargetRegisterClass *AddrRegClass =
9539       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9540     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9541     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9542     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9543                                 DAG.getRegister(Vreg, SPTy));
9544     SDValue Ops1[2] = { Value, Chain };
9545     return DAG.getMergeValues(Ops1, 2, dl);
9546   } else {
9547     SDValue Flag;
9548     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9549
9550     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9551     Flag = Chain.getValue(1);
9552     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9553
9554     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9555     Flag = Chain.getValue(1);
9556
9557     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9558
9559     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9560     return DAG.getMergeValues(Ops1, 2, dl);
9561   }
9562 }
9563
9564 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9565   MachineFunction &MF = DAG.getMachineFunction();
9566   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9567
9568   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9569   DebugLoc DL = Op.getDebugLoc();
9570
9571   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9572     // vastart just stores the address of the VarArgsFrameIndex slot into the
9573     // memory location argument.
9574     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9575                                    getPointerTy());
9576     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9577                         MachinePointerInfo(SV), false, false, 0);
9578   }
9579
9580   // __va_list_tag:
9581   //   gp_offset         (0 - 6 * 8)
9582   //   fp_offset         (48 - 48 + 8 * 16)
9583   //   overflow_arg_area (point to parameters coming in memory).
9584   //   reg_save_area
9585   SmallVector<SDValue, 8> MemOps;
9586   SDValue FIN = Op.getOperand(1);
9587   // Store gp_offset
9588   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9589                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9590                                                MVT::i32),
9591                                FIN, MachinePointerInfo(SV), false, false, 0);
9592   MemOps.push_back(Store);
9593
9594   // Store fp_offset
9595   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9596                     FIN, DAG.getIntPtrConstant(4));
9597   Store = DAG.getStore(Op.getOperand(0), DL,
9598                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9599                                        MVT::i32),
9600                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9601   MemOps.push_back(Store);
9602
9603   // Store ptr to overflow_arg_area
9604   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9605                     FIN, DAG.getIntPtrConstant(4));
9606   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9607                                     getPointerTy());
9608   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9609                        MachinePointerInfo(SV, 8),
9610                        false, false, 0);
9611   MemOps.push_back(Store);
9612
9613   // Store ptr to reg_save_area.
9614   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9615                     FIN, DAG.getIntPtrConstant(8));
9616   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9617                                     getPointerTy());
9618   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9619                        MachinePointerInfo(SV, 16), false, false, 0);
9620   MemOps.push_back(Store);
9621   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9622                      &MemOps[0], MemOps.size());
9623 }
9624
9625 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9626   assert(Subtarget->is64Bit() &&
9627          "LowerVAARG only handles 64-bit va_arg!");
9628   assert((Subtarget->isTargetLinux() ||
9629           Subtarget->isTargetDarwin()) &&
9630           "Unhandled target in LowerVAARG");
9631   assert(Op.getNode()->getNumOperands() == 4);
9632   SDValue Chain = Op.getOperand(0);
9633   SDValue SrcPtr = Op.getOperand(1);
9634   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9635   unsigned Align = Op.getConstantOperandVal(3);
9636   DebugLoc dl = Op.getDebugLoc();
9637
9638   EVT ArgVT = Op.getNode()->getValueType(0);
9639   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9640   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9641   uint8_t ArgMode;
9642
9643   // Decide which area this value should be read from.
9644   // TODO: Implement the AMD64 ABI in its entirety. This simple
9645   // selection mechanism works only for the basic types.
9646   if (ArgVT == MVT::f80) {
9647     llvm_unreachable("va_arg for f80 not yet implemented");
9648   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9649     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9650   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9651     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9652   } else {
9653     llvm_unreachable("Unhandled argument type in LowerVAARG");
9654   }
9655
9656   if (ArgMode == 2) {
9657     // Sanity Check: Make sure using fp_offset makes sense.
9658     assert(!getTargetMachine().Options.UseSoftFloat &&
9659            !(DAG.getMachineFunction()
9660                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9661            Subtarget->hasSSE1());
9662   }
9663
9664   // Insert VAARG_64 node into the DAG
9665   // VAARG_64 returns two values: Variable Argument Address, Chain
9666   SmallVector<SDValue, 11> InstOps;
9667   InstOps.push_back(Chain);
9668   InstOps.push_back(SrcPtr);
9669   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9670   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9671   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9672   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9673   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9674                                           VTs, &InstOps[0], InstOps.size(),
9675                                           MVT::i64,
9676                                           MachinePointerInfo(SV),
9677                                           /*Align=*/0,
9678                                           /*Volatile=*/false,
9679                                           /*ReadMem=*/true,
9680                                           /*WriteMem=*/true);
9681   Chain = VAARG.getValue(1);
9682
9683   // Load the next argument and return it
9684   return DAG.getLoad(ArgVT, dl,
9685                      Chain,
9686                      VAARG,
9687                      MachinePointerInfo(),
9688                      false, false, false, 0);
9689 }
9690
9691 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9692                            SelectionDAG &DAG) {
9693   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9694   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9695   SDValue Chain = Op.getOperand(0);
9696   SDValue DstPtr = Op.getOperand(1);
9697   SDValue SrcPtr = Op.getOperand(2);
9698   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9699   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9700   DebugLoc DL = Op.getDebugLoc();
9701
9702   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9703                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9704                        false,
9705                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9706 }
9707
9708 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9709 // may or may not be a constant. Takes immediate version of shift as input.
9710 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9711                                    SDValue SrcOp, SDValue ShAmt,
9712                                    SelectionDAG &DAG) {
9713   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9714
9715   if (isa<ConstantSDNode>(ShAmt)) {
9716     // Constant may be a TargetConstant. Use a regular constant.
9717     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9718     switch (Opc) {
9719       default: llvm_unreachable("Unknown target vector shift node");
9720       case X86ISD::VSHLI:
9721       case X86ISD::VSRLI:
9722       case X86ISD::VSRAI:
9723         return DAG.getNode(Opc, dl, VT, SrcOp,
9724                            DAG.getConstant(ShiftAmt, MVT::i32));
9725     }
9726   }
9727
9728   // Change opcode to non-immediate version
9729   switch (Opc) {
9730     default: llvm_unreachable("Unknown target vector shift node");
9731     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9732     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9733     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9734   }
9735
9736   // Need to build a vector containing shift amount
9737   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9738   SDValue ShOps[4];
9739   ShOps[0] = ShAmt;
9740   ShOps[1] = DAG.getConstant(0, MVT::i32);
9741   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9742   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9743
9744   // The return type has to be a 128-bit type with the same element
9745   // type as the input type.
9746   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9747   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9748
9749   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9750   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9751 }
9752
9753 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9754   DebugLoc dl = Op.getDebugLoc();
9755   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9756   switch (IntNo) {
9757   default: return SDValue();    // Don't custom lower most intrinsics.
9758   // Comparison intrinsics.
9759   case Intrinsic::x86_sse_comieq_ss:
9760   case Intrinsic::x86_sse_comilt_ss:
9761   case Intrinsic::x86_sse_comile_ss:
9762   case Intrinsic::x86_sse_comigt_ss:
9763   case Intrinsic::x86_sse_comige_ss:
9764   case Intrinsic::x86_sse_comineq_ss:
9765   case Intrinsic::x86_sse_ucomieq_ss:
9766   case Intrinsic::x86_sse_ucomilt_ss:
9767   case Intrinsic::x86_sse_ucomile_ss:
9768   case Intrinsic::x86_sse_ucomigt_ss:
9769   case Intrinsic::x86_sse_ucomige_ss:
9770   case Intrinsic::x86_sse_ucomineq_ss:
9771   case Intrinsic::x86_sse2_comieq_sd:
9772   case Intrinsic::x86_sse2_comilt_sd:
9773   case Intrinsic::x86_sse2_comile_sd:
9774   case Intrinsic::x86_sse2_comigt_sd:
9775   case Intrinsic::x86_sse2_comige_sd:
9776   case Intrinsic::x86_sse2_comineq_sd:
9777   case Intrinsic::x86_sse2_ucomieq_sd:
9778   case Intrinsic::x86_sse2_ucomilt_sd:
9779   case Intrinsic::x86_sse2_ucomile_sd:
9780   case Intrinsic::x86_sse2_ucomigt_sd:
9781   case Intrinsic::x86_sse2_ucomige_sd:
9782   case Intrinsic::x86_sse2_ucomineq_sd: {
9783     unsigned Opc;
9784     ISD::CondCode CC;
9785     switch (IntNo) {
9786     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9787     case Intrinsic::x86_sse_comieq_ss:
9788     case Intrinsic::x86_sse2_comieq_sd:
9789       Opc = X86ISD::COMI;
9790       CC = ISD::SETEQ;
9791       break;
9792     case Intrinsic::x86_sse_comilt_ss:
9793     case Intrinsic::x86_sse2_comilt_sd:
9794       Opc = X86ISD::COMI;
9795       CC = ISD::SETLT;
9796       break;
9797     case Intrinsic::x86_sse_comile_ss:
9798     case Intrinsic::x86_sse2_comile_sd:
9799       Opc = X86ISD::COMI;
9800       CC = ISD::SETLE;
9801       break;
9802     case Intrinsic::x86_sse_comigt_ss:
9803     case Intrinsic::x86_sse2_comigt_sd:
9804       Opc = X86ISD::COMI;
9805       CC = ISD::SETGT;
9806       break;
9807     case Intrinsic::x86_sse_comige_ss:
9808     case Intrinsic::x86_sse2_comige_sd:
9809       Opc = X86ISD::COMI;
9810       CC = ISD::SETGE;
9811       break;
9812     case Intrinsic::x86_sse_comineq_ss:
9813     case Intrinsic::x86_sse2_comineq_sd:
9814       Opc = X86ISD::COMI;
9815       CC = ISD::SETNE;
9816       break;
9817     case Intrinsic::x86_sse_ucomieq_ss:
9818     case Intrinsic::x86_sse2_ucomieq_sd:
9819       Opc = X86ISD::UCOMI;
9820       CC = ISD::SETEQ;
9821       break;
9822     case Intrinsic::x86_sse_ucomilt_ss:
9823     case Intrinsic::x86_sse2_ucomilt_sd:
9824       Opc = X86ISD::UCOMI;
9825       CC = ISD::SETLT;
9826       break;
9827     case Intrinsic::x86_sse_ucomile_ss:
9828     case Intrinsic::x86_sse2_ucomile_sd:
9829       Opc = X86ISD::UCOMI;
9830       CC = ISD::SETLE;
9831       break;
9832     case Intrinsic::x86_sse_ucomigt_ss:
9833     case Intrinsic::x86_sse2_ucomigt_sd:
9834       Opc = X86ISD::UCOMI;
9835       CC = ISD::SETGT;
9836       break;
9837     case Intrinsic::x86_sse_ucomige_ss:
9838     case Intrinsic::x86_sse2_ucomige_sd:
9839       Opc = X86ISD::UCOMI;
9840       CC = ISD::SETGE;
9841       break;
9842     case Intrinsic::x86_sse_ucomineq_ss:
9843     case Intrinsic::x86_sse2_ucomineq_sd:
9844       Opc = X86ISD::UCOMI;
9845       CC = ISD::SETNE;
9846       break;
9847     }
9848
9849     SDValue LHS = Op.getOperand(1);
9850     SDValue RHS = Op.getOperand(2);
9851     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9852     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9853     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9854     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9855                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9856     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9857   }
9858
9859   // Arithmetic intrinsics.
9860   case Intrinsic::x86_sse2_pmulu_dq:
9861   case Intrinsic::x86_avx2_pmulu_dq:
9862     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9863                        Op.getOperand(1), Op.getOperand(2));
9864
9865   // SSE3/AVX horizontal add/sub intrinsics
9866   case Intrinsic::x86_sse3_hadd_ps:
9867   case Intrinsic::x86_sse3_hadd_pd:
9868   case Intrinsic::x86_avx_hadd_ps_256:
9869   case Intrinsic::x86_avx_hadd_pd_256:
9870   case Intrinsic::x86_sse3_hsub_ps:
9871   case Intrinsic::x86_sse3_hsub_pd:
9872   case Intrinsic::x86_avx_hsub_ps_256:
9873   case Intrinsic::x86_avx_hsub_pd_256:
9874   case Intrinsic::x86_ssse3_phadd_w_128:
9875   case Intrinsic::x86_ssse3_phadd_d_128:
9876   case Intrinsic::x86_avx2_phadd_w:
9877   case Intrinsic::x86_avx2_phadd_d:
9878   case Intrinsic::x86_ssse3_phsub_w_128:
9879   case Intrinsic::x86_ssse3_phsub_d_128:
9880   case Intrinsic::x86_avx2_phsub_w:
9881   case Intrinsic::x86_avx2_phsub_d: {
9882     unsigned Opcode;
9883     switch (IntNo) {
9884     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9885     case Intrinsic::x86_sse3_hadd_ps:
9886     case Intrinsic::x86_sse3_hadd_pd:
9887     case Intrinsic::x86_avx_hadd_ps_256:
9888     case Intrinsic::x86_avx_hadd_pd_256:
9889       Opcode = X86ISD::FHADD;
9890       break;
9891     case Intrinsic::x86_sse3_hsub_ps:
9892     case Intrinsic::x86_sse3_hsub_pd:
9893     case Intrinsic::x86_avx_hsub_ps_256:
9894     case Intrinsic::x86_avx_hsub_pd_256:
9895       Opcode = X86ISD::FHSUB;
9896       break;
9897     case Intrinsic::x86_ssse3_phadd_w_128:
9898     case Intrinsic::x86_ssse3_phadd_d_128:
9899     case Intrinsic::x86_avx2_phadd_w:
9900     case Intrinsic::x86_avx2_phadd_d:
9901       Opcode = X86ISD::HADD;
9902       break;
9903     case Intrinsic::x86_ssse3_phsub_w_128:
9904     case Intrinsic::x86_ssse3_phsub_d_128:
9905     case Intrinsic::x86_avx2_phsub_w:
9906     case Intrinsic::x86_avx2_phsub_d:
9907       Opcode = X86ISD::HSUB;
9908       break;
9909     }
9910     return DAG.getNode(Opcode, dl, Op.getValueType(),
9911                        Op.getOperand(1), Op.getOperand(2));
9912   }
9913
9914   // AVX2 variable shift intrinsics
9915   case Intrinsic::x86_avx2_psllv_d:
9916   case Intrinsic::x86_avx2_psllv_q:
9917   case Intrinsic::x86_avx2_psllv_d_256:
9918   case Intrinsic::x86_avx2_psllv_q_256:
9919   case Intrinsic::x86_avx2_psrlv_d:
9920   case Intrinsic::x86_avx2_psrlv_q:
9921   case Intrinsic::x86_avx2_psrlv_d_256:
9922   case Intrinsic::x86_avx2_psrlv_q_256:
9923   case Intrinsic::x86_avx2_psrav_d:
9924   case Intrinsic::x86_avx2_psrav_d_256: {
9925     unsigned Opcode;
9926     switch (IntNo) {
9927     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9928     case Intrinsic::x86_avx2_psllv_d:
9929     case Intrinsic::x86_avx2_psllv_q:
9930     case Intrinsic::x86_avx2_psllv_d_256:
9931     case Intrinsic::x86_avx2_psllv_q_256:
9932       Opcode = ISD::SHL;
9933       break;
9934     case Intrinsic::x86_avx2_psrlv_d:
9935     case Intrinsic::x86_avx2_psrlv_q:
9936     case Intrinsic::x86_avx2_psrlv_d_256:
9937     case Intrinsic::x86_avx2_psrlv_q_256:
9938       Opcode = ISD::SRL;
9939       break;
9940     case Intrinsic::x86_avx2_psrav_d:
9941     case Intrinsic::x86_avx2_psrav_d_256:
9942       Opcode = ISD::SRA;
9943       break;
9944     }
9945     return DAG.getNode(Opcode, dl, Op.getValueType(),
9946                        Op.getOperand(1), Op.getOperand(2));
9947   }
9948
9949   case Intrinsic::x86_ssse3_pshuf_b_128:
9950   case Intrinsic::x86_avx2_pshuf_b:
9951     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9952                        Op.getOperand(1), Op.getOperand(2));
9953
9954   case Intrinsic::x86_ssse3_psign_b_128:
9955   case Intrinsic::x86_ssse3_psign_w_128:
9956   case Intrinsic::x86_ssse3_psign_d_128:
9957   case Intrinsic::x86_avx2_psign_b:
9958   case Intrinsic::x86_avx2_psign_w:
9959   case Intrinsic::x86_avx2_psign_d:
9960     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9961                        Op.getOperand(1), Op.getOperand(2));
9962
9963   case Intrinsic::x86_sse41_insertps:
9964     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9965                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9966
9967   case Intrinsic::x86_avx_vperm2f128_ps_256:
9968   case Intrinsic::x86_avx_vperm2f128_pd_256:
9969   case Intrinsic::x86_avx_vperm2f128_si_256:
9970   case Intrinsic::x86_avx2_vperm2i128:
9971     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9972                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9973
9974   case Intrinsic::x86_avx2_permd:
9975   case Intrinsic::x86_avx2_permps:
9976     // Operands intentionally swapped. Mask is last operand to intrinsic,
9977     // but second operand for node/intruction.
9978     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9979                        Op.getOperand(2), Op.getOperand(1));
9980
9981   // ptest and testp intrinsics. The intrinsic these come from are designed to
9982   // return an integer value, not just an instruction so lower it to the ptest
9983   // or testp pattern and a setcc for the result.
9984   case Intrinsic::x86_sse41_ptestz:
9985   case Intrinsic::x86_sse41_ptestc:
9986   case Intrinsic::x86_sse41_ptestnzc:
9987   case Intrinsic::x86_avx_ptestz_256:
9988   case Intrinsic::x86_avx_ptestc_256:
9989   case Intrinsic::x86_avx_ptestnzc_256:
9990   case Intrinsic::x86_avx_vtestz_ps:
9991   case Intrinsic::x86_avx_vtestc_ps:
9992   case Intrinsic::x86_avx_vtestnzc_ps:
9993   case Intrinsic::x86_avx_vtestz_pd:
9994   case Intrinsic::x86_avx_vtestc_pd:
9995   case Intrinsic::x86_avx_vtestnzc_pd:
9996   case Intrinsic::x86_avx_vtestz_ps_256:
9997   case Intrinsic::x86_avx_vtestc_ps_256:
9998   case Intrinsic::x86_avx_vtestnzc_ps_256:
9999   case Intrinsic::x86_avx_vtestz_pd_256:
10000   case Intrinsic::x86_avx_vtestc_pd_256:
10001   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10002     bool IsTestPacked = false;
10003     unsigned X86CC;
10004     switch (IntNo) {
10005     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10006     case Intrinsic::x86_avx_vtestz_ps:
10007     case Intrinsic::x86_avx_vtestz_pd:
10008     case Intrinsic::x86_avx_vtestz_ps_256:
10009     case Intrinsic::x86_avx_vtestz_pd_256:
10010       IsTestPacked = true; // Fallthrough
10011     case Intrinsic::x86_sse41_ptestz:
10012     case Intrinsic::x86_avx_ptestz_256:
10013       // ZF = 1
10014       X86CC = X86::COND_E;
10015       break;
10016     case Intrinsic::x86_avx_vtestc_ps:
10017     case Intrinsic::x86_avx_vtestc_pd:
10018     case Intrinsic::x86_avx_vtestc_ps_256:
10019     case Intrinsic::x86_avx_vtestc_pd_256:
10020       IsTestPacked = true; // Fallthrough
10021     case Intrinsic::x86_sse41_ptestc:
10022     case Intrinsic::x86_avx_ptestc_256:
10023       // CF = 1
10024       X86CC = X86::COND_B;
10025       break;
10026     case Intrinsic::x86_avx_vtestnzc_ps:
10027     case Intrinsic::x86_avx_vtestnzc_pd:
10028     case Intrinsic::x86_avx_vtestnzc_ps_256:
10029     case Intrinsic::x86_avx_vtestnzc_pd_256:
10030       IsTestPacked = true; // Fallthrough
10031     case Intrinsic::x86_sse41_ptestnzc:
10032     case Intrinsic::x86_avx_ptestnzc_256:
10033       // ZF and CF = 0
10034       X86CC = X86::COND_A;
10035       break;
10036     }
10037
10038     SDValue LHS = Op.getOperand(1);
10039     SDValue RHS = Op.getOperand(2);
10040     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10041     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10042     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10043     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10044     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10045   }
10046
10047   // SSE/AVX shift intrinsics
10048   case Intrinsic::x86_sse2_psll_w:
10049   case Intrinsic::x86_sse2_psll_d:
10050   case Intrinsic::x86_sse2_psll_q:
10051   case Intrinsic::x86_avx2_psll_w:
10052   case Intrinsic::x86_avx2_psll_d:
10053   case Intrinsic::x86_avx2_psll_q:
10054   case Intrinsic::x86_sse2_psrl_w:
10055   case Intrinsic::x86_sse2_psrl_d:
10056   case Intrinsic::x86_sse2_psrl_q:
10057   case Intrinsic::x86_avx2_psrl_w:
10058   case Intrinsic::x86_avx2_psrl_d:
10059   case Intrinsic::x86_avx2_psrl_q:
10060   case Intrinsic::x86_sse2_psra_w:
10061   case Intrinsic::x86_sse2_psra_d:
10062   case Intrinsic::x86_avx2_psra_w:
10063   case Intrinsic::x86_avx2_psra_d: {
10064     unsigned Opcode;
10065     switch (IntNo) {
10066     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10067     case Intrinsic::x86_sse2_psll_w:
10068     case Intrinsic::x86_sse2_psll_d:
10069     case Intrinsic::x86_sse2_psll_q:
10070     case Intrinsic::x86_avx2_psll_w:
10071     case Intrinsic::x86_avx2_psll_d:
10072     case Intrinsic::x86_avx2_psll_q:
10073       Opcode = X86ISD::VSHL;
10074       break;
10075     case Intrinsic::x86_sse2_psrl_w:
10076     case Intrinsic::x86_sse2_psrl_d:
10077     case Intrinsic::x86_sse2_psrl_q:
10078     case Intrinsic::x86_avx2_psrl_w:
10079     case Intrinsic::x86_avx2_psrl_d:
10080     case Intrinsic::x86_avx2_psrl_q:
10081       Opcode = X86ISD::VSRL;
10082       break;
10083     case Intrinsic::x86_sse2_psra_w:
10084     case Intrinsic::x86_sse2_psra_d:
10085     case Intrinsic::x86_avx2_psra_w:
10086     case Intrinsic::x86_avx2_psra_d:
10087       Opcode = X86ISD::VSRA;
10088       break;
10089     }
10090     return DAG.getNode(Opcode, dl, Op.getValueType(),
10091                        Op.getOperand(1), Op.getOperand(2));
10092   }
10093
10094   // SSE/AVX immediate shift intrinsics
10095   case Intrinsic::x86_sse2_pslli_w:
10096   case Intrinsic::x86_sse2_pslli_d:
10097   case Intrinsic::x86_sse2_pslli_q:
10098   case Intrinsic::x86_avx2_pslli_w:
10099   case Intrinsic::x86_avx2_pslli_d:
10100   case Intrinsic::x86_avx2_pslli_q:
10101   case Intrinsic::x86_sse2_psrli_w:
10102   case Intrinsic::x86_sse2_psrli_d:
10103   case Intrinsic::x86_sse2_psrli_q:
10104   case Intrinsic::x86_avx2_psrli_w:
10105   case Intrinsic::x86_avx2_psrli_d:
10106   case Intrinsic::x86_avx2_psrli_q:
10107   case Intrinsic::x86_sse2_psrai_w:
10108   case Intrinsic::x86_sse2_psrai_d:
10109   case Intrinsic::x86_avx2_psrai_w:
10110   case Intrinsic::x86_avx2_psrai_d: {
10111     unsigned Opcode;
10112     switch (IntNo) {
10113     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10114     case Intrinsic::x86_sse2_pslli_w:
10115     case Intrinsic::x86_sse2_pslli_d:
10116     case Intrinsic::x86_sse2_pslli_q:
10117     case Intrinsic::x86_avx2_pslli_w:
10118     case Intrinsic::x86_avx2_pslli_d:
10119     case Intrinsic::x86_avx2_pslli_q:
10120       Opcode = X86ISD::VSHLI;
10121       break;
10122     case Intrinsic::x86_sse2_psrli_w:
10123     case Intrinsic::x86_sse2_psrli_d:
10124     case Intrinsic::x86_sse2_psrli_q:
10125     case Intrinsic::x86_avx2_psrli_w:
10126     case Intrinsic::x86_avx2_psrli_d:
10127     case Intrinsic::x86_avx2_psrli_q:
10128       Opcode = X86ISD::VSRLI;
10129       break;
10130     case Intrinsic::x86_sse2_psrai_w:
10131     case Intrinsic::x86_sse2_psrai_d:
10132     case Intrinsic::x86_avx2_psrai_w:
10133     case Intrinsic::x86_avx2_psrai_d:
10134       Opcode = X86ISD::VSRAI;
10135       break;
10136     }
10137     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10138                                Op.getOperand(1), Op.getOperand(2), DAG);
10139   }
10140
10141   case Intrinsic::x86_sse42_pcmpistria128:
10142   case Intrinsic::x86_sse42_pcmpestria128:
10143   case Intrinsic::x86_sse42_pcmpistric128:
10144   case Intrinsic::x86_sse42_pcmpestric128:
10145   case Intrinsic::x86_sse42_pcmpistrio128:
10146   case Intrinsic::x86_sse42_pcmpestrio128:
10147   case Intrinsic::x86_sse42_pcmpistris128:
10148   case Intrinsic::x86_sse42_pcmpestris128:
10149   case Intrinsic::x86_sse42_pcmpistriz128:
10150   case Intrinsic::x86_sse42_pcmpestriz128: {
10151     unsigned Opcode;
10152     unsigned X86CC;
10153     switch (IntNo) {
10154     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10155     case Intrinsic::x86_sse42_pcmpistria128:
10156       Opcode = X86ISD::PCMPISTRI;
10157       X86CC = X86::COND_A;
10158       break;
10159     case Intrinsic::x86_sse42_pcmpestria128:
10160       Opcode = X86ISD::PCMPESTRI;
10161       X86CC = X86::COND_A;
10162       break;
10163     case Intrinsic::x86_sse42_pcmpistric128:
10164       Opcode = X86ISD::PCMPISTRI;
10165       X86CC = X86::COND_B;
10166       break;
10167     case Intrinsic::x86_sse42_pcmpestric128:
10168       Opcode = X86ISD::PCMPESTRI;
10169       X86CC = X86::COND_B;
10170       break;
10171     case Intrinsic::x86_sse42_pcmpistrio128:
10172       Opcode = X86ISD::PCMPISTRI;
10173       X86CC = X86::COND_O;
10174       break;
10175     case Intrinsic::x86_sse42_pcmpestrio128:
10176       Opcode = X86ISD::PCMPESTRI;
10177       X86CC = X86::COND_O;
10178       break;
10179     case Intrinsic::x86_sse42_pcmpistris128:
10180       Opcode = X86ISD::PCMPISTRI;
10181       X86CC = X86::COND_S;
10182       break;
10183     case Intrinsic::x86_sse42_pcmpestris128:
10184       Opcode = X86ISD::PCMPESTRI;
10185       X86CC = X86::COND_S;
10186       break;
10187     case Intrinsic::x86_sse42_pcmpistriz128:
10188       Opcode = X86ISD::PCMPISTRI;
10189       X86CC = X86::COND_E;
10190       break;
10191     case Intrinsic::x86_sse42_pcmpestriz128:
10192       Opcode = X86ISD::PCMPESTRI;
10193       X86CC = X86::COND_E;
10194       break;
10195     }
10196     SmallVector<SDValue, 5> NewOps;
10197     NewOps.append(Op->op_begin()+1, Op->op_end());
10198     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10199     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10200     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10201                                 DAG.getConstant(X86CC, MVT::i8),
10202                                 SDValue(PCMP.getNode(), 1));
10203     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10204   }
10205
10206   case Intrinsic::x86_sse42_pcmpistri128:
10207   case Intrinsic::x86_sse42_pcmpestri128: {
10208     unsigned Opcode;
10209     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10210       Opcode = X86ISD::PCMPISTRI;
10211     else
10212       Opcode = X86ISD::PCMPESTRI;
10213
10214     SmallVector<SDValue, 5> NewOps;
10215     NewOps.append(Op->op_begin()+1, Op->op_end());
10216     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10217     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10218   }
10219   case Intrinsic::x86_fma_vfmadd_ps:
10220   case Intrinsic::x86_fma_vfmadd_pd:
10221   case Intrinsic::x86_fma_vfmsub_ps:
10222   case Intrinsic::x86_fma_vfmsub_pd:
10223   case Intrinsic::x86_fma_vfnmadd_ps:
10224   case Intrinsic::x86_fma_vfnmadd_pd:
10225   case Intrinsic::x86_fma_vfnmsub_ps:
10226   case Intrinsic::x86_fma_vfnmsub_pd:
10227   case Intrinsic::x86_fma_vfmaddsub_ps:
10228   case Intrinsic::x86_fma_vfmaddsub_pd:
10229   case Intrinsic::x86_fma_vfmsubadd_ps:
10230   case Intrinsic::x86_fma_vfmsubadd_pd:
10231   case Intrinsic::x86_fma_vfmadd_ps_256:
10232   case Intrinsic::x86_fma_vfmadd_pd_256:
10233   case Intrinsic::x86_fma_vfmsub_ps_256:
10234   case Intrinsic::x86_fma_vfmsub_pd_256:
10235   case Intrinsic::x86_fma_vfnmadd_ps_256:
10236   case Intrinsic::x86_fma_vfnmadd_pd_256:
10237   case Intrinsic::x86_fma_vfnmsub_ps_256:
10238   case Intrinsic::x86_fma_vfnmsub_pd_256:
10239   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10240   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10241   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10242   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10243     unsigned Opc;
10244     switch (IntNo) {
10245     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10246     case Intrinsic::x86_fma_vfmadd_ps:
10247     case Intrinsic::x86_fma_vfmadd_pd:
10248     case Intrinsic::x86_fma_vfmadd_ps_256:
10249     case Intrinsic::x86_fma_vfmadd_pd_256:
10250       Opc = X86ISD::FMADD;
10251       break;
10252     case Intrinsic::x86_fma_vfmsub_ps:
10253     case Intrinsic::x86_fma_vfmsub_pd:
10254     case Intrinsic::x86_fma_vfmsub_ps_256:
10255     case Intrinsic::x86_fma_vfmsub_pd_256:
10256       Opc = X86ISD::FMSUB;
10257       break;
10258     case Intrinsic::x86_fma_vfnmadd_ps:
10259     case Intrinsic::x86_fma_vfnmadd_pd:
10260     case Intrinsic::x86_fma_vfnmadd_ps_256:
10261     case Intrinsic::x86_fma_vfnmadd_pd_256:
10262       Opc = X86ISD::FNMADD;
10263       break;
10264     case Intrinsic::x86_fma_vfnmsub_ps:
10265     case Intrinsic::x86_fma_vfnmsub_pd:
10266     case Intrinsic::x86_fma_vfnmsub_ps_256:
10267     case Intrinsic::x86_fma_vfnmsub_pd_256:
10268       Opc = X86ISD::FNMSUB;
10269       break;
10270     case Intrinsic::x86_fma_vfmaddsub_ps:
10271     case Intrinsic::x86_fma_vfmaddsub_pd:
10272     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10273     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10274       Opc = X86ISD::FMADDSUB;
10275       break;
10276     case Intrinsic::x86_fma_vfmsubadd_ps:
10277     case Intrinsic::x86_fma_vfmsubadd_pd:
10278     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10279     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10280       Opc = X86ISD::FMSUBADD;
10281       break;
10282     }
10283
10284     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10285                        Op.getOperand(2), Op.getOperand(3));
10286   }
10287   }
10288 }
10289
10290 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10291   DebugLoc dl = Op.getDebugLoc();
10292   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10293   switch (IntNo) {
10294   default: return SDValue();    // Don't custom lower most intrinsics.
10295
10296   // RDRAND intrinsics.
10297   case Intrinsic::x86_rdrand_16:
10298   case Intrinsic::x86_rdrand_32:
10299   case Intrinsic::x86_rdrand_64: {
10300     // Emit the node with the right value type.
10301     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10302     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10303
10304     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10305     // return the value from Rand, which is always 0, casted to i32.
10306     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10307                       DAG.getConstant(1, Op->getValueType(1)),
10308                       DAG.getConstant(X86::COND_B, MVT::i32),
10309                       SDValue(Result.getNode(), 1) };
10310     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10311                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10312                                   Ops, 4);
10313
10314     // Return { result, isValid, chain }.
10315     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10316                        SDValue(Result.getNode(), 2));
10317   }
10318   }
10319 }
10320
10321 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10322                                            SelectionDAG &DAG) const {
10323   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10324   MFI->setReturnAddressIsTaken(true);
10325
10326   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10327   DebugLoc dl = Op.getDebugLoc();
10328
10329   if (Depth > 0) {
10330     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10331     SDValue Offset =
10332       DAG.getConstant(TD->getPointerSize(),
10333                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10334     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10335                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10336                                    FrameAddr, Offset),
10337                        MachinePointerInfo(), false, false, false, 0);
10338   }
10339
10340   // Just load the return address.
10341   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10342   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10343                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10344 }
10345
10346 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10347   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10348   MFI->setFrameAddressIsTaken(true);
10349
10350   EVT VT = Op.getValueType();
10351   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10352   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10353   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10354   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10355   while (Depth--)
10356     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10357                             MachinePointerInfo(),
10358                             false, false, false, 0);
10359   return FrameAddr;
10360 }
10361
10362 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10363                                                      SelectionDAG &DAG) const {
10364   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10365 }
10366
10367 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10368   SDValue Chain     = Op.getOperand(0);
10369   SDValue Offset    = Op.getOperand(1);
10370   SDValue Handler   = Op.getOperand(2);
10371   DebugLoc dl       = Op.getDebugLoc();
10372
10373   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10374                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10375                                      getPointerTy());
10376   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10377
10378   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10379                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10380   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10381   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10382                        false, false, 0);
10383   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10384
10385   return DAG.getNode(X86ISD::EH_RETURN, dl,
10386                      MVT::Other,
10387                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10388 }
10389
10390 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10391   return Op.getOperand(0);
10392 }
10393
10394 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10395                                                 SelectionDAG &DAG) const {
10396   SDValue Root = Op.getOperand(0);
10397   SDValue Trmp = Op.getOperand(1); // trampoline
10398   SDValue FPtr = Op.getOperand(2); // nested function
10399   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10400   DebugLoc dl  = Op.getDebugLoc();
10401
10402   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10403
10404   if (Subtarget->is64Bit()) {
10405     SDValue OutChains[6];
10406
10407     // Large code-model.
10408     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10409     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10410
10411     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10412     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10413
10414     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10415
10416     // Load the pointer to the nested function into R11.
10417     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10418     SDValue Addr = Trmp;
10419     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10420                                 Addr, MachinePointerInfo(TrmpAddr),
10421                                 false, false, 0);
10422
10423     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10424                        DAG.getConstant(2, MVT::i64));
10425     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10426                                 MachinePointerInfo(TrmpAddr, 2),
10427                                 false, false, 2);
10428
10429     // Load the 'nest' parameter value into R10.
10430     // R10 is specified in X86CallingConv.td
10431     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10432     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10433                        DAG.getConstant(10, MVT::i64));
10434     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10435                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10436                                 false, false, 0);
10437
10438     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10439                        DAG.getConstant(12, MVT::i64));
10440     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10441                                 MachinePointerInfo(TrmpAddr, 12),
10442                                 false, false, 2);
10443
10444     // Jump to the nested function.
10445     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10446     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10447                        DAG.getConstant(20, MVT::i64));
10448     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10449                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10450                                 false, false, 0);
10451
10452     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10454                        DAG.getConstant(22, MVT::i64));
10455     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10456                                 MachinePointerInfo(TrmpAddr, 22),
10457                                 false, false, 0);
10458
10459     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10460   } else {
10461     const Function *Func =
10462       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10463     CallingConv::ID CC = Func->getCallingConv();
10464     unsigned NestReg;
10465
10466     switch (CC) {
10467     default:
10468       llvm_unreachable("Unsupported calling convention");
10469     case CallingConv::C:
10470     case CallingConv::X86_StdCall: {
10471       // Pass 'nest' parameter in ECX.
10472       // Must be kept in sync with X86CallingConv.td
10473       NestReg = X86::ECX;
10474
10475       // Check that ECX wasn't needed by an 'inreg' parameter.
10476       FunctionType *FTy = Func->getFunctionType();
10477       const AttrListPtr &Attrs = Func->getAttributes();
10478
10479       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10480         unsigned InRegCount = 0;
10481         unsigned Idx = 1;
10482
10483         for (FunctionType::param_iterator I = FTy->param_begin(),
10484              E = FTy->param_end(); I != E; ++I, ++Idx)
10485           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10486             // FIXME: should only count parameters that are lowered to integers.
10487             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10488
10489         if (InRegCount > 2) {
10490           report_fatal_error("Nest register in use - reduce number of inreg"
10491                              " parameters!");
10492         }
10493       }
10494       break;
10495     }
10496     case CallingConv::X86_FastCall:
10497     case CallingConv::X86_ThisCall:
10498     case CallingConv::Fast:
10499       // Pass 'nest' parameter in EAX.
10500       // Must be kept in sync with X86CallingConv.td
10501       NestReg = X86::EAX;
10502       break;
10503     }
10504
10505     SDValue OutChains[4];
10506     SDValue Addr, Disp;
10507
10508     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10509                        DAG.getConstant(10, MVT::i32));
10510     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10511
10512     // This is storing the opcode for MOV32ri.
10513     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10514     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10515     OutChains[0] = DAG.getStore(Root, dl,
10516                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10517                                 Trmp, MachinePointerInfo(TrmpAddr),
10518                                 false, false, 0);
10519
10520     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10521                        DAG.getConstant(1, MVT::i32));
10522     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10523                                 MachinePointerInfo(TrmpAddr, 1),
10524                                 false, false, 1);
10525
10526     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10527     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10528                        DAG.getConstant(5, MVT::i32));
10529     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10530                                 MachinePointerInfo(TrmpAddr, 5),
10531                                 false, false, 1);
10532
10533     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10534                        DAG.getConstant(6, MVT::i32));
10535     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10536                                 MachinePointerInfo(TrmpAddr, 6),
10537                                 false, false, 1);
10538
10539     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10540   }
10541 }
10542
10543 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10544                                             SelectionDAG &DAG) const {
10545   /*
10546    The rounding mode is in bits 11:10 of FPSR, and has the following
10547    settings:
10548      00 Round to nearest
10549      01 Round to -inf
10550      10 Round to +inf
10551      11 Round to 0
10552
10553   FLT_ROUNDS, on the other hand, expects the following:
10554     -1 Undefined
10555      0 Round to 0
10556      1 Round to nearest
10557      2 Round to +inf
10558      3 Round to -inf
10559
10560   To perform the conversion, we do:
10561     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10562   */
10563
10564   MachineFunction &MF = DAG.getMachineFunction();
10565   const TargetMachine &TM = MF.getTarget();
10566   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10567   unsigned StackAlignment = TFI.getStackAlignment();
10568   EVT VT = Op.getValueType();
10569   DebugLoc DL = Op.getDebugLoc();
10570
10571   // Save FP Control Word to stack slot
10572   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10573   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10574
10575
10576   MachineMemOperand *MMO =
10577    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10578                            MachineMemOperand::MOStore, 2, 2);
10579
10580   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10581   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10582                                           DAG.getVTList(MVT::Other),
10583                                           Ops, 2, MVT::i16, MMO);
10584
10585   // Load FP Control Word from stack slot
10586   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10587                             MachinePointerInfo(), false, false, false, 0);
10588
10589   // Transform as necessary
10590   SDValue CWD1 =
10591     DAG.getNode(ISD::SRL, DL, MVT::i16,
10592                 DAG.getNode(ISD::AND, DL, MVT::i16,
10593                             CWD, DAG.getConstant(0x800, MVT::i16)),
10594                 DAG.getConstant(11, MVT::i8));
10595   SDValue CWD2 =
10596     DAG.getNode(ISD::SRL, DL, MVT::i16,
10597                 DAG.getNode(ISD::AND, DL, MVT::i16,
10598                             CWD, DAG.getConstant(0x400, MVT::i16)),
10599                 DAG.getConstant(9, MVT::i8));
10600
10601   SDValue RetVal =
10602     DAG.getNode(ISD::AND, DL, MVT::i16,
10603                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10604                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10605                             DAG.getConstant(1, MVT::i16)),
10606                 DAG.getConstant(3, MVT::i16));
10607
10608
10609   return DAG.getNode((VT.getSizeInBits() < 16 ?
10610                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10611 }
10612
10613 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10614   EVT VT = Op.getValueType();
10615   EVT OpVT = VT;
10616   unsigned NumBits = VT.getSizeInBits();
10617   DebugLoc dl = Op.getDebugLoc();
10618
10619   Op = Op.getOperand(0);
10620   if (VT == MVT::i8) {
10621     // Zero extend to i32 since there is not an i8 bsr.
10622     OpVT = MVT::i32;
10623     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10624   }
10625
10626   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10627   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10628   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10629
10630   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10631   SDValue Ops[] = {
10632     Op,
10633     DAG.getConstant(NumBits+NumBits-1, OpVT),
10634     DAG.getConstant(X86::COND_E, MVT::i8),
10635     Op.getValue(1)
10636   };
10637   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10638
10639   // Finally xor with NumBits-1.
10640   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10641
10642   if (VT == MVT::i8)
10643     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10644   return Op;
10645 }
10646
10647 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10648   EVT VT = Op.getValueType();
10649   EVT OpVT = VT;
10650   unsigned NumBits = VT.getSizeInBits();
10651   DebugLoc dl = Op.getDebugLoc();
10652
10653   Op = Op.getOperand(0);
10654   if (VT == MVT::i8) {
10655     // Zero extend to i32 since there is not an i8 bsr.
10656     OpVT = MVT::i32;
10657     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10658   }
10659
10660   // Issue a bsr (scan bits in reverse).
10661   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10662   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10663
10664   // And xor with NumBits-1.
10665   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10666
10667   if (VT == MVT::i8)
10668     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10669   return Op;
10670 }
10671
10672 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10673   EVT VT = Op.getValueType();
10674   unsigned NumBits = VT.getSizeInBits();
10675   DebugLoc dl = Op.getDebugLoc();
10676   Op = Op.getOperand(0);
10677
10678   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10679   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10680   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10681
10682   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10683   SDValue Ops[] = {
10684     Op,
10685     DAG.getConstant(NumBits, VT),
10686     DAG.getConstant(X86::COND_E, MVT::i8),
10687     Op.getValue(1)
10688   };
10689   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10690 }
10691
10692 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10693 // ones, and then concatenate the result back.
10694 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10695   EVT VT = Op.getValueType();
10696
10697   assert(VT.is256BitVector() && VT.isInteger() &&
10698          "Unsupported value type for operation");
10699
10700   unsigned NumElems = VT.getVectorNumElements();
10701   DebugLoc dl = Op.getDebugLoc();
10702
10703   // Extract the LHS vectors
10704   SDValue LHS = Op.getOperand(0);
10705   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10706   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10707
10708   // Extract the RHS vectors
10709   SDValue RHS = Op.getOperand(1);
10710   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10711   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10712
10713   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10714   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10715
10716   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10717                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10718                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10719 }
10720
10721 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10722   assert(Op.getValueType().is256BitVector() &&
10723          Op.getValueType().isInteger() &&
10724          "Only handle AVX 256-bit vector integer operation");
10725   return Lower256IntArith(Op, DAG);
10726 }
10727
10728 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10729   assert(Op.getValueType().is256BitVector() &&
10730          Op.getValueType().isInteger() &&
10731          "Only handle AVX 256-bit vector integer operation");
10732   return Lower256IntArith(Op, DAG);
10733 }
10734
10735 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10736                         SelectionDAG &DAG) {
10737   EVT VT = Op.getValueType();
10738
10739   // Decompose 256-bit ops into smaller 128-bit ops.
10740   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10741     return Lower256IntArith(Op, DAG);
10742
10743   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10744          "Only know how to lower V2I64/V4I64 multiply");
10745
10746   DebugLoc dl = Op.getDebugLoc();
10747
10748   //  Ahi = psrlqi(a, 32);
10749   //  Bhi = psrlqi(b, 32);
10750   //
10751   //  AloBlo = pmuludq(a, b);
10752   //  AloBhi = pmuludq(a, Bhi);
10753   //  AhiBlo = pmuludq(Ahi, b);
10754
10755   //  AloBhi = psllqi(AloBhi, 32);
10756   //  AhiBlo = psllqi(AhiBlo, 32);
10757   //  return AloBlo + AloBhi + AhiBlo;
10758
10759   SDValue A = Op.getOperand(0);
10760   SDValue B = Op.getOperand(1);
10761
10762   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10763
10764   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10765   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10766
10767   // Bit cast to 32-bit vectors for MULUDQ
10768   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10769   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10770   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10771   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10772   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10773
10774   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10775   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10776   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10777
10778   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10779   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10780
10781   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10782   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10783 }
10784
10785 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10786
10787   EVT VT = Op.getValueType();
10788   DebugLoc dl = Op.getDebugLoc();
10789   SDValue R = Op.getOperand(0);
10790   SDValue Amt = Op.getOperand(1);
10791   LLVMContext *Context = DAG.getContext();
10792
10793   if (!Subtarget->hasSSE2())
10794     return SDValue();
10795
10796   // Optimize shl/srl/sra with constant shift amount.
10797   if (isSplatVector(Amt.getNode())) {
10798     SDValue SclrAmt = Amt->getOperand(0);
10799     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10800       uint64_t ShiftAmt = C->getZExtValue();
10801
10802       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10803           (Subtarget->hasAVX2() &&
10804            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10805         if (Op.getOpcode() == ISD::SHL)
10806           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10807                              DAG.getConstant(ShiftAmt, MVT::i32));
10808         if (Op.getOpcode() == ISD::SRL)
10809           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10810                              DAG.getConstant(ShiftAmt, MVT::i32));
10811         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10812           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10813                              DAG.getConstant(ShiftAmt, MVT::i32));
10814       }
10815
10816       if (VT == MVT::v16i8) {
10817         if (Op.getOpcode() == ISD::SHL) {
10818           // Make a large shift.
10819           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10820                                     DAG.getConstant(ShiftAmt, MVT::i32));
10821           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10822           // Zero out the rightmost bits.
10823           SmallVector<SDValue, 16> V(16,
10824                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10825                                                      MVT::i8));
10826           return DAG.getNode(ISD::AND, dl, VT, SHL,
10827                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10828         }
10829         if (Op.getOpcode() == ISD::SRL) {
10830           // Make a large shift.
10831           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10832                                     DAG.getConstant(ShiftAmt, MVT::i32));
10833           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10834           // Zero out the leftmost bits.
10835           SmallVector<SDValue, 16> V(16,
10836                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10837                                                      MVT::i8));
10838           return DAG.getNode(ISD::AND, dl, VT, SRL,
10839                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10840         }
10841         if (Op.getOpcode() == ISD::SRA) {
10842           if (ShiftAmt == 7) {
10843             // R s>> 7  ===  R s< 0
10844             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10845             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10846           }
10847
10848           // R s>> a === ((R u>> a) ^ m) - m
10849           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10850           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10851                                                          MVT::i8));
10852           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10853           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10854           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10855           return Res;
10856         }
10857         llvm_unreachable("Unknown shift opcode.");
10858       }
10859
10860       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10861         if (Op.getOpcode() == ISD::SHL) {
10862           // Make a large shift.
10863           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10864                                     DAG.getConstant(ShiftAmt, MVT::i32));
10865           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10866           // Zero out the rightmost bits.
10867           SmallVector<SDValue, 32> V(32,
10868                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10869                                                      MVT::i8));
10870           return DAG.getNode(ISD::AND, dl, VT, SHL,
10871                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10872         }
10873         if (Op.getOpcode() == ISD::SRL) {
10874           // Make a large shift.
10875           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10876                                     DAG.getConstant(ShiftAmt, MVT::i32));
10877           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10878           // Zero out the leftmost bits.
10879           SmallVector<SDValue, 32> V(32,
10880                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10881                                                      MVT::i8));
10882           return DAG.getNode(ISD::AND, dl, VT, SRL,
10883                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10884         }
10885         if (Op.getOpcode() == ISD::SRA) {
10886           if (ShiftAmt == 7) {
10887             // R s>> 7  ===  R s< 0
10888             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10889             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10890           }
10891
10892           // R s>> a === ((R u>> a) ^ m) - m
10893           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10894           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10895                                                          MVT::i8));
10896           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10897           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10898           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10899           return Res;
10900         }
10901         llvm_unreachable("Unknown shift opcode.");
10902       }
10903     }
10904   }
10905
10906   // Lower SHL with variable shift amount.
10907   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10908     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10909                      DAG.getConstant(23, MVT::i32));
10910
10911     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10912     Constant *C = ConstantDataVector::get(*Context, CV);
10913     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10914     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10915                                  MachinePointerInfo::getConstantPool(),
10916                                  false, false, false, 16);
10917
10918     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10919     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10920     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10921     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10922   }
10923   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10924     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10925
10926     // a = a << 5;
10927     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10928                      DAG.getConstant(5, MVT::i32));
10929     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10930
10931     // Turn 'a' into a mask suitable for VSELECT
10932     SDValue VSelM = DAG.getConstant(0x80, VT);
10933     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10934     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10935
10936     SDValue CM1 = DAG.getConstant(0x0f, VT);
10937     SDValue CM2 = DAG.getConstant(0x3f, VT);
10938
10939     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10940     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10941     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10942                             DAG.getConstant(4, MVT::i32), DAG);
10943     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10944     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10945
10946     // a += a
10947     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10948     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10949     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10950
10951     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10952     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10953     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10954                             DAG.getConstant(2, MVT::i32), DAG);
10955     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10956     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10957
10958     // a += a
10959     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10960     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10961     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10962
10963     // return VSELECT(r, r+r, a);
10964     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10965                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10966     return R;
10967   }
10968
10969   // Decompose 256-bit shifts into smaller 128-bit shifts.
10970   if (VT.is256BitVector()) {
10971     unsigned NumElems = VT.getVectorNumElements();
10972     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10973     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10974
10975     // Extract the two vectors
10976     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10977     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10978
10979     // Recreate the shift amount vectors
10980     SDValue Amt1, Amt2;
10981     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10982       // Constant shift amount
10983       SmallVector<SDValue, 4> Amt1Csts;
10984       SmallVector<SDValue, 4> Amt2Csts;
10985       for (unsigned i = 0; i != NumElems/2; ++i)
10986         Amt1Csts.push_back(Amt->getOperand(i));
10987       for (unsigned i = NumElems/2; i != NumElems; ++i)
10988         Amt2Csts.push_back(Amt->getOperand(i));
10989
10990       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10991                                  &Amt1Csts[0], NumElems/2);
10992       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10993                                  &Amt2Csts[0], NumElems/2);
10994     } else {
10995       // Variable shift amount
10996       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10997       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10998     }
10999
11000     // Issue new vector shifts for the smaller types
11001     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11002     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11003
11004     // Concatenate the result back
11005     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11006   }
11007
11008   return SDValue();
11009 }
11010
11011 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11012   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11013   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11014   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11015   // has only one use.
11016   SDNode *N = Op.getNode();
11017   SDValue LHS = N->getOperand(0);
11018   SDValue RHS = N->getOperand(1);
11019   unsigned BaseOp = 0;
11020   unsigned Cond = 0;
11021   DebugLoc DL = Op.getDebugLoc();
11022   switch (Op.getOpcode()) {
11023   default: llvm_unreachable("Unknown ovf instruction!");
11024   case ISD::SADDO:
11025     // A subtract of one will be selected as a INC. Note that INC doesn't
11026     // set CF, so we can't do this for UADDO.
11027     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11028       if (C->isOne()) {
11029         BaseOp = X86ISD::INC;
11030         Cond = X86::COND_O;
11031         break;
11032       }
11033     BaseOp = X86ISD::ADD;
11034     Cond = X86::COND_O;
11035     break;
11036   case ISD::UADDO:
11037     BaseOp = X86ISD::ADD;
11038     Cond = X86::COND_B;
11039     break;
11040   case ISD::SSUBO:
11041     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11042     // set CF, so we can't do this for USUBO.
11043     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11044       if (C->isOne()) {
11045         BaseOp = X86ISD::DEC;
11046         Cond = X86::COND_O;
11047         break;
11048       }
11049     BaseOp = X86ISD::SUB;
11050     Cond = X86::COND_O;
11051     break;
11052   case ISD::USUBO:
11053     BaseOp = X86ISD::SUB;
11054     Cond = X86::COND_B;
11055     break;
11056   case ISD::SMULO:
11057     BaseOp = X86ISD::SMUL;
11058     Cond = X86::COND_O;
11059     break;
11060   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11061     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11062                                  MVT::i32);
11063     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11064
11065     SDValue SetCC =
11066       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11067                   DAG.getConstant(X86::COND_O, MVT::i32),
11068                   SDValue(Sum.getNode(), 2));
11069
11070     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11071   }
11072   }
11073
11074   // Also sets EFLAGS.
11075   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11076   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11077
11078   SDValue SetCC =
11079     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11080                 DAG.getConstant(Cond, MVT::i32),
11081                 SDValue(Sum.getNode(), 1));
11082
11083   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11084 }
11085
11086 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11087                                                   SelectionDAG &DAG) const {
11088   DebugLoc dl = Op.getDebugLoc();
11089   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11090   EVT VT = Op.getValueType();
11091
11092   if (!Subtarget->hasSSE2() || !VT.isVector())
11093     return SDValue();
11094
11095   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11096                       ExtraVT.getScalarType().getSizeInBits();
11097   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11098
11099   switch (VT.getSimpleVT().SimpleTy) {
11100     default: return SDValue();
11101     case MVT::v8i32:
11102     case MVT::v16i16:
11103       if (!Subtarget->hasAVX())
11104         return SDValue();
11105       if (!Subtarget->hasAVX2()) {
11106         // needs to be split
11107         unsigned NumElems = VT.getVectorNumElements();
11108
11109         // Extract the LHS vectors
11110         SDValue LHS = Op.getOperand(0);
11111         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11112         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11113
11114         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11115         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11116
11117         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11118         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11119         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11120                                    ExtraNumElems/2);
11121         SDValue Extra = DAG.getValueType(ExtraVT);
11122
11123         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11124         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11125
11126         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11127       }
11128       // fall through
11129     case MVT::v4i32:
11130     case MVT::v8i16: {
11131       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11132                                          Op.getOperand(0), ShAmt, DAG);
11133       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11134     }
11135   }
11136 }
11137
11138
11139 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11140                               SelectionDAG &DAG) {
11141   DebugLoc dl = Op.getDebugLoc();
11142
11143   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11144   // There isn't any reason to disable it if the target processor supports it.
11145   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11146     SDValue Chain = Op.getOperand(0);
11147     SDValue Zero = DAG.getConstant(0, MVT::i32);
11148     SDValue Ops[] = {
11149       DAG.getRegister(X86::ESP, MVT::i32), // Base
11150       DAG.getTargetConstant(1, MVT::i8),   // Scale
11151       DAG.getRegister(0, MVT::i32),        // Index
11152       DAG.getTargetConstant(0, MVT::i32),  // Disp
11153       DAG.getRegister(0, MVT::i32),        // Segment.
11154       Zero,
11155       Chain
11156     };
11157     SDNode *Res =
11158       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11159                           array_lengthof(Ops));
11160     return SDValue(Res, 0);
11161   }
11162
11163   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11164   if (!isDev)
11165     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11166
11167   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11168   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11169   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11170   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11171
11172   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11173   if (!Op1 && !Op2 && !Op3 && Op4)
11174     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11175
11176   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11177   if (Op1 && !Op2 && !Op3 && !Op4)
11178     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11179
11180   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11181   //           (MFENCE)>;
11182   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11183 }
11184
11185 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11186                                  SelectionDAG &DAG) {
11187   DebugLoc dl = Op.getDebugLoc();
11188   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11189     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11190   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11191     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11192
11193   // The only fence that needs an instruction is a sequentially-consistent
11194   // cross-thread fence.
11195   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11196     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11197     // no-sse2). There isn't any reason to disable it if the target processor
11198     // supports it.
11199     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11200       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11201
11202     SDValue Chain = Op.getOperand(0);
11203     SDValue Zero = DAG.getConstant(0, MVT::i32);
11204     SDValue Ops[] = {
11205       DAG.getRegister(X86::ESP, MVT::i32), // Base
11206       DAG.getTargetConstant(1, MVT::i8),   // Scale
11207       DAG.getRegister(0, MVT::i32),        // Index
11208       DAG.getTargetConstant(0, MVT::i32),  // Disp
11209       DAG.getRegister(0, MVT::i32),        // Segment.
11210       Zero,
11211       Chain
11212     };
11213     SDNode *Res =
11214       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11215                          array_lengthof(Ops));
11216     return SDValue(Res, 0);
11217   }
11218
11219   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11220   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11221 }
11222
11223
11224 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11225                              SelectionDAG &DAG) {
11226   EVT T = Op.getValueType();
11227   DebugLoc DL = Op.getDebugLoc();
11228   unsigned Reg = 0;
11229   unsigned size = 0;
11230   switch(T.getSimpleVT().SimpleTy) {
11231   default: llvm_unreachable("Invalid value type!");
11232   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11233   case MVT::i16: Reg = X86::AX;  size = 2; break;
11234   case MVT::i32: Reg = X86::EAX; size = 4; break;
11235   case MVT::i64:
11236     assert(Subtarget->is64Bit() && "Node not type legal!");
11237     Reg = X86::RAX; size = 8;
11238     break;
11239   }
11240   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11241                                     Op.getOperand(2), SDValue());
11242   SDValue Ops[] = { cpIn.getValue(0),
11243                     Op.getOperand(1),
11244                     Op.getOperand(3),
11245                     DAG.getTargetConstant(size, MVT::i8),
11246                     cpIn.getValue(1) };
11247   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11248   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11249   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11250                                            Ops, 5, T, MMO);
11251   SDValue cpOut =
11252     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11253   return cpOut;
11254 }
11255
11256 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11257                                      SelectionDAG &DAG) {
11258   assert(Subtarget->is64Bit() && "Result not type legalized?");
11259   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11260   SDValue TheChain = Op.getOperand(0);
11261   DebugLoc dl = Op.getDebugLoc();
11262   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11263   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11264   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11265                                    rax.getValue(2));
11266   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11267                             DAG.getConstant(32, MVT::i8));
11268   SDValue Ops[] = {
11269     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11270     rdx.getValue(1)
11271   };
11272   return DAG.getMergeValues(Ops, 2, dl);
11273 }
11274
11275 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11276   EVT SrcVT = Op.getOperand(0).getValueType();
11277   EVT DstVT = Op.getValueType();
11278   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11279          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11280   assert((DstVT == MVT::i64 ||
11281           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11282          "Unexpected custom BITCAST");
11283   // i64 <=> MMX conversions are Legal.
11284   if (SrcVT==MVT::i64 && DstVT.isVector())
11285     return Op;
11286   if (DstVT==MVT::i64 && SrcVT.isVector())
11287     return Op;
11288   // MMX <=> MMX conversions are Legal.
11289   if (SrcVT.isVector() && DstVT.isVector())
11290     return Op;
11291   // All other conversions need to be expanded.
11292   return SDValue();
11293 }
11294
11295 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11296   SDNode *Node = Op.getNode();
11297   DebugLoc dl = Node->getDebugLoc();
11298   EVT T = Node->getValueType(0);
11299   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11300                               DAG.getConstant(0, T), Node->getOperand(2));
11301   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11302                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11303                        Node->getOperand(0),
11304                        Node->getOperand(1), negOp,
11305                        cast<AtomicSDNode>(Node)->getSrcValue(),
11306                        cast<AtomicSDNode>(Node)->getAlignment(),
11307                        cast<AtomicSDNode>(Node)->getOrdering(),
11308                        cast<AtomicSDNode>(Node)->getSynchScope());
11309 }
11310
11311 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11312   SDNode *Node = Op.getNode();
11313   DebugLoc dl = Node->getDebugLoc();
11314   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11315
11316   // Convert seq_cst store -> xchg
11317   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11318   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11319   //        (The only way to get a 16-byte store is cmpxchg16b)
11320   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11321   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11322       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11323     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11324                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11325                                  Node->getOperand(0),
11326                                  Node->getOperand(1), Node->getOperand(2),
11327                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11328                                  cast<AtomicSDNode>(Node)->getOrdering(),
11329                                  cast<AtomicSDNode>(Node)->getSynchScope());
11330     return Swap.getValue(1);
11331   }
11332   // Other atomic stores have a simple pattern.
11333   return Op;
11334 }
11335
11336 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11337   EVT VT = Op.getNode()->getValueType(0);
11338
11339   // Let legalize expand this if it isn't a legal type yet.
11340   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11341     return SDValue();
11342
11343   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11344
11345   unsigned Opc;
11346   bool ExtraOp = false;
11347   switch (Op.getOpcode()) {
11348   default: llvm_unreachable("Invalid code");
11349   case ISD::ADDC: Opc = X86ISD::ADD; break;
11350   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11351   case ISD::SUBC: Opc = X86ISD::SUB; break;
11352   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11353   }
11354
11355   if (!ExtraOp)
11356     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11357                        Op.getOperand(1));
11358   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11359                      Op.getOperand(1), Op.getOperand(2));
11360 }
11361
11362 /// LowerOperation - Provide custom lowering hooks for some operations.
11363 ///
11364 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11365   switch (Op.getOpcode()) {
11366   default: llvm_unreachable("Should not custom lower this!");
11367   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11368   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11369   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11370   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11371   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11372   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11373   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11374   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11375   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11376   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11377   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11378   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11379   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11380   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11381   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11382   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11383   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11384   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11385   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11386   case ISD::SHL_PARTS:
11387   case ISD::SRA_PARTS:
11388   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11389   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11390   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11391   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11392   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11393   case ISD::FABS:               return LowerFABS(Op, DAG);
11394   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11395   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11396   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11397   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11398   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11399   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11400   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11401   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11402   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11403   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11404   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11405   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11406   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11407   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11408   case ISD::FRAME_TO_ARGS_OFFSET:
11409                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11410   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11411   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11412   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11413   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11414   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11415   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11416   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11417   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11418   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11419   case ISD::SRA:
11420   case ISD::SRL:
11421   case ISD::SHL:                return LowerShift(Op, DAG);
11422   case ISD::SADDO:
11423   case ISD::UADDO:
11424   case ISD::SSUBO:
11425   case ISD::USUBO:
11426   case ISD::SMULO:
11427   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11428   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11429   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11430   case ISD::ADDC:
11431   case ISD::ADDE:
11432   case ISD::SUBC:
11433   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11434   case ISD::ADD:                return LowerADD(Op, DAG);
11435   case ISD::SUB:                return LowerSUB(Op, DAG);
11436   }
11437 }
11438
11439 static void ReplaceATOMIC_LOAD(SDNode *Node,
11440                                   SmallVectorImpl<SDValue> &Results,
11441                                   SelectionDAG &DAG) {
11442   DebugLoc dl = Node->getDebugLoc();
11443   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11444
11445   // Convert wide load -> cmpxchg8b/cmpxchg16b
11446   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11447   //        (The only way to get a 16-byte load is cmpxchg16b)
11448   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11449   SDValue Zero = DAG.getConstant(0, VT);
11450   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11451                                Node->getOperand(0),
11452                                Node->getOperand(1), Zero, Zero,
11453                                cast<AtomicSDNode>(Node)->getMemOperand(),
11454                                cast<AtomicSDNode>(Node)->getOrdering(),
11455                                cast<AtomicSDNode>(Node)->getSynchScope());
11456   Results.push_back(Swap.getValue(0));
11457   Results.push_back(Swap.getValue(1));
11458 }
11459
11460 static void
11461 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11462                         SelectionDAG &DAG, unsigned NewOp) {
11463   DebugLoc dl = Node->getDebugLoc();
11464   assert (Node->getValueType(0) == MVT::i64 &&
11465           "Only know how to expand i64 atomics");
11466
11467   SDValue Chain = Node->getOperand(0);
11468   SDValue In1 = Node->getOperand(1);
11469   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11470                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11471   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11472                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11473   SDValue Ops[] = { Chain, In1, In2L, In2H };
11474   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11475   SDValue Result =
11476     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11477                             cast<MemSDNode>(Node)->getMemOperand());
11478   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11479   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11480   Results.push_back(Result.getValue(2));
11481 }
11482
11483 /// ReplaceNodeResults - Replace a node with an illegal result type
11484 /// with a new node built out of custom code.
11485 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11486                                            SmallVectorImpl<SDValue>&Results,
11487                                            SelectionDAG &DAG) const {
11488   DebugLoc dl = N->getDebugLoc();
11489   switch (N->getOpcode()) {
11490   default:
11491     llvm_unreachable("Do not know how to custom type legalize this operation!");
11492   case ISD::SIGN_EXTEND_INREG:
11493   case ISD::ADDC:
11494   case ISD::ADDE:
11495   case ISD::SUBC:
11496   case ISD::SUBE:
11497     // We don't want to expand or promote these.
11498     return;
11499   case ISD::FP_TO_SINT:
11500   case ISD::FP_TO_UINT: {
11501     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11502
11503     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11504       return;
11505
11506     std::pair<SDValue,SDValue> Vals =
11507         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11508     SDValue FIST = Vals.first, StackSlot = Vals.second;
11509     if (FIST.getNode() != 0) {
11510       EVT VT = N->getValueType(0);
11511       // Return a load from the stack slot.
11512       if (StackSlot.getNode() != 0)
11513         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11514                                       MachinePointerInfo(),
11515                                       false, false, false, 0));
11516       else
11517         Results.push_back(FIST);
11518     }
11519     return;
11520   }
11521   case ISD::READCYCLECOUNTER: {
11522     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11523     SDValue TheChain = N->getOperand(0);
11524     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11525     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11526                                      rd.getValue(1));
11527     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11528                                      eax.getValue(2));
11529     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11530     SDValue Ops[] = { eax, edx };
11531     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11532     Results.push_back(edx.getValue(1));
11533     return;
11534   }
11535   case ISD::ATOMIC_CMP_SWAP: {
11536     EVT T = N->getValueType(0);
11537     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11538     bool Regs64bit = T == MVT::i128;
11539     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11540     SDValue cpInL, cpInH;
11541     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11542                         DAG.getConstant(0, HalfT));
11543     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11544                         DAG.getConstant(1, HalfT));
11545     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11546                              Regs64bit ? X86::RAX : X86::EAX,
11547                              cpInL, SDValue());
11548     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11549                              Regs64bit ? X86::RDX : X86::EDX,
11550                              cpInH, cpInL.getValue(1));
11551     SDValue swapInL, swapInH;
11552     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11553                           DAG.getConstant(0, HalfT));
11554     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11555                           DAG.getConstant(1, HalfT));
11556     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11557                                Regs64bit ? X86::RBX : X86::EBX,
11558                                swapInL, cpInH.getValue(1));
11559     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11560                                Regs64bit ? X86::RCX : X86::ECX,
11561                                swapInH, swapInL.getValue(1));
11562     SDValue Ops[] = { swapInH.getValue(0),
11563                       N->getOperand(1),
11564                       swapInH.getValue(1) };
11565     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11566     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11567     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11568                                   X86ISD::LCMPXCHG8_DAG;
11569     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11570                                              Ops, 3, T, MMO);
11571     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11572                                         Regs64bit ? X86::RAX : X86::EAX,
11573                                         HalfT, Result.getValue(1));
11574     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11575                                         Regs64bit ? X86::RDX : X86::EDX,
11576                                         HalfT, cpOutL.getValue(2));
11577     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11578     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11579     Results.push_back(cpOutH.getValue(1));
11580     return;
11581   }
11582   case ISD::ATOMIC_LOAD_ADD:
11583   case ISD::ATOMIC_LOAD_AND:
11584   case ISD::ATOMIC_LOAD_NAND:
11585   case ISD::ATOMIC_LOAD_OR:
11586   case ISD::ATOMIC_LOAD_SUB:
11587   case ISD::ATOMIC_LOAD_XOR:
11588   case ISD::ATOMIC_SWAP: {
11589     unsigned Opc;
11590     switch (N->getOpcode()) {
11591     default: llvm_unreachable("Unexpected opcode");
11592     case ISD::ATOMIC_LOAD_ADD:
11593       Opc = X86ISD::ATOMADD64_DAG;
11594       break;
11595     case ISD::ATOMIC_LOAD_AND:
11596       Opc = X86ISD::ATOMAND64_DAG;
11597       break;
11598     case ISD::ATOMIC_LOAD_NAND:
11599       Opc = X86ISD::ATOMNAND64_DAG;
11600       break;
11601     case ISD::ATOMIC_LOAD_OR:
11602       Opc = X86ISD::ATOMOR64_DAG;
11603       break;
11604     case ISD::ATOMIC_LOAD_SUB:
11605       Opc = X86ISD::ATOMSUB64_DAG;
11606       break;
11607     case ISD::ATOMIC_LOAD_XOR:
11608       Opc = X86ISD::ATOMXOR64_DAG;
11609       break;
11610     case ISD::ATOMIC_SWAP:
11611       Opc = X86ISD::ATOMSWAP64_DAG;
11612       break;
11613     }
11614     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11615     return;
11616   }
11617   case ISD::ATOMIC_LOAD:
11618     ReplaceATOMIC_LOAD(N, Results, DAG);
11619   }
11620 }
11621
11622 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11623   switch (Opcode) {
11624   default: return NULL;
11625   case X86ISD::BSF:                return "X86ISD::BSF";
11626   case X86ISD::BSR:                return "X86ISD::BSR";
11627   case X86ISD::SHLD:               return "X86ISD::SHLD";
11628   case X86ISD::SHRD:               return "X86ISD::SHRD";
11629   case X86ISD::FAND:               return "X86ISD::FAND";
11630   case X86ISD::FOR:                return "X86ISD::FOR";
11631   case X86ISD::FXOR:               return "X86ISD::FXOR";
11632   case X86ISD::FSRL:               return "X86ISD::FSRL";
11633   case X86ISD::FILD:               return "X86ISD::FILD";
11634   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11635   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11636   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11637   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11638   case X86ISD::FLD:                return "X86ISD::FLD";
11639   case X86ISD::FST:                return "X86ISD::FST";
11640   case X86ISD::CALL:               return "X86ISD::CALL";
11641   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11642   case X86ISD::BT:                 return "X86ISD::BT";
11643   case X86ISD::CMP:                return "X86ISD::CMP";
11644   case X86ISD::COMI:               return "X86ISD::COMI";
11645   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11646   case X86ISD::SETCC:              return "X86ISD::SETCC";
11647   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11648   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11649   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11650   case X86ISD::CMOV:               return "X86ISD::CMOV";
11651   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11652   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11653   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11654   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11655   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11656   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11657   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11658   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11659   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11660   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11661   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11662   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11663   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11664   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11665   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11666   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11667   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11668   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11669   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11670   case X86ISD::HADD:               return "X86ISD::HADD";
11671   case X86ISD::HSUB:               return "X86ISD::HSUB";
11672   case X86ISD::FHADD:              return "X86ISD::FHADD";
11673   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11674   case X86ISD::FMAX:               return "X86ISD::FMAX";
11675   case X86ISD::FMIN:               return "X86ISD::FMIN";
11676   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11677   case X86ISD::FMINC:              return "X86ISD::FMINC";
11678   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11679   case X86ISD::FRCP:               return "X86ISD::FRCP";
11680   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11681   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11682   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11683   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11684   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11685   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11686   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11687   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11688   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11689   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11690   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11691   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11692   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11693   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11694   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11695   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11696   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11697   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11698   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11699   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11700   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11701   case X86ISD::VSHL:               return "X86ISD::VSHL";
11702   case X86ISD::VSRL:               return "X86ISD::VSRL";
11703   case X86ISD::VSRA:               return "X86ISD::VSRA";
11704   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11705   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11706   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11707   case X86ISD::CMPP:               return "X86ISD::CMPP";
11708   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11709   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11710   case X86ISD::ADD:                return "X86ISD::ADD";
11711   case X86ISD::SUB:                return "X86ISD::SUB";
11712   case X86ISD::ADC:                return "X86ISD::ADC";
11713   case X86ISD::SBB:                return "X86ISD::SBB";
11714   case X86ISD::SMUL:               return "X86ISD::SMUL";
11715   case X86ISD::UMUL:               return "X86ISD::UMUL";
11716   case X86ISD::INC:                return "X86ISD::INC";
11717   case X86ISD::DEC:                return "X86ISD::DEC";
11718   case X86ISD::OR:                 return "X86ISD::OR";
11719   case X86ISD::XOR:                return "X86ISD::XOR";
11720   case X86ISD::AND:                return "X86ISD::AND";
11721   case X86ISD::ANDN:               return "X86ISD::ANDN";
11722   case X86ISD::BLSI:               return "X86ISD::BLSI";
11723   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11724   case X86ISD::BLSR:               return "X86ISD::BLSR";
11725   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11726   case X86ISD::PTEST:              return "X86ISD::PTEST";
11727   case X86ISD::TESTP:              return "X86ISD::TESTP";
11728   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11729   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11730   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11731   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11732   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11733   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11734   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11735   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11736   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11737   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11738   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11739   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11740   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11741   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11742   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11743   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11744   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11745   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11746   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11747   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11748   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11749   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11750   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11751   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11752   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11753   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11754   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11755   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11756   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11757   case X86ISD::SAHF:               return "X86ISD::SAHF";
11758   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11759   case X86ISD::FMADD:              return "X86ISD::FMADD";
11760   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11761   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11762   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11763   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11764   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11765   }
11766 }
11767
11768 // isLegalAddressingMode - Return true if the addressing mode represented
11769 // by AM is legal for this target, for a load/store of the specified type.
11770 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11771                                               Type *Ty) const {
11772   // X86 supports extremely general addressing modes.
11773   CodeModel::Model M = getTargetMachine().getCodeModel();
11774   Reloc::Model R = getTargetMachine().getRelocationModel();
11775
11776   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11777   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11778     return false;
11779
11780   if (AM.BaseGV) {
11781     unsigned GVFlags =
11782       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11783
11784     // If a reference to this global requires an extra load, we can't fold it.
11785     if (isGlobalStubReference(GVFlags))
11786       return false;
11787
11788     // If BaseGV requires a register for the PIC base, we cannot also have a
11789     // BaseReg specified.
11790     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11791       return false;
11792
11793     // If lower 4G is not available, then we must use rip-relative addressing.
11794     if ((M != CodeModel::Small || R != Reloc::Static) &&
11795         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11796       return false;
11797   }
11798
11799   switch (AM.Scale) {
11800   case 0:
11801   case 1:
11802   case 2:
11803   case 4:
11804   case 8:
11805     // These scales always work.
11806     break;
11807   case 3:
11808   case 5:
11809   case 9:
11810     // These scales are formed with basereg+scalereg.  Only accept if there is
11811     // no basereg yet.
11812     if (AM.HasBaseReg)
11813       return false;
11814     break;
11815   default:  // Other stuff never works.
11816     return false;
11817   }
11818
11819   return true;
11820 }
11821
11822
11823 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11824   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11825     return false;
11826   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11827   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11828   if (NumBits1 <= NumBits2)
11829     return false;
11830   return true;
11831 }
11832
11833 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11834   return Imm == (int32_t)Imm;
11835 }
11836
11837 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11838   // Can also use sub to handle negated immediates.
11839   return Imm == (int32_t)Imm;
11840 }
11841
11842 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11843   if (!VT1.isInteger() || !VT2.isInteger())
11844     return false;
11845   unsigned NumBits1 = VT1.getSizeInBits();
11846   unsigned NumBits2 = VT2.getSizeInBits();
11847   if (NumBits1 <= NumBits2)
11848     return false;
11849   return true;
11850 }
11851
11852 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11853   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11854   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11855 }
11856
11857 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11858   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11859   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11860 }
11861
11862 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11863   // i16 instructions are longer (0x66 prefix) and potentially slower.
11864   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11865 }
11866
11867 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11868 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11869 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11870 /// are assumed to be legal.
11871 bool
11872 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11873                                       EVT VT) const {
11874   // Very little shuffling can be done for 64-bit vectors right now.
11875   if (VT.getSizeInBits() == 64)
11876     return false;
11877
11878   // FIXME: pshufb, blends, shifts.
11879   return (VT.getVectorNumElements() == 2 ||
11880           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11881           isMOVLMask(M, VT) ||
11882           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11883           isPSHUFDMask(M, VT) ||
11884           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11885           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11886           isPALIGNRMask(M, VT, Subtarget) ||
11887           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11888           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11889           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11890           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11891 }
11892
11893 bool
11894 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11895                                           EVT VT) const {
11896   unsigned NumElts = VT.getVectorNumElements();
11897   // FIXME: This collection of masks seems suspect.
11898   if (NumElts == 2)
11899     return true;
11900   if (NumElts == 4 && VT.is128BitVector()) {
11901     return (isMOVLMask(Mask, VT)  ||
11902             isCommutedMOVLMask(Mask, VT, true) ||
11903             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11904             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11905   }
11906   return false;
11907 }
11908
11909 //===----------------------------------------------------------------------===//
11910 //                           X86 Scheduler Hooks
11911 //===----------------------------------------------------------------------===//
11912
11913 // private utility function
11914
11915 // Get CMPXCHG opcode for the specified data type.
11916 static unsigned getCmpXChgOpcode(EVT VT) {
11917   switch (VT.getSimpleVT().SimpleTy) {
11918   case MVT::i8:  return X86::LCMPXCHG8;
11919   case MVT::i16: return X86::LCMPXCHG16;
11920   case MVT::i32: return X86::LCMPXCHG32;
11921   case MVT::i64: return X86::LCMPXCHG64;
11922   default:
11923     break;
11924   }
11925   llvm_unreachable("Invalid operand size!");
11926 }
11927
11928 // Get LOAD opcode for the specified data type.
11929 static unsigned getLoadOpcode(EVT VT) {
11930   switch (VT.getSimpleVT().SimpleTy) {
11931   case MVT::i8:  return X86::MOV8rm;
11932   case MVT::i16: return X86::MOV16rm;
11933   case MVT::i32: return X86::MOV32rm;
11934   case MVT::i64: return X86::MOV64rm;
11935   default:
11936     break;
11937   }
11938   llvm_unreachable("Invalid operand size!");
11939 }
11940
11941 // Get opcode of the non-atomic one from the specified atomic instruction.
11942 static unsigned getNonAtomicOpcode(unsigned Opc) {
11943   switch (Opc) {
11944   case X86::ATOMAND8:  return X86::AND8rr;
11945   case X86::ATOMAND16: return X86::AND16rr;
11946   case X86::ATOMAND32: return X86::AND32rr;
11947   case X86::ATOMAND64: return X86::AND64rr;
11948   case X86::ATOMOR8:   return X86::OR8rr;
11949   case X86::ATOMOR16:  return X86::OR16rr;
11950   case X86::ATOMOR32:  return X86::OR32rr;
11951   case X86::ATOMOR64:  return X86::OR64rr;
11952   case X86::ATOMXOR8:  return X86::XOR8rr;
11953   case X86::ATOMXOR16: return X86::XOR16rr;
11954   case X86::ATOMXOR32: return X86::XOR32rr;
11955   case X86::ATOMXOR64: return X86::XOR64rr;
11956   }
11957   llvm_unreachable("Unhandled atomic-load-op opcode!");
11958 }
11959
11960 // Get opcode of the non-atomic one from the specified atomic instruction with
11961 // extra opcode.
11962 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11963                                                unsigned &ExtraOpc) {
11964   switch (Opc) {
11965   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
11966   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
11967   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
11968   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
11969   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
11970   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
11971   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
11972   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
11973   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
11974   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
11975   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
11976   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
11977   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
11978   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
11979   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
11980   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
11981   }
11982   llvm_unreachable("Unhandled atomic-load-op opcode!");
11983 }
11984
11985 // Get opcode of the non-atomic one from the specified atomic instruction for
11986 // 64-bit data type on 32-bit target.
11987 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
11988   switch (Opc) {
11989   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
11990   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
11991   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
11992   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
11993   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
11994   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
11995   }
11996   llvm_unreachable("Unhandled atomic-load-op opcode!");
11997 }
11998
11999 // Get opcode of the non-atomic one from the specified atomic instruction for
12000 // 64-bit data type on 32-bit target with extra opcode.
12001 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12002                                                    unsigned &HiOpc,
12003                                                    unsigned &ExtraOpc) {
12004   switch (Opc) {
12005   case X86::ATOMNAND6432:
12006     ExtraOpc = X86::NOT32r;
12007     HiOpc = X86::AND32rr;
12008     return X86::AND32rr;
12009   }
12010   llvm_unreachable("Unhandled atomic-load-op opcode!");
12011 }
12012
12013 // Get pseudo CMOV opcode from the specified data type.
12014 static unsigned getPseudoCMOVOpc(EVT VT) {
12015   switch (VT.getSimpleVT().SimpleTy) {
12016   case MVT::i16: return X86::CMOV_GR16;
12017   case MVT::i32: return X86::CMOV_GR32;
12018   default:
12019     break;
12020   }
12021   llvm_unreachable("Unknown CMOV opcode!");
12022 }
12023
12024 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12025 // They will be translated into a spin-loop or compare-exchange loop from
12026 //
12027 //    ...
12028 //    dst = atomic-fetch-op MI.addr, MI.val
12029 //    ...
12030 //
12031 // to
12032 //
12033 //    ...
12034 //    EAX = LOAD MI.addr
12035 // loop:
12036 //    t1 = OP MI.val, EAX
12037 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12038 //    JNE loop
12039 // sink:
12040 //    dst = EAX
12041 //    ...
12042 MachineBasicBlock *
12043 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12044                                        MachineBasicBlock *MBB) const {
12045   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12046   DebugLoc DL = MI->getDebugLoc();
12047
12048   MachineFunction *MF = MBB->getParent();
12049   MachineRegisterInfo &MRI = MF->getRegInfo();
12050
12051   const BasicBlock *BB = MBB->getBasicBlock();
12052   MachineFunction::iterator I = MBB;
12053   ++I;
12054
12055   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12056          "Unexpected number of operands");
12057
12058   assert(MI->hasOneMemOperand() &&
12059          "Expected atomic-load-op to have one memoperand");
12060
12061   // Memory Reference
12062   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12063   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12064
12065   unsigned DstReg, SrcReg;
12066   unsigned MemOpndSlot;
12067
12068   unsigned CurOp = 0;
12069
12070   DstReg = MI->getOperand(CurOp++).getReg();
12071   MemOpndSlot = CurOp;
12072   CurOp += X86::AddrNumOperands;
12073   SrcReg = MI->getOperand(CurOp++).getReg();
12074
12075   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12076   EVT VT = *RC->vt_begin();
12077   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12078
12079   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12080   unsigned LOADOpc = getLoadOpcode(VT);
12081
12082   // For the atomic load-arith operator, we generate
12083   //
12084   //  thisMBB:
12085   //    EAX = LOAD [MI.addr]
12086   //  mainMBB:
12087   //    t1 = OP MI.val, EAX
12088   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12089   //    JNE mainMBB
12090   //  sinkMBB:
12091
12092   MachineBasicBlock *thisMBB = MBB;
12093   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12094   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12095   MF->insert(I, mainMBB);
12096   MF->insert(I, sinkMBB);
12097
12098   MachineInstrBuilder MIB;
12099
12100   // Transfer the remainder of BB and its successor edges to sinkMBB.
12101   sinkMBB->splice(sinkMBB->begin(), MBB,
12102                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12103   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12104
12105   // thisMBB:
12106   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12107   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12108     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12109   MIB.setMemRefs(MMOBegin, MMOEnd);
12110
12111   thisMBB->addSuccessor(mainMBB);
12112
12113   // mainMBB:
12114   MachineBasicBlock *origMainMBB = mainMBB;
12115   mainMBB->addLiveIn(AccPhyReg);
12116
12117   // Copy AccPhyReg as it is used more than once.
12118   unsigned AccReg = MRI.createVirtualRegister(RC);
12119   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12120     .addReg(AccPhyReg);
12121
12122   unsigned t1 = MRI.createVirtualRegister(RC);
12123   unsigned Opc = MI->getOpcode();
12124   switch (Opc) {
12125   default:
12126     llvm_unreachable("Unhandled atomic-load-op opcode!");
12127   case X86::ATOMAND8:
12128   case X86::ATOMAND16:
12129   case X86::ATOMAND32:
12130   case X86::ATOMAND64:
12131   case X86::ATOMOR8:
12132   case X86::ATOMOR16:
12133   case X86::ATOMOR32:
12134   case X86::ATOMOR64:
12135   case X86::ATOMXOR8:
12136   case X86::ATOMXOR16:
12137   case X86::ATOMXOR32:
12138   case X86::ATOMXOR64: {
12139     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12140     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12141       .addReg(AccReg);
12142     break;
12143   }
12144   case X86::ATOMNAND8:
12145   case X86::ATOMNAND16:
12146   case X86::ATOMNAND32:
12147   case X86::ATOMNAND64: {
12148     unsigned t2 = MRI.createVirtualRegister(RC);
12149     unsigned NOTOpc;
12150     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12151     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12152       .addReg(AccReg);
12153     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12154     break;
12155   }
12156   case X86::ATOMMAX8:
12157   case X86::ATOMMIN8:
12158   case X86::ATOMUMAX8:
12159   case X86::ATOMUMIN8:
12160     llvm_unreachable("Not supported yet!");
12161   case X86::ATOMMAX16:
12162   case X86::ATOMMAX32:
12163   case X86::ATOMMAX64:
12164   case X86::ATOMMIN16:
12165   case X86::ATOMMIN32:
12166   case X86::ATOMMIN64:
12167   case X86::ATOMUMAX16:
12168   case X86::ATOMUMAX32:
12169   case X86::ATOMUMAX64:
12170   case X86::ATOMUMIN16:
12171   case X86::ATOMUMIN32:
12172   case X86::ATOMUMIN64: {
12173     unsigned CMPOpc;
12174     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12175
12176     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12177       .addReg(SrcReg)
12178       .addReg(AccReg);
12179
12180     if (Subtarget->hasCMov()) {
12181       // Native support
12182       BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12183         .addReg(SrcReg)
12184         .addReg(AccReg);
12185     } else {
12186       // Use pseudo select and lower them.
12187       assert((VT == MVT::i16 || VT == MVT::i32) &&
12188              "Invalid atomic-load-op transformation!");
12189       unsigned SelOpc = getPseudoCMOVOpc(VT);
12190       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12191       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12192       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12193               .addReg(SrcReg).addReg(AccReg)
12194               .addImm(CC);
12195       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12196     }
12197     break;
12198   }
12199   }
12200
12201   // Copy AccPhyReg back from virtual register.
12202   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12203     .addReg(AccReg);
12204
12205   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12206   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12207     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12208   MIB.addReg(t1);
12209   MIB.setMemRefs(MMOBegin, MMOEnd);
12210
12211   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12212
12213   mainMBB->addSuccessor(origMainMBB);
12214   mainMBB->addSuccessor(sinkMBB);
12215
12216   // sinkMBB:
12217   sinkMBB->addLiveIn(AccPhyReg);
12218
12219   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12220           TII->get(TargetOpcode::COPY), DstReg)
12221     .addReg(AccPhyReg);
12222
12223   MI->eraseFromParent();
12224   return sinkMBB;
12225 }
12226
12227 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12228 // instructions. They will be translated into a spin-loop or compare-exchange
12229 // loop from
12230 //
12231 //    ...
12232 //    dst = atomic-fetch-op MI.addr, MI.val
12233 //    ...
12234 //
12235 // to
12236 //
12237 //    ...
12238 //    EAX = LOAD [MI.addr + 0]
12239 //    EDX = LOAD [MI.addr + 4]
12240 // loop:
12241 //    EBX = OP MI.val.lo, EAX
12242 //    ECX = OP MI.val.hi, EDX
12243 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12244 //    JNE loop
12245 // sink:
12246 //    dst = EDX:EAX
12247 //    ...
12248 MachineBasicBlock *
12249 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12250                                            MachineBasicBlock *MBB) const {
12251   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12252   DebugLoc DL = MI->getDebugLoc();
12253
12254   MachineFunction *MF = MBB->getParent();
12255   MachineRegisterInfo &MRI = MF->getRegInfo();
12256
12257   const BasicBlock *BB = MBB->getBasicBlock();
12258   MachineFunction::iterator I = MBB;
12259   ++I;
12260
12261   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12262          "Unexpected number of operands");
12263
12264   assert(MI->hasOneMemOperand() &&
12265          "Expected atomic-load-op32 to have one memoperand");
12266
12267   // Memory Reference
12268   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12269   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12270
12271   unsigned DstLoReg, DstHiReg;
12272   unsigned SrcLoReg, SrcHiReg;
12273   unsigned MemOpndSlot;
12274
12275   unsigned CurOp = 0;
12276
12277   DstLoReg = MI->getOperand(CurOp++).getReg();
12278   DstHiReg = MI->getOperand(CurOp++).getReg();
12279   MemOpndSlot = CurOp;
12280   CurOp += X86::AddrNumOperands;
12281   SrcLoReg = MI->getOperand(CurOp++).getReg();
12282   SrcHiReg = MI->getOperand(CurOp++).getReg();
12283
12284   const TargetRegisterClass *RC = &X86::GR32RegClass;
12285
12286   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12287   unsigned LOADOpc = X86::MOV32rm;
12288
12289   // For the atomic load-arith operator, we generate
12290   //
12291   //  thisMBB:
12292   //    EAX = LOAD [MI.addr + 0]
12293   //    EDX = LOAD [MI.addr + 4]
12294   //  mainMBB:
12295   //    EBX = OP MI.vallo, EAX
12296   //    ECX = OP MI.valhi, EDX
12297   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12298   //    JNE mainMBB
12299   //  sinkMBB:
12300
12301   MachineBasicBlock *thisMBB = MBB;
12302   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12303   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12304   MF->insert(I, mainMBB);
12305   MF->insert(I, sinkMBB);
12306
12307   MachineInstrBuilder MIB;
12308
12309   // Transfer the remainder of BB and its successor edges to sinkMBB.
12310   sinkMBB->splice(sinkMBB->begin(), MBB,
12311                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12312   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12313
12314   // thisMBB:
12315   // Lo
12316   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12317   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12318     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12319   MIB.setMemRefs(MMOBegin, MMOEnd);
12320   // Hi
12321   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12322   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12323     if (i == X86::AddrDisp)
12324       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12325     else
12326       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12327   }
12328   MIB.setMemRefs(MMOBegin, MMOEnd);
12329
12330   thisMBB->addSuccessor(mainMBB);
12331
12332   // mainMBB:
12333   MachineBasicBlock *origMainMBB = mainMBB;
12334   mainMBB->addLiveIn(X86::EAX);
12335   mainMBB->addLiveIn(X86::EDX);
12336
12337   // Copy EDX:EAX as they are used more than once.
12338   unsigned LoReg = MRI.createVirtualRegister(RC);
12339   unsigned HiReg = MRI.createVirtualRegister(RC);
12340   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12341   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12342
12343   unsigned t1L = MRI.createVirtualRegister(RC);
12344   unsigned t1H = MRI.createVirtualRegister(RC);
12345
12346   unsigned Opc = MI->getOpcode();
12347   switch (Opc) {
12348   default:
12349     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12350   case X86::ATOMAND6432:
12351   case X86::ATOMOR6432:
12352   case X86::ATOMXOR6432:
12353   case X86::ATOMADD6432:
12354   case X86::ATOMSUB6432: {
12355     unsigned HiOpc;
12356     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12357     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12358     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12359     break;
12360   }
12361   case X86::ATOMNAND6432: {
12362     unsigned HiOpc, NOTOpc;
12363     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12364     unsigned t2L = MRI.createVirtualRegister(RC);
12365     unsigned t2H = MRI.createVirtualRegister(RC);
12366     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12367     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12368     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12369     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12370     break;
12371   }
12372   case X86::ATOMSWAP6432: {
12373     unsigned HiOpc;
12374     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12375     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12376     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12377     break;
12378   }
12379   }
12380
12381   // Copy EDX:EAX back from HiReg:LoReg
12382   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12383   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12384   // Copy ECX:EBX from t1H:t1L
12385   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12386   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12387
12388   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12389   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12390     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12391   MIB.setMemRefs(MMOBegin, MMOEnd);
12392
12393   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12394
12395   mainMBB->addSuccessor(origMainMBB);
12396   mainMBB->addSuccessor(sinkMBB);
12397
12398   // sinkMBB:
12399   sinkMBB->addLiveIn(X86::EAX);
12400   sinkMBB->addLiveIn(X86::EDX);
12401
12402   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12403           TII->get(TargetOpcode::COPY), DstLoReg)
12404     .addReg(X86::EAX);
12405   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12406           TII->get(TargetOpcode::COPY), DstHiReg)
12407     .addReg(X86::EDX);
12408
12409   MI->eraseFromParent();
12410   return sinkMBB;
12411 }
12412
12413 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12414 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12415 // in the .td file.
12416 MachineBasicBlock *
12417 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12418                             unsigned numArgs, bool memArg) const {
12419   assert(Subtarget->hasSSE42() &&
12420          "Target must have SSE4.2 or AVX features enabled");
12421
12422   DebugLoc dl = MI->getDebugLoc();
12423   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12424   unsigned Opc;
12425   if (!Subtarget->hasAVX()) {
12426     if (memArg)
12427       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12428     else
12429       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12430   } else {
12431     if (memArg)
12432       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12433     else
12434       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12435   }
12436
12437   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12438   for (unsigned i = 0; i < numArgs; ++i) {
12439     MachineOperand &Op = MI->getOperand(i+1);
12440     if (!(Op.isReg() && Op.isImplicit()))
12441       MIB.addOperand(Op);
12442   }
12443   BuildMI(*BB, MI, dl,
12444     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12445     .addReg(X86::XMM0);
12446
12447   MI->eraseFromParent();
12448   return BB;
12449 }
12450
12451 MachineBasicBlock *
12452 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12453   DebugLoc dl = MI->getDebugLoc();
12454   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12455
12456   // Address into RAX/EAX, other two args into ECX, EDX.
12457   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12458   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12459   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12460   for (int i = 0; i < X86::AddrNumOperands; ++i)
12461     MIB.addOperand(MI->getOperand(i));
12462
12463   unsigned ValOps = X86::AddrNumOperands;
12464   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12465     .addReg(MI->getOperand(ValOps).getReg());
12466   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12467     .addReg(MI->getOperand(ValOps+1).getReg());
12468
12469   // The instruction doesn't actually take any operands though.
12470   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12471
12472   MI->eraseFromParent(); // The pseudo is gone now.
12473   return BB;
12474 }
12475
12476 MachineBasicBlock *
12477 X86TargetLowering::EmitVAARG64WithCustomInserter(
12478                    MachineInstr *MI,
12479                    MachineBasicBlock *MBB) const {
12480   // Emit va_arg instruction on X86-64.
12481
12482   // Operands to this pseudo-instruction:
12483   // 0  ) Output        : destination address (reg)
12484   // 1-5) Input         : va_list address (addr, i64mem)
12485   // 6  ) ArgSize       : Size (in bytes) of vararg type
12486   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12487   // 8  ) Align         : Alignment of type
12488   // 9  ) EFLAGS (implicit-def)
12489
12490   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12491   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12492
12493   unsigned DestReg = MI->getOperand(0).getReg();
12494   MachineOperand &Base = MI->getOperand(1);
12495   MachineOperand &Scale = MI->getOperand(2);
12496   MachineOperand &Index = MI->getOperand(3);
12497   MachineOperand &Disp = MI->getOperand(4);
12498   MachineOperand &Segment = MI->getOperand(5);
12499   unsigned ArgSize = MI->getOperand(6).getImm();
12500   unsigned ArgMode = MI->getOperand(7).getImm();
12501   unsigned Align = MI->getOperand(8).getImm();
12502
12503   // Memory Reference
12504   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12505   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12506   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12507
12508   // Machine Information
12509   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12510   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12511   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12512   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12513   DebugLoc DL = MI->getDebugLoc();
12514
12515   // struct va_list {
12516   //   i32   gp_offset
12517   //   i32   fp_offset
12518   //   i64   overflow_area (address)
12519   //   i64   reg_save_area (address)
12520   // }
12521   // sizeof(va_list) = 24
12522   // alignment(va_list) = 8
12523
12524   unsigned TotalNumIntRegs = 6;
12525   unsigned TotalNumXMMRegs = 8;
12526   bool UseGPOffset = (ArgMode == 1);
12527   bool UseFPOffset = (ArgMode == 2);
12528   unsigned MaxOffset = TotalNumIntRegs * 8 +
12529                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12530
12531   /* Align ArgSize to a multiple of 8 */
12532   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12533   bool NeedsAlign = (Align > 8);
12534
12535   MachineBasicBlock *thisMBB = MBB;
12536   MachineBasicBlock *overflowMBB;
12537   MachineBasicBlock *offsetMBB;
12538   MachineBasicBlock *endMBB;
12539
12540   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12541   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12542   unsigned OffsetReg = 0;
12543
12544   if (!UseGPOffset && !UseFPOffset) {
12545     // If we only pull from the overflow region, we don't create a branch.
12546     // We don't need to alter control flow.
12547     OffsetDestReg = 0; // unused
12548     OverflowDestReg = DestReg;
12549
12550     offsetMBB = NULL;
12551     overflowMBB = thisMBB;
12552     endMBB = thisMBB;
12553   } else {
12554     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12555     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12556     // If not, pull from overflow_area. (branch to overflowMBB)
12557     //
12558     //       thisMBB
12559     //         |     .
12560     //         |        .
12561     //     offsetMBB   overflowMBB
12562     //         |        .
12563     //         |     .
12564     //        endMBB
12565
12566     // Registers for the PHI in endMBB
12567     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12568     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12569
12570     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12571     MachineFunction *MF = MBB->getParent();
12572     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12573     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12574     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12575
12576     MachineFunction::iterator MBBIter = MBB;
12577     ++MBBIter;
12578
12579     // Insert the new basic blocks
12580     MF->insert(MBBIter, offsetMBB);
12581     MF->insert(MBBIter, overflowMBB);
12582     MF->insert(MBBIter, endMBB);
12583
12584     // Transfer the remainder of MBB and its successor edges to endMBB.
12585     endMBB->splice(endMBB->begin(), thisMBB,
12586                     llvm::next(MachineBasicBlock::iterator(MI)),
12587                     thisMBB->end());
12588     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12589
12590     // Make offsetMBB and overflowMBB successors of thisMBB
12591     thisMBB->addSuccessor(offsetMBB);
12592     thisMBB->addSuccessor(overflowMBB);
12593
12594     // endMBB is a successor of both offsetMBB and overflowMBB
12595     offsetMBB->addSuccessor(endMBB);
12596     overflowMBB->addSuccessor(endMBB);
12597
12598     // Load the offset value into a register
12599     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12600     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12601       .addOperand(Base)
12602       .addOperand(Scale)
12603       .addOperand(Index)
12604       .addDisp(Disp, UseFPOffset ? 4 : 0)
12605       .addOperand(Segment)
12606       .setMemRefs(MMOBegin, MMOEnd);
12607
12608     // Check if there is enough room left to pull this argument.
12609     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12610       .addReg(OffsetReg)
12611       .addImm(MaxOffset + 8 - ArgSizeA8);
12612
12613     // Branch to "overflowMBB" if offset >= max
12614     // Fall through to "offsetMBB" otherwise
12615     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12616       .addMBB(overflowMBB);
12617   }
12618
12619   // In offsetMBB, emit code to use the reg_save_area.
12620   if (offsetMBB) {
12621     assert(OffsetReg != 0);
12622
12623     // Read the reg_save_area address.
12624     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12625     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12626       .addOperand(Base)
12627       .addOperand(Scale)
12628       .addOperand(Index)
12629       .addDisp(Disp, 16)
12630       .addOperand(Segment)
12631       .setMemRefs(MMOBegin, MMOEnd);
12632
12633     // Zero-extend the offset
12634     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12635       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12636         .addImm(0)
12637         .addReg(OffsetReg)
12638         .addImm(X86::sub_32bit);
12639
12640     // Add the offset to the reg_save_area to get the final address.
12641     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12642       .addReg(OffsetReg64)
12643       .addReg(RegSaveReg);
12644
12645     // Compute the offset for the next argument
12646     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12647     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12648       .addReg(OffsetReg)
12649       .addImm(UseFPOffset ? 16 : 8);
12650
12651     // Store it back into the va_list.
12652     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12653       .addOperand(Base)
12654       .addOperand(Scale)
12655       .addOperand(Index)
12656       .addDisp(Disp, UseFPOffset ? 4 : 0)
12657       .addOperand(Segment)
12658       .addReg(NextOffsetReg)
12659       .setMemRefs(MMOBegin, MMOEnd);
12660
12661     // Jump to endMBB
12662     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12663       .addMBB(endMBB);
12664   }
12665
12666   //
12667   // Emit code to use overflow area
12668   //
12669
12670   // Load the overflow_area address into a register.
12671   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12672   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12673     .addOperand(Base)
12674     .addOperand(Scale)
12675     .addOperand(Index)
12676     .addDisp(Disp, 8)
12677     .addOperand(Segment)
12678     .setMemRefs(MMOBegin, MMOEnd);
12679
12680   // If we need to align it, do so. Otherwise, just copy the address
12681   // to OverflowDestReg.
12682   if (NeedsAlign) {
12683     // Align the overflow address
12684     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12685     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12686
12687     // aligned_addr = (addr + (align-1)) & ~(align-1)
12688     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12689       .addReg(OverflowAddrReg)
12690       .addImm(Align-1);
12691
12692     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12693       .addReg(TmpReg)
12694       .addImm(~(uint64_t)(Align-1));
12695   } else {
12696     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12697       .addReg(OverflowAddrReg);
12698   }
12699
12700   // Compute the next overflow address after this argument.
12701   // (the overflow address should be kept 8-byte aligned)
12702   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12703   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12704     .addReg(OverflowDestReg)
12705     .addImm(ArgSizeA8);
12706
12707   // Store the new overflow address.
12708   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12709     .addOperand(Base)
12710     .addOperand(Scale)
12711     .addOperand(Index)
12712     .addDisp(Disp, 8)
12713     .addOperand(Segment)
12714     .addReg(NextAddrReg)
12715     .setMemRefs(MMOBegin, MMOEnd);
12716
12717   // If we branched, emit the PHI to the front of endMBB.
12718   if (offsetMBB) {
12719     BuildMI(*endMBB, endMBB->begin(), DL,
12720             TII->get(X86::PHI), DestReg)
12721       .addReg(OffsetDestReg).addMBB(offsetMBB)
12722       .addReg(OverflowDestReg).addMBB(overflowMBB);
12723   }
12724
12725   // Erase the pseudo instruction
12726   MI->eraseFromParent();
12727
12728   return endMBB;
12729 }
12730
12731 MachineBasicBlock *
12732 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12733                                                  MachineInstr *MI,
12734                                                  MachineBasicBlock *MBB) const {
12735   // Emit code to save XMM registers to the stack. The ABI says that the
12736   // number of registers to save is given in %al, so it's theoretically
12737   // possible to do an indirect jump trick to avoid saving all of them,
12738   // however this code takes a simpler approach and just executes all
12739   // of the stores if %al is non-zero. It's less code, and it's probably
12740   // easier on the hardware branch predictor, and stores aren't all that
12741   // expensive anyway.
12742
12743   // Create the new basic blocks. One block contains all the XMM stores,
12744   // and one block is the final destination regardless of whether any
12745   // stores were performed.
12746   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12747   MachineFunction *F = MBB->getParent();
12748   MachineFunction::iterator MBBIter = MBB;
12749   ++MBBIter;
12750   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12751   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12752   F->insert(MBBIter, XMMSaveMBB);
12753   F->insert(MBBIter, EndMBB);
12754
12755   // Transfer the remainder of MBB and its successor edges to EndMBB.
12756   EndMBB->splice(EndMBB->begin(), MBB,
12757                  llvm::next(MachineBasicBlock::iterator(MI)),
12758                  MBB->end());
12759   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12760
12761   // The original block will now fall through to the XMM save block.
12762   MBB->addSuccessor(XMMSaveMBB);
12763   // The XMMSaveMBB will fall through to the end block.
12764   XMMSaveMBB->addSuccessor(EndMBB);
12765
12766   // Now add the instructions.
12767   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12768   DebugLoc DL = MI->getDebugLoc();
12769
12770   unsigned CountReg = MI->getOperand(0).getReg();
12771   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12772   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12773
12774   if (!Subtarget->isTargetWin64()) {
12775     // If %al is 0, branch around the XMM save block.
12776     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12777     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12778     MBB->addSuccessor(EndMBB);
12779   }
12780
12781   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12782   // In the XMM save block, save all the XMM argument registers.
12783   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12784     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12785     MachineMemOperand *MMO =
12786       F->getMachineMemOperand(
12787           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12788         MachineMemOperand::MOStore,
12789         /*Size=*/16, /*Align=*/16);
12790     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12791       .addFrameIndex(RegSaveFrameIndex)
12792       .addImm(/*Scale=*/1)
12793       .addReg(/*IndexReg=*/0)
12794       .addImm(/*Disp=*/Offset)
12795       .addReg(/*Segment=*/0)
12796       .addReg(MI->getOperand(i).getReg())
12797       .addMemOperand(MMO);
12798   }
12799
12800   MI->eraseFromParent();   // The pseudo instruction is gone now.
12801
12802   return EndMBB;
12803 }
12804
12805 // The EFLAGS operand of SelectItr might be missing a kill marker
12806 // because there were multiple uses of EFLAGS, and ISel didn't know
12807 // which to mark. Figure out whether SelectItr should have had a
12808 // kill marker, and set it if it should. Returns the correct kill
12809 // marker value.
12810 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12811                                      MachineBasicBlock* BB,
12812                                      const TargetRegisterInfo* TRI) {
12813   // Scan forward through BB for a use/def of EFLAGS.
12814   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12815   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12816     const MachineInstr& mi = *miI;
12817     if (mi.readsRegister(X86::EFLAGS))
12818       return false;
12819     if (mi.definesRegister(X86::EFLAGS))
12820       break; // Should have kill-flag - update below.
12821   }
12822
12823   // If we hit the end of the block, check whether EFLAGS is live into a
12824   // successor.
12825   if (miI == BB->end()) {
12826     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12827                                           sEnd = BB->succ_end();
12828          sItr != sEnd; ++sItr) {
12829       MachineBasicBlock* succ = *sItr;
12830       if (succ->isLiveIn(X86::EFLAGS))
12831         return false;
12832     }
12833   }
12834
12835   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12836   // out. SelectMI should have a kill flag on EFLAGS.
12837   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12838   return true;
12839 }
12840
12841 MachineBasicBlock *
12842 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12843                                      MachineBasicBlock *BB) const {
12844   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12845   DebugLoc DL = MI->getDebugLoc();
12846
12847   // To "insert" a SELECT_CC instruction, we actually have to insert the
12848   // diamond control-flow pattern.  The incoming instruction knows the
12849   // destination vreg to set, the condition code register to branch on, the
12850   // true/false values to select between, and a branch opcode to use.
12851   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12852   MachineFunction::iterator It = BB;
12853   ++It;
12854
12855   //  thisMBB:
12856   //  ...
12857   //   TrueVal = ...
12858   //   cmpTY ccX, r1, r2
12859   //   bCC copy1MBB
12860   //   fallthrough --> copy0MBB
12861   MachineBasicBlock *thisMBB = BB;
12862   MachineFunction *F = BB->getParent();
12863   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12864   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12865   F->insert(It, copy0MBB);
12866   F->insert(It, sinkMBB);
12867
12868   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12869   // live into the sink and copy blocks.
12870   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12871   if (!MI->killsRegister(X86::EFLAGS) &&
12872       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12873     copy0MBB->addLiveIn(X86::EFLAGS);
12874     sinkMBB->addLiveIn(X86::EFLAGS);
12875   }
12876
12877   // Transfer the remainder of BB and its successor edges to sinkMBB.
12878   sinkMBB->splice(sinkMBB->begin(), BB,
12879                   llvm::next(MachineBasicBlock::iterator(MI)),
12880                   BB->end());
12881   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12882
12883   // Add the true and fallthrough blocks as its successors.
12884   BB->addSuccessor(copy0MBB);
12885   BB->addSuccessor(sinkMBB);
12886
12887   // Create the conditional branch instruction.
12888   unsigned Opc =
12889     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12890   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12891
12892   //  copy0MBB:
12893   //   %FalseValue = ...
12894   //   # fallthrough to sinkMBB
12895   copy0MBB->addSuccessor(sinkMBB);
12896
12897   //  sinkMBB:
12898   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12899   //  ...
12900   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12901           TII->get(X86::PHI), MI->getOperand(0).getReg())
12902     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12903     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12904
12905   MI->eraseFromParent();   // The pseudo instruction is gone now.
12906   return sinkMBB;
12907 }
12908
12909 MachineBasicBlock *
12910 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12911                                         bool Is64Bit) const {
12912   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12913   DebugLoc DL = MI->getDebugLoc();
12914   MachineFunction *MF = BB->getParent();
12915   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12916
12917   assert(getTargetMachine().Options.EnableSegmentedStacks);
12918
12919   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12920   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12921
12922   // BB:
12923   //  ... [Till the alloca]
12924   // If stacklet is not large enough, jump to mallocMBB
12925   //
12926   // bumpMBB:
12927   //  Allocate by subtracting from RSP
12928   //  Jump to continueMBB
12929   //
12930   // mallocMBB:
12931   //  Allocate by call to runtime
12932   //
12933   // continueMBB:
12934   //  ...
12935   //  [rest of original BB]
12936   //
12937
12938   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12939   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12940   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12941
12942   MachineRegisterInfo &MRI = MF->getRegInfo();
12943   const TargetRegisterClass *AddrRegClass =
12944     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12945
12946   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12947     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12948     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12949     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12950     sizeVReg = MI->getOperand(1).getReg(),
12951     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12952
12953   MachineFunction::iterator MBBIter = BB;
12954   ++MBBIter;
12955
12956   MF->insert(MBBIter, bumpMBB);
12957   MF->insert(MBBIter, mallocMBB);
12958   MF->insert(MBBIter, continueMBB);
12959
12960   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12961                       (MachineBasicBlock::iterator(MI)), BB->end());
12962   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12963
12964   // Add code to the main basic block to check if the stack limit has been hit,
12965   // and if so, jump to mallocMBB otherwise to bumpMBB.
12966   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12967   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12968     .addReg(tmpSPVReg).addReg(sizeVReg);
12969   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12970     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12971     .addReg(SPLimitVReg);
12972   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12973
12974   // bumpMBB simply decreases the stack pointer, since we know the current
12975   // stacklet has enough space.
12976   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12977     .addReg(SPLimitVReg);
12978   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12979     .addReg(SPLimitVReg);
12980   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12981
12982   // Calls into a routine in libgcc to allocate more space from the heap.
12983   const uint32_t *RegMask =
12984     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12985   if (Is64Bit) {
12986     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12987       .addReg(sizeVReg);
12988     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12989       .addExternalSymbol("__morestack_allocate_stack_space")
12990       .addRegMask(RegMask)
12991       .addReg(X86::RDI, RegState::Implicit)
12992       .addReg(X86::RAX, RegState::ImplicitDefine);
12993   } else {
12994     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12995       .addImm(12);
12996     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12997     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12998       .addExternalSymbol("__morestack_allocate_stack_space")
12999       .addRegMask(RegMask)
13000       .addReg(X86::EAX, RegState::ImplicitDefine);
13001   }
13002
13003   if (!Is64Bit)
13004     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13005       .addImm(16);
13006
13007   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13008     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13009   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13010
13011   // Set up the CFG correctly.
13012   BB->addSuccessor(bumpMBB);
13013   BB->addSuccessor(mallocMBB);
13014   mallocMBB->addSuccessor(continueMBB);
13015   bumpMBB->addSuccessor(continueMBB);
13016
13017   // Take care of the PHI nodes.
13018   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13019           MI->getOperand(0).getReg())
13020     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13021     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13022
13023   // Delete the original pseudo instruction.
13024   MI->eraseFromParent();
13025
13026   // And we're done.
13027   return continueMBB;
13028 }
13029
13030 MachineBasicBlock *
13031 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13032                                           MachineBasicBlock *BB) const {
13033   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13034   DebugLoc DL = MI->getDebugLoc();
13035
13036   assert(!Subtarget->isTargetEnvMacho());
13037
13038   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13039   // non-trivial part is impdef of ESP.
13040
13041   if (Subtarget->isTargetWin64()) {
13042     if (Subtarget->isTargetCygMing()) {
13043       // ___chkstk(Mingw64):
13044       // Clobbers R10, R11, RAX and EFLAGS.
13045       // Updates RSP.
13046       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13047         .addExternalSymbol("___chkstk")
13048         .addReg(X86::RAX, RegState::Implicit)
13049         .addReg(X86::RSP, RegState::Implicit)
13050         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13051         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13052         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13053     } else {
13054       // __chkstk(MSVCRT): does not update stack pointer.
13055       // Clobbers R10, R11 and EFLAGS.
13056       // FIXME: RAX(allocated size) might be reused and not killed.
13057       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13058         .addExternalSymbol("__chkstk")
13059         .addReg(X86::RAX, RegState::Implicit)
13060         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13061       // RAX has the offset to subtracted from RSP.
13062       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13063         .addReg(X86::RSP)
13064         .addReg(X86::RAX);
13065     }
13066   } else {
13067     const char *StackProbeSymbol =
13068       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13069
13070     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13071       .addExternalSymbol(StackProbeSymbol)
13072       .addReg(X86::EAX, RegState::Implicit)
13073       .addReg(X86::ESP, RegState::Implicit)
13074       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13075       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13076       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13077   }
13078
13079   MI->eraseFromParent();   // The pseudo instruction is gone now.
13080   return BB;
13081 }
13082
13083 MachineBasicBlock *
13084 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13085                                       MachineBasicBlock *BB) const {
13086   // This is pretty easy.  We're taking the value that we received from
13087   // our load from the relocation, sticking it in either RDI (x86-64)
13088   // or EAX and doing an indirect call.  The return value will then
13089   // be in the normal return register.
13090   const X86InstrInfo *TII
13091     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13092   DebugLoc DL = MI->getDebugLoc();
13093   MachineFunction *F = BB->getParent();
13094
13095   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13096   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13097
13098   // Get a register mask for the lowered call.
13099   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13100   // proper register mask.
13101   const uint32_t *RegMask =
13102     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13103   if (Subtarget->is64Bit()) {
13104     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13105                                       TII->get(X86::MOV64rm), X86::RDI)
13106     .addReg(X86::RIP)
13107     .addImm(0).addReg(0)
13108     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13109                       MI->getOperand(3).getTargetFlags())
13110     .addReg(0);
13111     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13112     addDirectMem(MIB, X86::RDI);
13113     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13114   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13115     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13116                                       TII->get(X86::MOV32rm), X86::EAX)
13117     .addReg(0)
13118     .addImm(0).addReg(0)
13119     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13120                       MI->getOperand(3).getTargetFlags())
13121     .addReg(0);
13122     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13123     addDirectMem(MIB, X86::EAX);
13124     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13125   } else {
13126     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13127                                       TII->get(X86::MOV32rm), X86::EAX)
13128     .addReg(TII->getGlobalBaseReg(F))
13129     .addImm(0).addReg(0)
13130     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13131                       MI->getOperand(3).getTargetFlags())
13132     .addReg(0);
13133     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13134     addDirectMem(MIB, X86::EAX);
13135     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13136   }
13137
13138   MI->eraseFromParent(); // The pseudo instruction is gone now.
13139   return BB;
13140 }
13141
13142 MachineBasicBlock *
13143 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13144                                                MachineBasicBlock *BB) const {
13145   switch (MI->getOpcode()) {
13146   default: llvm_unreachable("Unexpected instr type to insert");
13147   case X86::TAILJMPd64:
13148   case X86::TAILJMPr64:
13149   case X86::TAILJMPm64:
13150     llvm_unreachable("TAILJMP64 would not be touched here.");
13151   case X86::TCRETURNdi64:
13152   case X86::TCRETURNri64:
13153   case X86::TCRETURNmi64:
13154     return BB;
13155   case X86::WIN_ALLOCA:
13156     return EmitLoweredWinAlloca(MI, BB);
13157   case X86::SEG_ALLOCA_32:
13158     return EmitLoweredSegAlloca(MI, BB, false);
13159   case X86::SEG_ALLOCA_64:
13160     return EmitLoweredSegAlloca(MI, BB, true);
13161   case X86::TLSCall_32:
13162   case X86::TLSCall_64:
13163     return EmitLoweredTLSCall(MI, BB);
13164   case X86::CMOV_GR8:
13165   case X86::CMOV_FR32:
13166   case X86::CMOV_FR64:
13167   case X86::CMOV_V4F32:
13168   case X86::CMOV_V2F64:
13169   case X86::CMOV_V2I64:
13170   case X86::CMOV_V8F32:
13171   case X86::CMOV_V4F64:
13172   case X86::CMOV_V4I64:
13173   case X86::CMOV_GR16:
13174   case X86::CMOV_GR32:
13175   case X86::CMOV_RFP32:
13176   case X86::CMOV_RFP64:
13177   case X86::CMOV_RFP80:
13178     return EmitLoweredSelect(MI, BB);
13179
13180   case X86::FP32_TO_INT16_IN_MEM:
13181   case X86::FP32_TO_INT32_IN_MEM:
13182   case X86::FP32_TO_INT64_IN_MEM:
13183   case X86::FP64_TO_INT16_IN_MEM:
13184   case X86::FP64_TO_INT32_IN_MEM:
13185   case X86::FP64_TO_INT64_IN_MEM:
13186   case X86::FP80_TO_INT16_IN_MEM:
13187   case X86::FP80_TO_INT32_IN_MEM:
13188   case X86::FP80_TO_INT64_IN_MEM: {
13189     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13190     DebugLoc DL = MI->getDebugLoc();
13191
13192     // Change the floating point control register to use "round towards zero"
13193     // mode when truncating to an integer value.
13194     MachineFunction *F = BB->getParent();
13195     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13196     addFrameReference(BuildMI(*BB, MI, DL,
13197                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13198
13199     // Load the old value of the high byte of the control word...
13200     unsigned OldCW =
13201       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13202     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13203                       CWFrameIdx);
13204
13205     // Set the high part to be round to zero...
13206     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13207       .addImm(0xC7F);
13208
13209     // Reload the modified control word now...
13210     addFrameReference(BuildMI(*BB, MI, DL,
13211                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13212
13213     // Restore the memory image of control word to original value
13214     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13215       .addReg(OldCW);
13216
13217     // Get the X86 opcode to use.
13218     unsigned Opc;
13219     switch (MI->getOpcode()) {
13220     default: llvm_unreachable("illegal opcode!");
13221     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13222     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13223     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13224     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13225     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13226     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13227     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13228     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13229     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13230     }
13231
13232     X86AddressMode AM;
13233     MachineOperand &Op = MI->getOperand(0);
13234     if (Op.isReg()) {
13235       AM.BaseType = X86AddressMode::RegBase;
13236       AM.Base.Reg = Op.getReg();
13237     } else {
13238       AM.BaseType = X86AddressMode::FrameIndexBase;
13239       AM.Base.FrameIndex = Op.getIndex();
13240     }
13241     Op = MI->getOperand(1);
13242     if (Op.isImm())
13243       AM.Scale = Op.getImm();
13244     Op = MI->getOperand(2);
13245     if (Op.isImm())
13246       AM.IndexReg = Op.getImm();
13247     Op = MI->getOperand(3);
13248     if (Op.isGlobal()) {
13249       AM.GV = Op.getGlobal();
13250     } else {
13251       AM.Disp = Op.getImm();
13252     }
13253     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13254                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13255
13256     // Reload the original control word now.
13257     addFrameReference(BuildMI(*BB, MI, DL,
13258                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13259
13260     MI->eraseFromParent();   // The pseudo instruction is gone now.
13261     return BB;
13262   }
13263     // String/text processing lowering.
13264   case X86::PCMPISTRM128REG:
13265   case X86::VPCMPISTRM128REG:
13266   case X86::PCMPISTRM128MEM:
13267   case X86::VPCMPISTRM128MEM:
13268   case X86::PCMPESTRM128REG:
13269   case X86::VPCMPESTRM128REG:
13270   case X86::PCMPESTRM128MEM:
13271   case X86::VPCMPESTRM128MEM: {
13272     unsigned NumArgs;
13273     bool MemArg;
13274     switch (MI->getOpcode()) {
13275     default: llvm_unreachable("illegal opcode!");
13276     case X86::PCMPISTRM128REG:
13277     case X86::VPCMPISTRM128REG:
13278       NumArgs = 3; MemArg = false; break;
13279     case X86::PCMPISTRM128MEM:
13280     case X86::VPCMPISTRM128MEM:
13281       NumArgs = 3; MemArg = true; break;
13282     case X86::PCMPESTRM128REG:
13283     case X86::VPCMPESTRM128REG:
13284       NumArgs = 5; MemArg = false; break;
13285     case X86::PCMPESTRM128MEM:
13286     case X86::VPCMPESTRM128MEM:
13287       NumArgs = 5; MemArg = true; break;
13288     }
13289     return EmitPCMP(MI, BB, NumArgs, MemArg);
13290   }
13291
13292     // Thread synchronization.
13293   case X86::MONITOR:
13294     return EmitMonitor(MI, BB);
13295
13296     // Atomic Lowering.
13297   case X86::ATOMAND8:
13298   case X86::ATOMAND16:
13299   case X86::ATOMAND32:
13300   case X86::ATOMAND64:
13301     // Fall through
13302   case X86::ATOMOR8:
13303   case X86::ATOMOR16:
13304   case X86::ATOMOR32:
13305   case X86::ATOMOR64:
13306     // Fall through
13307   case X86::ATOMXOR16:
13308   case X86::ATOMXOR8:
13309   case X86::ATOMXOR32:
13310   case X86::ATOMXOR64:
13311     // Fall through
13312   case X86::ATOMNAND8:
13313   case X86::ATOMNAND16:
13314   case X86::ATOMNAND32:
13315   case X86::ATOMNAND64:
13316     // Fall through
13317   case X86::ATOMMAX16:
13318   case X86::ATOMMAX32:
13319   case X86::ATOMMAX64:
13320     // Fall through
13321   case X86::ATOMMIN16:
13322   case X86::ATOMMIN32:
13323   case X86::ATOMMIN64:
13324     // Fall through
13325   case X86::ATOMUMAX16:
13326   case X86::ATOMUMAX32:
13327   case X86::ATOMUMAX64:
13328     // Fall through
13329   case X86::ATOMUMIN16:
13330   case X86::ATOMUMIN32:
13331   case X86::ATOMUMIN64:
13332     return EmitAtomicLoadArith(MI, BB);
13333
13334   // This group does 64-bit operations on a 32-bit host.
13335   case X86::ATOMAND6432:
13336   case X86::ATOMOR6432:
13337   case X86::ATOMXOR6432:
13338   case X86::ATOMNAND6432:
13339   case X86::ATOMADD6432:
13340   case X86::ATOMSUB6432:
13341   case X86::ATOMSWAP6432:
13342     return EmitAtomicLoadArith6432(MI, BB);
13343
13344   case X86::VASTART_SAVE_XMM_REGS:
13345     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13346
13347   case X86::VAARG_64:
13348     return EmitVAARG64WithCustomInserter(MI, BB);
13349   }
13350 }
13351
13352 //===----------------------------------------------------------------------===//
13353 //                           X86 Optimization Hooks
13354 //===----------------------------------------------------------------------===//
13355
13356 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13357                                                        APInt &KnownZero,
13358                                                        APInt &KnownOne,
13359                                                        const SelectionDAG &DAG,
13360                                                        unsigned Depth) const {
13361   unsigned BitWidth = KnownZero.getBitWidth();
13362   unsigned Opc = Op.getOpcode();
13363   assert((Opc >= ISD::BUILTIN_OP_END ||
13364           Opc == ISD::INTRINSIC_WO_CHAIN ||
13365           Opc == ISD::INTRINSIC_W_CHAIN ||
13366           Opc == ISD::INTRINSIC_VOID) &&
13367          "Should use MaskedValueIsZero if you don't know whether Op"
13368          " is a target node!");
13369
13370   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13371   switch (Opc) {
13372   default: break;
13373   case X86ISD::ADD:
13374   case X86ISD::SUB:
13375   case X86ISD::ADC:
13376   case X86ISD::SBB:
13377   case X86ISD::SMUL:
13378   case X86ISD::UMUL:
13379   case X86ISD::INC:
13380   case X86ISD::DEC:
13381   case X86ISD::OR:
13382   case X86ISD::XOR:
13383   case X86ISD::AND:
13384     // These nodes' second result is a boolean.
13385     if (Op.getResNo() == 0)
13386       break;
13387     // Fallthrough
13388   case X86ISD::SETCC:
13389     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13390     break;
13391   case ISD::INTRINSIC_WO_CHAIN: {
13392     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13393     unsigned NumLoBits = 0;
13394     switch (IntId) {
13395     default: break;
13396     case Intrinsic::x86_sse_movmsk_ps:
13397     case Intrinsic::x86_avx_movmsk_ps_256:
13398     case Intrinsic::x86_sse2_movmsk_pd:
13399     case Intrinsic::x86_avx_movmsk_pd_256:
13400     case Intrinsic::x86_mmx_pmovmskb:
13401     case Intrinsic::x86_sse2_pmovmskb_128:
13402     case Intrinsic::x86_avx2_pmovmskb: {
13403       // High bits of movmskp{s|d}, pmovmskb are known zero.
13404       switch (IntId) {
13405         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13406         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13407         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13408         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13409         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13410         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13411         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13412         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13413       }
13414       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13415       break;
13416     }
13417     }
13418     break;
13419   }
13420   }
13421 }
13422
13423 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13424                                                          unsigned Depth) const {
13425   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13426   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13427     return Op.getValueType().getScalarType().getSizeInBits();
13428
13429   // Fallback case.
13430   return 1;
13431 }
13432
13433 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13434 /// node is a GlobalAddress + offset.
13435 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13436                                        const GlobalValue* &GA,
13437                                        int64_t &Offset) const {
13438   if (N->getOpcode() == X86ISD::Wrapper) {
13439     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13440       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13441       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13442       return true;
13443     }
13444   }
13445   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13446 }
13447
13448 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13449 /// same as extracting the high 128-bit part of 256-bit vector and then
13450 /// inserting the result into the low part of a new 256-bit vector
13451 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13452   EVT VT = SVOp->getValueType(0);
13453   unsigned NumElems = VT.getVectorNumElements();
13454
13455   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13456   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13457     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13458         SVOp->getMaskElt(j) >= 0)
13459       return false;
13460
13461   return true;
13462 }
13463
13464 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13465 /// same as extracting the low 128-bit part of 256-bit vector and then
13466 /// inserting the result into the high part of a new 256-bit vector
13467 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13468   EVT VT = SVOp->getValueType(0);
13469   unsigned NumElems = VT.getVectorNumElements();
13470
13471   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13472   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13473     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13474         SVOp->getMaskElt(j) >= 0)
13475       return false;
13476
13477   return true;
13478 }
13479
13480 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13481 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13482                                         TargetLowering::DAGCombinerInfo &DCI,
13483                                         const X86Subtarget* Subtarget) {
13484   DebugLoc dl = N->getDebugLoc();
13485   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13486   SDValue V1 = SVOp->getOperand(0);
13487   SDValue V2 = SVOp->getOperand(1);
13488   EVT VT = SVOp->getValueType(0);
13489   unsigned NumElems = VT.getVectorNumElements();
13490
13491   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13492       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13493     //
13494     //                   0,0,0,...
13495     //                      |
13496     //    V      UNDEF    BUILD_VECTOR    UNDEF
13497     //     \      /           \           /
13498     //  CONCAT_VECTOR         CONCAT_VECTOR
13499     //         \                  /
13500     //          \                /
13501     //          RESULT: V + zero extended
13502     //
13503     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13504         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13505         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13506       return SDValue();
13507
13508     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13509       return SDValue();
13510
13511     // To match the shuffle mask, the first half of the mask should
13512     // be exactly the first vector, and all the rest a splat with the
13513     // first element of the second one.
13514     for (unsigned i = 0; i != NumElems/2; ++i)
13515       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13516           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13517         return SDValue();
13518
13519     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13520     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13521       if (Ld->hasNUsesOfValue(1, 0)) {
13522         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13523         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13524         SDValue ResNode =
13525           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13526                                   Ld->getMemoryVT(),
13527                                   Ld->getPointerInfo(),
13528                                   Ld->getAlignment(),
13529                                   false/*isVolatile*/, true/*ReadMem*/,
13530                                   false/*WriteMem*/);
13531         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13532       }
13533     }
13534
13535     // Emit a zeroed vector and insert the desired subvector on its
13536     // first half.
13537     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13538     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13539     return DCI.CombineTo(N, InsV);
13540   }
13541
13542   //===--------------------------------------------------------------------===//
13543   // Combine some shuffles into subvector extracts and inserts:
13544   //
13545
13546   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13547   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13548     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13549     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13550     return DCI.CombineTo(N, InsV);
13551   }
13552
13553   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13554   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13555     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13556     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13557     return DCI.CombineTo(N, InsV);
13558   }
13559
13560   return SDValue();
13561 }
13562
13563 /// PerformShuffleCombine - Performs several different shuffle combines.
13564 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13565                                      TargetLowering::DAGCombinerInfo &DCI,
13566                                      const X86Subtarget *Subtarget) {
13567   DebugLoc dl = N->getDebugLoc();
13568   EVT VT = N->getValueType(0);
13569
13570   // Don't create instructions with illegal types after legalize types has run.
13571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13572   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13573     return SDValue();
13574
13575   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13576   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13577       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13578     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13579
13580   // Only handle 128 wide vector from here on.
13581   if (!VT.is128BitVector())
13582     return SDValue();
13583
13584   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13585   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13586   // consecutive, non-overlapping, and in the right order.
13587   SmallVector<SDValue, 16> Elts;
13588   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13589     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13590
13591   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13592 }
13593
13594
13595 /// PerformTruncateCombine - Converts truncate operation to
13596 /// a sequence of vector shuffle operations.
13597 /// It is possible when we truncate 256-bit vector to 128-bit vector
13598 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13599                                       TargetLowering::DAGCombinerInfo &DCI,
13600                                       const X86Subtarget *Subtarget)  {
13601   if (!DCI.isBeforeLegalizeOps())
13602     return SDValue();
13603
13604   if (!Subtarget->hasAVX())
13605     return SDValue();
13606
13607   EVT VT = N->getValueType(0);
13608   SDValue Op = N->getOperand(0);
13609   EVT OpVT = Op.getValueType();
13610   DebugLoc dl = N->getDebugLoc();
13611
13612   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13613
13614     if (Subtarget->hasAVX2()) {
13615       // AVX2: v4i64 -> v4i32
13616
13617       // VPERMD
13618       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13619
13620       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13621       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13622                                 ShufMask);
13623
13624       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13625                          DAG.getIntPtrConstant(0));
13626     }
13627
13628     // AVX: v4i64 -> v4i32
13629     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13630                                DAG.getIntPtrConstant(0));
13631
13632     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13633                                DAG.getIntPtrConstant(2));
13634
13635     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13636     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13637
13638     // PSHUFD
13639     static const int ShufMask1[] = {0, 2, 0, 0};
13640
13641     SDValue Undef = DAG.getUNDEF(VT);
13642     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13643     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13644
13645     // MOVLHPS
13646     static const int ShufMask2[] = {0, 1, 4, 5};
13647
13648     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13649   }
13650
13651   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13652
13653     if (Subtarget->hasAVX2()) {
13654       // AVX2: v8i32 -> v8i16
13655
13656       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13657
13658       // PSHUFB
13659       SmallVector<SDValue,32> pshufbMask;
13660       for (unsigned i = 0; i < 2; ++i) {
13661         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13662         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13663         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13664         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13665         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13666         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13667         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13668         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13669         for (unsigned j = 0; j < 8; ++j)
13670           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13671       }
13672       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13673                                &pshufbMask[0], 32);
13674       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13675
13676       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13677
13678       static const int ShufMask[] = {0,  2,  -1,  -1};
13679       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13680                                 &ShufMask[0]);
13681
13682       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13683                        DAG.getIntPtrConstant(0));
13684
13685       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13686     }
13687
13688     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13689                                DAG.getIntPtrConstant(0));
13690
13691     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13692                                DAG.getIntPtrConstant(4));
13693
13694     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13695     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13696
13697     // PSHUFB
13698     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13699                                    -1, -1, -1, -1, -1, -1, -1, -1};
13700
13701     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13702     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13703     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13704
13705     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13706     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13707
13708     // MOVLHPS
13709     static const int ShufMask2[] = {0, 1, 4, 5};
13710
13711     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13712     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13713   }
13714
13715   return SDValue();
13716 }
13717
13718 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13719 /// specific shuffle of a load can be folded into a single element load.
13720 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13721 /// shuffles have been customed lowered so we need to handle those here.
13722 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13723                                          TargetLowering::DAGCombinerInfo &DCI) {
13724   if (DCI.isBeforeLegalizeOps())
13725     return SDValue();
13726
13727   SDValue InVec = N->getOperand(0);
13728   SDValue EltNo = N->getOperand(1);
13729
13730   if (!isa<ConstantSDNode>(EltNo))
13731     return SDValue();
13732
13733   EVT VT = InVec.getValueType();
13734
13735   bool HasShuffleIntoBitcast = false;
13736   if (InVec.getOpcode() == ISD::BITCAST) {
13737     // Don't duplicate a load with other uses.
13738     if (!InVec.hasOneUse())
13739       return SDValue();
13740     EVT BCVT = InVec.getOperand(0).getValueType();
13741     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13742       return SDValue();
13743     InVec = InVec.getOperand(0);
13744     HasShuffleIntoBitcast = true;
13745   }
13746
13747   if (!isTargetShuffle(InVec.getOpcode()))
13748     return SDValue();
13749
13750   // Don't duplicate a load with other uses.
13751   if (!InVec.hasOneUse())
13752     return SDValue();
13753
13754   SmallVector<int, 16> ShuffleMask;
13755   bool UnaryShuffle;
13756   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13757                             UnaryShuffle))
13758     return SDValue();
13759
13760   // Select the input vector, guarding against out of range extract vector.
13761   unsigned NumElems = VT.getVectorNumElements();
13762   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13763   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13764   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13765                                          : InVec.getOperand(1);
13766
13767   // If inputs to shuffle are the same for both ops, then allow 2 uses
13768   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13769
13770   if (LdNode.getOpcode() == ISD::BITCAST) {
13771     // Don't duplicate a load with other uses.
13772     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13773       return SDValue();
13774
13775     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13776     LdNode = LdNode.getOperand(0);
13777   }
13778
13779   if (!ISD::isNormalLoad(LdNode.getNode()))
13780     return SDValue();
13781
13782   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13783
13784   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13785     return SDValue();
13786
13787   if (HasShuffleIntoBitcast) {
13788     // If there's a bitcast before the shuffle, check if the load type and
13789     // alignment is valid.
13790     unsigned Align = LN0->getAlignment();
13791     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13792     unsigned NewAlign = TLI.getTargetData()->
13793       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13794
13795     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13796       return SDValue();
13797   }
13798
13799   // All checks match so transform back to vector_shuffle so that DAG combiner
13800   // can finish the job
13801   DebugLoc dl = N->getDebugLoc();
13802
13803   // Create shuffle node taking into account the case that its a unary shuffle
13804   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13805   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13806                                  InVec.getOperand(0), Shuffle,
13807                                  &ShuffleMask[0]);
13808   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13809   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13810                      EltNo);
13811 }
13812
13813 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13814 /// generation and convert it from being a bunch of shuffles and extracts
13815 /// to a simple store and scalar loads to extract the elements.
13816 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13817                                          TargetLowering::DAGCombinerInfo &DCI) {
13818   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13819   if (NewOp.getNode())
13820     return NewOp;
13821
13822   SDValue InputVector = N->getOperand(0);
13823
13824   // Only operate on vectors of 4 elements, where the alternative shuffling
13825   // gets to be more expensive.
13826   if (InputVector.getValueType() != MVT::v4i32)
13827     return SDValue();
13828
13829   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13830   // single use which is a sign-extend or zero-extend, and all elements are
13831   // used.
13832   SmallVector<SDNode *, 4> Uses;
13833   unsigned ExtractedElements = 0;
13834   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13835        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13836     if (UI.getUse().getResNo() != InputVector.getResNo())
13837       return SDValue();
13838
13839     SDNode *Extract = *UI;
13840     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13841       return SDValue();
13842
13843     if (Extract->getValueType(0) != MVT::i32)
13844       return SDValue();
13845     if (!Extract->hasOneUse())
13846       return SDValue();
13847     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13848         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13849       return SDValue();
13850     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13851       return SDValue();
13852
13853     // Record which element was extracted.
13854     ExtractedElements |=
13855       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13856
13857     Uses.push_back(Extract);
13858   }
13859
13860   // If not all the elements were used, this may not be worthwhile.
13861   if (ExtractedElements != 15)
13862     return SDValue();
13863
13864   // Ok, we've now decided to do the transformation.
13865   DebugLoc dl = InputVector.getDebugLoc();
13866
13867   // Store the value to a temporary stack slot.
13868   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13869   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13870                             MachinePointerInfo(), false, false, 0);
13871
13872   // Replace each use (extract) with a load of the appropriate element.
13873   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13874        UE = Uses.end(); UI != UE; ++UI) {
13875     SDNode *Extract = *UI;
13876
13877     // cOMpute the element's address.
13878     SDValue Idx = Extract->getOperand(1);
13879     unsigned EltSize =
13880         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13881     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13882     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13883     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13884
13885     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13886                                      StackPtr, OffsetVal);
13887
13888     // Load the scalar.
13889     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13890                                      ScalarAddr, MachinePointerInfo(),
13891                                      false, false, false, 0);
13892
13893     // Replace the exact with the load.
13894     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13895   }
13896
13897   // The replacement was made in place; don't return anything.
13898   return SDValue();
13899 }
13900
13901 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13902 /// nodes.
13903 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13904                                     TargetLowering::DAGCombinerInfo &DCI,
13905                                     const X86Subtarget *Subtarget) {
13906   DebugLoc DL = N->getDebugLoc();
13907   SDValue Cond = N->getOperand(0);
13908   // Get the LHS/RHS of the select.
13909   SDValue LHS = N->getOperand(1);
13910   SDValue RHS = N->getOperand(2);
13911   EVT VT = LHS.getValueType();
13912
13913   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13914   // instructions match the semantics of the common C idiom x<y?x:y but not
13915   // x<=y?x:y, because of how they handle negative zero (which can be
13916   // ignored in unsafe-math mode).
13917   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13918       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13919       (Subtarget->hasSSE2() ||
13920        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13921     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13922
13923     unsigned Opcode = 0;
13924     // Check for x CC y ? x : y.
13925     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13926         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13927       switch (CC) {
13928       default: break;
13929       case ISD::SETULT:
13930         // Converting this to a min would handle NaNs incorrectly, and swapping
13931         // the operands would cause it to handle comparisons between positive
13932         // and negative zero incorrectly.
13933         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13934           if (!DAG.getTarget().Options.UnsafeFPMath &&
13935               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13936             break;
13937           std::swap(LHS, RHS);
13938         }
13939         Opcode = X86ISD::FMIN;
13940         break;
13941       case ISD::SETOLE:
13942         // Converting this to a min would handle comparisons between positive
13943         // and negative zero incorrectly.
13944         if (!DAG.getTarget().Options.UnsafeFPMath &&
13945             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13946           break;
13947         Opcode = X86ISD::FMIN;
13948         break;
13949       case ISD::SETULE:
13950         // Converting this to a min would handle both negative zeros and NaNs
13951         // incorrectly, but we can swap the operands to fix both.
13952         std::swap(LHS, RHS);
13953       case ISD::SETOLT:
13954       case ISD::SETLT:
13955       case ISD::SETLE:
13956         Opcode = X86ISD::FMIN;
13957         break;
13958
13959       case ISD::SETOGE:
13960         // Converting this to a max would handle comparisons between positive
13961         // and negative zero incorrectly.
13962         if (!DAG.getTarget().Options.UnsafeFPMath &&
13963             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13964           break;
13965         Opcode = X86ISD::FMAX;
13966         break;
13967       case ISD::SETUGT:
13968         // Converting this to a max would handle NaNs incorrectly, and swapping
13969         // the operands would cause it to handle comparisons between positive
13970         // and negative zero incorrectly.
13971         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13972           if (!DAG.getTarget().Options.UnsafeFPMath &&
13973               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13974             break;
13975           std::swap(LHS, RHS);
13976         }
13977         Opcode = X86ISD::FMAX;
13978         break;
13979       case ISD::SETUGE:
13980         // Converting this to a max would handle both negative zeros and NaNs
13981         // incorrectly, but we can swap the operands to fix both.
13982         std::swap(LHS, RHS);
13983       case ISD::SETOGT:
13984       case ISD::SETGT:
13985       case ISD::SETGE:
13986         Opcode = X86ISD::FMAX;
13987         break;
13988       }
13989     // Check for x CC y ? y : x -- a min/max with reversed arms.
13990     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13991                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13992       switch (CC) {
13993       default: break;
13994       case ISD::SETOGE:
13995         // Converting this to a min would handle comparisons between positive
13996         // and negative zero incorrectly, and swapping the operands would
13997         // cause it to handle NaNs incorrectly.
13998         if (!DAG.getTarget().Options.UnsafeFPMath &&
13999             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14000           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14001             break;
14002           std::swap(LHS, RHS);
14003         }
14004         Opcode = X86ISD::FMIN;
14005         break;
14006       case ISD::SETUGT:
14007         // Converting this to a min would handle NaNs incorrectly.
14008         if (!DAG.getTarget().Options.UnsafeFPMath &&
14009             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14010           break;
14011         Opcode = X86ISD::FMIN;
14012         break;
14013       case ISD::SETUGE:
14014         // Converting this to a min would handle both negative zeros and NaNs
14015         // incorrectly, but we can swap the operands to fix both.
14016         std::swap(LHS, RHS);
14017       case ISD::SETOGT:
14018       case ISD::SETGT:
14019       case ISD::SETGE:
14020         Opcode = X86ISD::FMIN;
14021         break;
14022
14023       case ISD::SETULT:
14024         // Converting this to a max would handle NaNs incorrectly.
14025         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14026           break;
14027         Opcode = X86ISD::FMAX;
14028         break;
14029       case ISD::SETOLE:
14030         // Converting this to a max would handle comparisons between positive
14031         // and negative zero incorrectly, and swapping the operands would
14032         // cause it to handle NaNs incorrectly.
14033         if (!DAG.getTarget().Options.UnsafeFPMath &&
14034             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14035           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14036             break;
14037           std::swap(LHS, RHS);
14038         }
14039         Opcode = X86ISD::FMAX;
14040         break;
14041       case ISD::SETULE:
14042         // Converting this to a max would handle both negative zeros and NaNs
14043         // incorrectly, but we can swap the operands to fix both.
14044         std::swap(LHS, RHS);
14045       case ISD::SETOLT:
14046       case ISD::SETLT:
14047       case ISD::SETLE:
14048         Opcode = X86ISD::FMAX;
14049         break;
14050       }
14051     }
14052
14053     if (Opcode)
14054       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14055   }
14056
14057   // If this is a select between two integer constants, try to do some
14058   // optimizations.
14059   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14060     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14061       // Don't do this for crazy integer types.
14062       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14063         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14064         // so that TrueC (the true value) is larger than FalseC.
14065         bool NeedsCondInvert = false;
14066
14067         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14068             // Efficiently invertible.
14069             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14070              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14071               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14072           NeedsCondInvert = true;
14073           std::swap(TrueC, FalseC);
14074         }
14075
14076         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14077         if (FalseC->getAPIntValue() == 0 &&
14078             TrueC->getAPIntValue().isPowerOf2()) {
14079           if (NeedsCondInvert) // Invert the condition if needed.
14080             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14081                                DAG.getConstant(1, Cond.getValueType()));
14082
14083           // Zero extend the condition if needed.
14084           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14085
14086           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14087           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14088                              DAG.getConstant(ShAmt, MVT::i8));
14089         }
14090
14091         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14092         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14093           if (NeedsCondInvert) // Invert the condition if needed.
14094             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14095                                DAG.getConstant(1, Cond.getValueType()));
14096
14097           // Zero extend the condition if needed.
14098           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14099                              FalseC->getValueType(0), Cond);
14100           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14101                              SDValue(FalseC, 0));
14102         }
14103
14104         // Optimize cases that will turn into an LEA instruction.  This requires
14105         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14106         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14107           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14108           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14109
14110           bool isFastMultiplier = false;
14111           if (Diff < 10) {
14112             switch ((unsigned char)Diff) {
14113               default: break;
14114               case 1:  // result = add base, cond
14115               case 2:  // result = lea base(    , cond*2)
14116               case 3:  // result = lea base(cond, cond*2)
14117               case 4:  // result = lea base(    , cond*4)
14118               case 5:  // result = lea base(cond, cond*4)
14119               case 8:  // result = lea base(    , cond*8)
14120               case 9:  // result = lea base(cond, cond*8)
14121                 isFastMultiplier = true;
14122                 break;
14123             }
14124           }
14125
14126           if (isFastMultiplier) {
14127             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14128             if (NeedsCondInvert) // Invert the condition if needed.
14129               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14130                                  DAG.getConstant(1, Cond.getValueType()));
14131
14132             // Zero extend the condition if needed.
14133             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14134                                Cond);
14135             // Scale the condition by the difference.
14136             if (Diff != 1)
14137               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14138                                  DAG.getConstant(Diff, Cond.getValueType()));
14139
14140             // Add the base if non-zero.
14141             if (FalseC->getAPIntValue() != 0)
14142               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14143                                  SDValue(FalseC, 0));
14144             return Cond;
14145           }
14146         }
14147       }
14148   }
14149
14150   // Canonicalize max and min:
14151   // (x > y) ? x : y -> (x >= y) ? x : y
14152   // (x < y) ? x : y -> (x <= y) ? x : y
14153   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14154   // the need for an extra compare
14155   // against zero. e.g.
14156   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14157   // subl   %esi, %edi
14158   // testl  %edi, %edi
14159   // movl   $0, %eax
14160   // cmovgl %edi, %eax
14161   // =>
14162   // xorl   %eax, %eax
14163   // subl   %esi, $edi
14164   // cmovsl %eax, %edi
14165   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14166       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14167       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14168     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14169     switch (CC) {
14170     default: break;
14171     case ISD::SETLT:
14172     case ISD::SETGT: {
14173       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14174       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14175                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14176       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14177     }
14178     }
14179   }
14180
14181   // If we know that this node is legal then we know that it is going to be
14182   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14183   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14184   // to simplify previous instructions.
14185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14186   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14187       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14188     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14189
14190     // Don't optimize vector selects that map to mask-registers.
14191     if (BitWidth == 1)
14192       return SDValue();
14193
14194     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14195     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14196
14197     APInt KnownZero, KnownOne;
14198     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14199                                           DCI.isBeforeLegalizeOps());
14200     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14201         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14202       DCI.CommitTargetLoweringOpt(TLO);
14203   }
14204
14205   return SDValue();
14206 }
14207
14208 // Check whether a boolean test is testing a boolean value generated by
14209 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14210 // code.
14211 //
14212 // Simplify the following patterns:
14213 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14214 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14215 // to (Op EFLAGS Cond)
14216 //
14217 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14218 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14219 // to (Op EFLAGS !Cond)
14220 //
14221 // where Op could be BRCOND or CMOV.
14222 //
14223 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14224   // Quit if not CMP and SUB with its value result used.
14225   if (Cmp.getOpcode() != X86ISD::CMP &&
14226       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14227       return SDValue();
14228
14229   // Quit if not used as a boolean value.
14230   if (CC != X86::COND_E && CC != X86::COND_NE)
14231     return SDValue();
14232
14233   // Check CMP operands. One of them should be 0 or 1 and the other should be
14234   // an SetCC or extended from it.
14235   SDValue Op1 = Cmp.getOperand(0);
14236   SDValue Op2 = Cmp.getOperand(1);
14237
14238   SDValue SetCC;
14239   const ConstantSDNode* C = 0;
14240   bool needOppositeCond = (CC == X86::COND_E);
14241
14242   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14243     SetCC = Op2;
14244   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14245     SetCC = Op1;
14246   else // Quit if all operands are not constants.
14247     return SDValue();
14248
14249   if (C->getZExtValue() == 1)
14250     needOppositeCond = !needOppositeCond;
14251   else if (C->getZExtValue() != 0)
14252     // Quit if the constant is neither 0 or 1.
14253     return SDValue();
14254
14255   // Skip 'zext' node.
14256   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14257     SetCC = SetCC.getOperand(0);
14258
14259   switch (SetCC.getOpcode()) {
14260   case X86ISD::SETCC:
14261     // Set the condition code or opposite one if necessary.
14262     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14263     if (needOppositeCond)
14264       CC = X86::GetOppositeBranchCondition(CC);
14265     return SetCC.getOperand(1);
14266   case X86ISD::CMOV: {
14267     // Check whether false/true value has canonical one, i.e. 0 or 1.
14268     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14269     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14270     // Quit if true value is not a constant.
14271     if (!TVal)
14272       return SDValue();
14273     // Quit if false value is not a constant.
14274     if (!FVal) {
14275       // A special case for rdrand, where 0 is set if false cond is found.
14276       SDValue Op = SetCC.getOperand(0);
14277       if (Op.getOpcode() != X86ISD::RDRAND)
14278         return SDValue();
14279     }
14280     // Quit if false value is not the constant 0 or 1.
14281     bool FValIsFalse = true;
14282     if (FVal && FVal->getZExtValue() != 0) {
14283       if (FVal->getZExtValue() != 1)
14284         return SDValue();
14285       // If FVal is 1, opposite cond is needed.
14286       needOppositeCond = !needOppositeCond;
14287       FValIsFalse = false;
14288     }
14289     // Quit if TVal is not the constant opposite of FVal.
14290     if (FValIsFalse && TVal->getZExtValue() != 1)
14291       return SDValue();
14292     if (!FValIsFalse && TVal->getZExtValue() != 0)
14293       return SDValue();
14294     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14295     if (needOppositeCond)
14296       CC = X86::GetOppositeBranchCondition(CC);
14297     return SetCC.getOperand(3);
14298   }
14299   }
14300
14301   return SDValue();
14302 }
14303
14304 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14305 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14306                                   TargetLowering::DAGCombinerInfo &DCI,
14307                                   const X86Subtarget *Subtarget) {
14308   DebugLoc DL = N->getDebugLoc();
14309
14310   // If the flag operand isn't dead, don't touch this CMOV.
14311   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14312     return SDValue();
14313
14314   SDValue FalseOp = N->getOperand(0);
14315   SDValue TrueOp = N->getOperand(1);
14316   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14317   SDValue Cond = N->getOperand(3);
14318
14319   if (CC == X86::COND_E || CC == X86::COND_NE) {
14320     switch (Cond.getOpcode()) {
14321     default: break;
14322     case X86ISD::BSR:
14323     case X86ISD::BSF:
14324       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14325       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14326         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14327     }
14328   }
14329
14330   SDValue Flags;
14331
14332   Flags = checkBoolTestSetCCCombine(Cond, CC);
14333   if (Flags.getNode() &&
14334       // Extra check as FCMOV only supports a subset of X86 cond.
14335       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14336     SDValue Ops[] = { FalseOp, TrueOp,
14337                       DAG.getConstant(CC, MVT::i8), Flags };
14338     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14339                        Ops, array_lengthof(Ops));
14340   }
14341
14342   // If this is a select between two integer constants, try to do some
14343   // optimizations.  Note that the operands are ordered the opposite of SELECT
14344   // operands.
14345   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14346     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14347       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14348       // larger than FalseC (the false value).
14349       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14350         CC = X86::GetOppositeBranchCondition(CC);
14351         std::swap(TrueC, FalseC);
14352       }
14353
14354       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14355       // This is efficient for any integer data type (including i8/i16) and
14356       // shift amount.
14357       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14358         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14359                            DAG.getConstant(CC, MVT::i8), Cond);
14360
14361         // Zero extend the condition if needed.
14362         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14363
14364         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14365         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14366                            DAG.getConstant(ShAmt, MVT::i8));
14367         if (N->getNumValues() == 2)  // Dead flag value?
14368           return DCI.CombineTo(N, Cond, SDValue());
14369         return Cond;
14370       }
14371
14372       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14373       // for any integer data type, including i8/i16.
14374       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14375         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14376                            DAG.getConstant(CC, MVT::i8), Cond);
14377
14378         // Zero extend the condition if needed.
14379         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14380                            FalseC->getValueType(0), Cond);
14381         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14382                            SDValue(FalseC, 0));
14383
14384         if (N->getNumValues() == 2)  // Dead flag value?
14385           return DCI.CombineTo(N, Cond, SDValue());
14386         return Cond;
14387       }
14388
14389       // Optimize cases that will turn into an LEA instruction.  This requires
14390       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14391       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14392         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14393         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14394
14395         bool isFastMultiplier = false;
14396         if (Diff < 10) {
14397           switch ((unsigned char)Diff) {
14398           default: break;
14399           case 1:  // result = add base, cond
14400           case 2:  // result = lea base(    , cond*2)
14401           case 3:  // result = lea base(cond, cond*2)
14402           case 4:  // result = lea base(    , cond*4)
14403           case 5:  // result = lea base(cond, cond*4)
14404           case 8:  // result = lea base(    , cond*8)
14405           case 9:  // result = lea base(cond, cond*8)
14406             isFastMultiplier = true;
14407             break;
14408           }
14409         }
14410
14411         if (isFastMultiplier) {
14412           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14413           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14414                              DAG.getConstant(CC, MVT::i8), Cond);
14415           // Zero extend the condition if needed.
14416           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14417                              Cond);
14418           // Scale the condition by the difference.
14419           if (Diff != 1)
14420             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14421                                DAG.getConstant(Diff, Cond.getValueType()));
14422
14423           // Add the base if non-zero.
14424           if (FalseC->getAPIntValue() != 0)
14425             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14426                                SDValue(FalseC, 0));
14427           if (N->getNumValues() == 2)  // Dead flag value?
14428             return DCI.CombineTo(N, Cond, SDValue());
14429           return Cond;
14430         }
14431       }
14432     }
14433   }
14434   return SDValue();
14435 }
14436
14437
14438 /// PerformMulCombine - Optimize a single multiply with constant into two
14439 /// in order to implement it with two cheaper instructions, e.g.
14440 /// LEA + SHL, LEA + LEA.
14441 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14442                                  TargetLowering::DAGCombinerInfo &DCI) {
14443   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14444     return SDValue();
14445
14446   EVT VT = N->getValueType(0);
14447   if (VT != MVT::i64)
14448     return SDValue();
14449
14450   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14451   if (!C)
14452     return SDValue();
14453   uint64_t MulAmt = C->getZExtValue();
14454   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14455     return SDValue();
14456
14457   uint64_t MulAmt1 = 0;
14458   uint64_t MulAmt2 = 0;
14459   if ((MulAmt % 9) == 0) {
14460     MulAmt1 = 9;
14461     MulAmt2 = MulAmt / 9;
14462   } else if ((MulAmt % 5) == 0) {
14463     MulAmt1 = 5;
14464     MulAmt2 = MulAmt / 5;
14465   } else if ((MulAmt % 3) == 0) {
14466     MulAmt1 = 3;
14467     MulAmt2 = MulAmt / 3;
14468   }
14469   if (MulAmt2 &&
14470       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14471     DebugLoc DL = N->getDebugLoc();
14472
14473     if (isPowerOf2_64(MulAmt2) &&
14474         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14475       // If second multiplifer is pow2, issue it first. We want the multiply by
14476       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14477       // is an add.
14478       std::swap(MulAmt1, MulAmt2);
14479
14480     SDValue NewMul;
14481     if (isPowerOf2_64(MulAmt1))
14482       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14483                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14484     else
14485       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14486                            DAG.getConstant(MulAmt1, VT));
14487
14488     if (isPowerOf2_64(MulAmt2))
14489       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14490                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14491     else
14492       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14493                            DAG.getConstant(MulAmt2, VT));
14494
14495     // Do not add new nodes to DAG combiner worklist.
14496     DCI.CombineTo(N, NewMul, false);
14497   }
14498   return SDValue();
14499 }
14500
14501 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14502   SDValue N0 = N->getOperand(0);
14503   SDValue N1 = N->getOperand(1);
14504   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14505   EVT VT = N0.getValueType();
14506
14507   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14508   // since the result of setcc_c is all zero's or all ones.
14509   if (VT.isInteger() && !VT.isVector() &&
14510       N1C && N0.getOpcode() == ISD::AND &&
14511       N0.getOperand(1).getOpcode() == ISD::Constant) {
14512     SDValue N00 = N0.getOperand(0);
14513     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14514         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14515           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14516          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14517       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14518       APInt ShAmt = N1C->getAPIntValue();
14519       Mask = Mask.shl(ShAmt);
14520       if (Mask != 0)
14521         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14522                            N00, DAG.getConstant(Mask, VT));
14523     }
14524   }
14525
14526
14527   // Hardware support for vector shifts is sparse which makes us scalarize the
14528   // vector operations in many cases. Also, on sandybridge ADD is faster than
14529   // shl.
14530   // (shl V, 1) -> add V,V
14531   if (isSplatVector(N1.getNode())) {
14532     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14533     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14534     // We shift all of the values by one. In many cases we do not have
14535     // hardware support for this operation. This is better expressed as an ADD
14536     // of two values.
14537     if (N1C && (1 == N1C->getZExtValue())) {
14538       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14539     }
14540   }
14541
14542   return SDValue();
14543 }
14544
14545 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14546 ///                       when possible.
14547 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14548                                    TargetLowering::DAGCombinerInfo &DCI,
14549                                    const X86Subtarget *Subtarget) {
14550   EVT VT = N->getValueType(0);
14551   if (N->getOpcode() == ISD::SHL) {
14552     SDValue V = PerformSHLCombine(N, DAG);
14553     if (V.getNode()) return V;
14554   }
14555
14556   // On X86 with SSE2 support, we can transform this to a vector shift if
14557   // all elements are shifted by the same amount.  We can't do this in legalize
14558   // because the a constant vector is typically transformed to a constant pool
14559   // so we have no knowledge of the shift amount.
14560   if (!Subtarget->hasSSE2())
14561     return SDValue();
14562
14563   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14564       (!Subtarget->hasAVX2() ||
14565        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14566     return SDValue();
14567
14568   SDValue ShAmtOp = N->getOperand(1);
14569   EVT EltVT = VT.getVectorElementType();
14570   DebugLoc DL = N->getDebugLoc();
14571   SDValue BaseShAmt = SDValue();
14572   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14573     unsigned NumElts = VT.getVectorNumElements();
14574     unsigned i = 0;
14575     for (; i != NumElts; ++i) {
14576       SDValue Arg = ShAmtOp.getOperand(i);
14577       if (Arg.getOpcode() == ISD::UNDEF) continue;
14578       BaseShAmt = Arg;
14579       break;
14580     }
14581     // Handle the case where the build_vector is all undef
14582     // FIXME: Should DAG allow this?
14583     if (i == NumElts)
14584       return SDValue();
14585
14586     for (; i != NumElts; ++i) {
14587       SDValue Arg = ShAmtOp.getOperand(i);
14588       if (Arg.getOpcode() == ISD::UNDEF) continue;
14589       if (Arg != BaseShAmt) {
14590         return SDValue();
14591       }
14592     }
14593   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14594              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14595     SDValue InVec = ShAmtOp.getOperand(0);
14596     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14597       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14598       unsigned i = 0;
14599       for (; i != NumElts; ++i) {
14600         SDValue Arg = InVec.getOperand(i);
14601         if (Arg.getOpcode() == ISD::UNDEF) continue;
14602         BaseShAmt = Arg;
14603         break;
14604       }
14605     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14606        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14607          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14608          if (C->getZExtValue() == SplatIdx)
14609            BaseShAmt = InVec.getOperand(1);
14610        }
14611     }
14612     if (BaseShAmt.getNode() == 0) {
14613       // Don't create instructions with illegal types after legalize
14614       // types has run.
14615       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14616           !DCI.isBeforeLegalize())
14617         return SDValue();
14618
14619       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14620                               DAG.getIntPtrConstant(0));
14621     }
14622   } else
14623     return SDValue();
14624
14625   // The shift amount is an i32.
14626   if (EltVT.bitsGT(MVT::i32))
14627     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14628   else if (EltVT.bitsLT(MVT::i32))
14629     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14630
14631   // The shift amount is identical so we can do a vector shift.
14632   SDValue  ValOp = N->getOperand(0);
14633   switch (N->getOpcode()) {
14634   default:
14635     llvm_unreachable("Unknown shift opcode!");
14636   case ISD::SHL:
14637     switch (VT.getSimpleVT().SimpleTy) {
14638     default: return SDValue();
14639     case MVT::v2i64:
14640     case MVT::v4i32:
14641     case MVT::v8i16:
14642     case MVT::v4i64:
14643     case MVT::v8i32:
14644     case MVT::v16i16:
14645       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14646     }
14647   case ISD::SRA:
14648     switch (VT.getSimpleVT().SimpleTy) {
14649     default: return SDValue();
14650     case MVT::v4i32:
14651     case MVT::v8i16:
14652     case MVT::v8i32:
14653     case MVT::v16i16:
14654       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14655     }
14656   case ISD::SRL:
14657     switch (VT.getSimpleVT().SimpleTy) {
14658     default: return SDValue();
14659     case MVT::v2i64:
14660     case MVT::v4i32:
14661     case MVT::v8i16:
14662     case MVT::v4i64:
14663     case MVT::v8i32:
14664     case MVT::v16i16:
14665       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14666     }
14667   }
14668 }
14669
14670
14671 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14672 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14673 // and friends.  Likewise for OR -> CMPNEQSS.
14674 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14675                             TargetLowering::DAGCombinerInfo &DCI,
14676                             const X86Subtarget *Subtarget) {
14677   unsigned opcode;
14678
14679   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14680   // we're requiring SSE2 for both.
14681   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14682     SDValue N0 = N->getOperand(0);
14683     SDValue N1 = N->getOperand(1);
14684     SDValue CMP0 = N0->getOperand(1);
14685     SDValue CMP1 = N1->getOperand(1);
14686     DebugLoc DL = N->getDebugLoc();
14687
14688     // The SETCCs should both refer to the same CMP.
14689     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14690       return SDValue();
14691
14692     SDValue CMP00 = CMP0->getOperand(0);
14693     SDValue CMP01 = CMP0->getOperand(1);
14694     EVT     VT    = CMP00.getValueType();
14695
14696     if (VT == MVT::f32 || VT == MVT::f64) {
14697       bool ExpectingFlags = false;
14698       // Check for any users that want flags:
14699       for (SDNode::use_iterator UI = N->use_begin(),
14700              UE = N->use_end();
14701            !ExpectingFlags && UI != UE; ++UI)
14702         switch (UI->getOpcode()) {
14703         default:
14704         case ISD::BR_CC:
14705         case ISD::BRCOND:
14706         case ISD::SELECT:
14707           ExpectingFlags = true;
14708           break;
14709         case ISD::CopyToReg:
14710         case ISD::SIGN_EXTEND:
14711         case ISD::ZERO_EXTEND:
14712         case ISD::ANY_EXTEND:
14713           break;
14714         }
14715
14716       if (!ExpectingFlags) {
14717         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14718         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14719
14720         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14721           X86::CondCode tmp = cc0;
14722           cc0 = cc1;
14723           cc1 = tmp;
14724         }
14725
14726         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14727             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14728           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14729           X86ISD::NodeType NTOperator = is64BitFP ?
14730             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14731           // FIXME: need symbolic constants for these magic numbers.
14732           // See X86ATTInstPrinter.cpp:printSSECC().
14733           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14734           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14735                                               DAG.getConstant(x86cc, MVT::i8));
14736           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14737                                               OnesOrZeroesF);
14738           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14739                                       DAG.getConstant(1, MVT::i32));
14740           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14741           return OneBitOfTruth;
14742         }
14743       }
14744     }
14745   }
14746   return SDValue();
14747 }
14748
14749 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14750 /// so it can be folded inside ANDNP.
14751 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14752   EVT VT = N->getValueType(0);
14753
14754   // Match direct AllOnes for 128 and 256-bit vectors
14755   if (ISD::isBuildVectorAllOnes(N))
14756     return true;
14757
14758   // Look through a bit convert.
14759   if (N->getOpcode() == ISD::BITCAST)
14760     N = N->getOperand(0).getNode();
14761
14762   // Sometimes the operand may come from a insert_subvector building a 256-bit
14763   // allones vector
14764   if (VT.is256BitVector() &&
14765       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14766     SDValue V1 = N->getOperand(0);
14767     SDValue V2 = N->getOperand(1);
14768
14769     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14770         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14771         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14772         ISD::isBuildVectorAllOnes(V2.getNode()))
14773       return true;
14774   }
14775
14776   return false;
14777 }
14778
14779 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14780                                  TargetLowering::DAGCombinerInfo &DCI,
14781                                  const X86Subtarget *Subtarget) {
14782   if (DCI.isBeforeLegalizeOps())
14783     return SDValue();
14784
14785   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14786   if (R.getNode())
14787     return R;
14788
14789   EVT VT = N->getValueType(0);
14790
14791   // Create ANDN, BLSI, and BLSR instructions
14792   // BLSI is X & (-X)
14793   // BLSR is X & (X-1)
14794   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14795     SDValue N0 = N->getOperand(0);
14796     SDValue N1 = N->getOperand(1);
14797     DebugLoc DL = N->getDebugLoc();
14798
14799     // Check LHS for not
14800     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14801       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14802     // Check RHS for not
14803     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14804       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14805
14806     // Check LHS for neg
14807     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14808         isZero(N0.getOperand(0)))
14809       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14810
14811     // Check RHS for neg
14812     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14813         isZero(N1.getOperand(0)))
14814       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14815
14816     // Check LHS for X-1
14817     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14818         isAllOnes(N0.getOperand(1)))
14819       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14820
14821     // Check RHS for X-1
14822     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14823         isAllOnes(N1.getOperand(1)))
14824       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14825
14826     return SDValue();
14827   }
14828
14829   // Want to form ANDNP nodes:
14830   // 1) In the hopes of then easily combining them with OR and AND nodes
14831   //    to form PBLEND/PSIGN.
14832   // 2) To match ANDN packed intrinsics
14833   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14834     return SDValue();
14835
14836   SDValue N0 = N->getOperand(0);
14837   SDValue N1 = N->getOperand(1);
14838   DebugLoc DL = N->getDebugLoc();
14839
14840   // Check LHS for vnot
14841   if (N0.getOpcode() == ISD::XOR &&
14842       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14843       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14844     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14845
14846   // Check RHS for vnot
14847   if (N1.getOpcode() == ISD::XOR &&
14848       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14849       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14850     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14851
14852   return SDValue();
14853 }
14854
14855 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14856                                 TargetLowering::DAGCombinerInfo &DCI,
14857                                 const X86Subtarget *Subtarget) {
14858   if (DCI.isBeforeLegalizeOps())
14859     return SDValue();
14860
14861   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14862   if (R.getNode())
14863     return R;
14864
14865   EVT VT = N->getValueType(0);
14866
14867   SDValue N0 = N->getOperand(0);
14868   SDValue N1 = N->getOperand(1);
14869
14870   // look for psign/blend
14871   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14872     if (!Subtarget->hasSSSE3() ||
14873         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14874       return SDValue();
14875
14876     // Canonicalize pandn to RHS
14877     if (N0.getOpcode() == X86ISD::ANDNP)
14878       std::swap(N0, N1);
14879     // or (and (m, y), (pandn m, x))
14880     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14881       SDValue Mask = N1.getOperand(0);
14882       SDValue X    = N1.getOperand(1);
14883       SDValue Y;
14884       if (N0.getOperand(0) == Mask)
14885         Y = N0.getOperand(1);
14886       if (N0.getOperand(1) == Mask)
14887         Y = N0.getOperand(0);
14888
14889       // Check to see if the mask appeared in both the AND and ANDNP and
14890       if (!Y.getNode())
14891         return SDValue();
14892
14893       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14894       // Look through mask bitcast.
14895       if (Mask.getOpcode() == ISD::BITCAST)
14896         Mask = Mask.getOperand(0);
14897       if (X.getOpcode() == ISD::BITCAST)
14898         X = X.getOperand(0);
14899       if (Y.getOpcode() == ISD::BITCAST)
14900         Y = Y.getOperand(0);
14901
14902       EVT MaskVT = Mask.getValueType();
14903
14904       // Validate that the Mask operand is a vector sra node.
14905       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14906       // there is no psrai.b
14907       if (Mask.getOpcode() != X86ISD::VSRAI)
14908         return SDValue();
14909
14910       // Check that the SRA is all signbits.
14911       SDValue SraC = Mask.getOperand(1);
14912       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14913       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14914       if ((SraAmt + 1) != EltBits)
14915         return SDValue();
14916
14917       DebugLoc DL = N->getDebugLoc();
14918
14919       // Now we know we at least have a plendvb with the mask val.  See if
14920       // we can form a psignb/w/d.
14921       // psign = x.type == y.type == mask.type && y = sub(0, x);
14922       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14923           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14924           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14925         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14926                "Unsupported VT for PSIGN");
14927         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14928         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14929       }
14930       // PBLENDVB only available on SSE 4.1
14931       if (!Subtarget->hasSSE41())
14932         return SDValue();
14933
14934       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14935
14936       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14937       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14938       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14939       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14940       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14941     }
14942   }
14943
14944   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14945     return SDValue();
14946
14947   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14948   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14949     std::swap(N0, N1);
14950   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14951     return SDValue();
14952   if (!N0.hasOneUse() || !N1.hasOneUse())
14953     return SDValue();
14954
14955   SDValue ShAmt0 = N0.getOperand(1);
14956   if (ShAmt0.getValueType() != MVT::i8)
14957     return SDValue();
14958   SDValue ShAmt1 = N1.getOperand(1);
14959   if (ShAmt1.getValueType() != MVT::i8)
14960     return SDValue();
14961   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14962     ShAmt0 = ShAmt0.getOperand(0);
14963   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14964     ShAmt1 = ShAmt1.getOperand(0);
14965
14966   DebugLoc DL = N->getDebugLoc();
14967   unsigned Opc = X86ISD::SHLD;
14968   SDValue Op0 = N0.getOperand(0);
14969   SDValue Op1 = N1.getOperand(0);
14970   if (ShAmt0.getOpcode() == ISD::SUB) {
14971     Opc = X86ISD::SHRD;
14972     std::swap(Op0, Op1);
14973     std::swap(ShAmt0, ShAmt1);
14974   }
14975
14976   unsigned Bits = VT.getSizeInBits();
14977   if (ShAmt1.getOpcode() == ISD::SUB) {
14978     SDValue Sum = ShAmt1.getOperand(0);
14979     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14980       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14981       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14982         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14983       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14984         return DAG.getNode(Opc, DL, VT,
14985                            Op0, Op1,
14986                            DAG.getNode(ISD::TRUNCATE, DL,
14987                                        MVT::i8, ShAmt0));
14988     }
14989   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14990     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14991     if (ShAmt0C &&
14992         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14993       return DAG.getNode(Opc, DL, VT,
14994                          N0.getOperand(0), N1.getOperand(0),
14995                          DAG.getNode(ISD::TRUNCATE, DL,
14996                                        MVT::i8, ShAmt0));
14997   }
14998
14999   return SDValue();
15000 }
15001
15002 // Generate NEG and CMOV for integer abs.
15003 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15004   EVT VT = N->getValueType(0);
15005
15006   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15007   // 8-bit integer abs to NEG and CMOV.
15008   if (VT.isInteger() && VT.getSizeInBits() == 8)
15009     return SDValue();
15010
15011   SDValue N0 = N->getOperand(0);
15012   SDValue N1 = N->getOperand(1);
15013   DebugLoc DL = N->getDebugLoc();
15014
15015   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15016   // and change it to SUB and CMOV.
15017   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15018       N0.getOpcode() == ISD::ADD &&
15019       N0.getOperand(1) == N1 &&
15020       N1.getOpcode() == ISD::SRA &&
15021       N1.getOperand(0) == N0.getOperand(0))
15022     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15023       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15024         // Generate SUB & CMOV.
15025         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15026                                   DAG.getConstant(0, VT), N0.getOperand(0));
15027
15028         SDValue Ops[] = { N0.getOperand(0), Neg,
15029                           DAG.getConstant(X86::COND_GE, MVT::i8),
15030                           SDValue(Neg.getNode(), 1) };
15031         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15032                            Ops, array_lengthof(Ops));
15033       }
15034   return SDValue();
15035 }
15036
15037 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15038 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15039                                  TargetLowering::DAGCombinerInfo &DCI,
15040                                  const X86Subtarget *Subtarget) {
15041   if (DCI.isBeforeLegalizeOps())
15042     return SDValue();
15043
15044   if (Subtarget->hasCMov()) {
15045     SDValue RV = performIntegerAbsCombine(N, DAG);
15046     if (RV.getNode())
15047       return RV;
15048   }
15049
15050   // Try forming BMI if it is available.
15051   if (!Subtarget->hasBMI())
15052     return SDValue();
15053
15054   EVT VT = N->getValueType(0);
15055
15056   if (VT != MVT::i32 && VT != MVT::i64)
15057     return SDValue();
15058
15059   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15060
15061   // Create BLSMSK instructions by finding X ^ (X-1)
15062   SDValue N0 = N->getOperand(0);
15063   SDValue N1 = N->getOperand(1);
15064   DebugLoc DL = N->getDebugLoc();
15065
15066   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15067       isAllOnes(N0.getOperand(1)))
15068     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15069
15070   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15071       isAllOnes(N1.getOperand(1)))
15072     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15073
15074   return SDValue();
15075 }
15076
15077 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15078 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15079                                   TargetLowering::DAGCombinerInfo &DCI,
15080                                   const X86Subtarget *Subtarget) {
15081   LoadSDNode *Ld = cast<LoadSDNode>(N);
15082   EVT RegVT = Ld->getValueType(0);
15083   EVT MemVT = Ld->getMemoryVT();
15084   DebugLoc dl = Ld->getDebugLoc();
15085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15086
15087   ISD::LoadExtType Ext = Ld->getExtensionType();
15088
15089   // If this is a vector EXT Load then attempt to optimize it using a
15090   // shuffle. We need SSE4 for the shuffles.
15091   // TODO: It is possible to support ZExt by zeroing the undef values
15092   // during the shuffle phase or after the shuffle.
15093   if (RegVT.isVector() && RegVT.isInteger() &&
15094       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15095     assert(MemVT != RegVT && "Cannot extend to the same type");
15096     assert(MemVT.isVector() && "Must load a vector from memory");
15097
15098     unsigned NumElems = RegVT.getVectorNumElements();
15099     unsigned RegSz = RegVT.getSizeInBits();
15100     unsigned MemSz = MemVT.getSizeInBits();
15101     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15102
15103     // All sizes must be a power of two.
15104     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15105       return SDValue();
15106
15107     // Attempt to load the original value using scalar loads.
15108     // Find the largest scalar type that divides the total loaded size.
15109     MVT SclrLoadTy = MVT::i8;
15110     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15111          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15112       MVT Tp = (MVT::SimpleValueType)tp;
15113       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15114         SclrLoadTy = Tp;
15115       }
15116     }
15117
15118     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15119     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15120         (64 <= MemSz))
15121       SclrLoadTy = MVT::f64;
15122
15123     // Calculate the number of scalar loads that we need to perform
15124     // in order to load our vector from memory.
15125     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15126
15127     // Represent our vector as a sequence of elements which are the
15128     // largest scalar that we can load.
15129     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15130       RegSz/SclrLoadTy.getSizeInBits());
15131
15132     // Represent the data using the same element type that is stored in
15133     // memory. In practice, we ''widen'' MemVT.
15134     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15135                                   RegSz/MemVT.getScalarType().getSizeInBits());
15136
15137     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15138       "Invalid vector type");
15139
15140     // We can't shuffle using an illegal type.
15141     if (!TLI.isTypeLegal(WideVecVT))
15142       return SDValue();
15143
15144     SmallVector<SDValue, 8> Chains;
15145     SDValue Ptr = Ld->getBasePtr();
15146     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15147                                         TLI.getPointerTy());
15148     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15149
15150     for (unsigned i = 0; i < NumLoads; ++i) {
15151       // Perform a single load.
15152       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15153                                        Ptr, Ld->getPointerInfo(),
15154                                        Ld->isVolatile(), Ld->isNonTemporal(),
15155                                        Ld->isInvariant(), Ld->getAlignment());
15156       Chains.push_back(ScalarLoad.getValue(1));
15157       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15158       // another round of DAGCombining.
15159       if (i == 0)
15160         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15161       else
15162         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15163                           ScalarLoad, DAG.getIntPtrConstant(i));
15164
15165       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15166     }
15167
15168     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15169                                Chains.size());
15170
15171     // Bitcast the loaded value to a vector of the original element type, in
15172     // the size of the target vector type.
15173     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15174     unsigned SizeRatio = RegSz/MemSz;
15175
15176     // Redistribute the loaded elements into the different locations.
15177     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15178     for (unsigned i = 0; i != NumElems; ++i)
15179       ShuffleVec[i*SizeRatio] = i;
15180
15181     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15182                                          DAG.getUNDEF(WideVecVT),
15183                                          &ShuffleVec[0]);
15184
15185     // Bitcast to the requested type.
15186     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15187     // Replace the original load with the new sequence
15188     // and return the new chain.
15189     return DCI.CombineTo(N, Shuff, TF, true);
15190   }
15191
15192   return SDValue();
15193 }
15194
15195 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15196 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15197                                    const X86Subtarget *Subtarget) {
15198   StoreSDNode *St = cast<StoreSDNode>(N);
15199   EVT VT = St->getValue().getValueType();
15200   EVT StVT = St->getMemoryVT();
15201   DebugLoc dl = St->getDebugLoc();
15202   SDValue StoredVal = St->getOperand(1);
15203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15204
15205   // If we are saving a concatenation of two XMM registers, perform two stores.
15206   // On Sandy Bridge, 256-bit memory operations are executed by two
15207   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15208   // memory  operation.
15209   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15210       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15211       StoredVal.getNumOperands() == 2) {
15212     SDValue Value0 = StoredVal.getOperand(0);
15213     SDValue Value1 = StoredVal.getOperand(1);
15214
15215     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15216     SDValue Ptr0 = St->getBasePtr();
15217     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15218
15219     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15220                                 St->getPointerInfo(), St->isVolatile(),
15221                                 St->isNonTemporal(), St->getAlignment());
15222     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15223                                 St->getPointerInfo(), St->isVolatile(),
15224                                 St->isNonTemporal(), St->getAlignment());
15225     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15226   }
15227
15228   // Optimize trunc store (of multiple scalars) to shuffle and store.
15229   // First, pack all of the elements in one place. Next, store to memory
15230   // in fewer chunks.
15231   if (St->isTruncatingStore() && VT.isVector()) {
15232     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15233     unsigned NumElems = VT.getVectorNumElements();
15234     assert(StVT != VT && "Cannot truncate to the same type");
15235     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15236     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15237
15238     // From, To sizes and ElemCount must be pow of two
15239     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15240     // We are going to use the original vector elt for storing.
15241     // Accumulated smaller vector elements must be a multiple of the store size.
15242     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15243
15244     unsigned SizeRatio  = FromSz / ToSz;
15245
15246     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15247
15248     // Create a type on which we perform the shuffle
15249     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15250             StVT.getScalarType(), NumElems*SizeRatio);
15251
15252     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15253
15254     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15255     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15256     for (unsigned i = 0; i != NumElems; ++i)
15257       ShuffleVec[i] = i * SizeRatio;
15258
15259     // Can't shuffle using an illegal type.
15260     if (!TLI.isTypeLegal(WideVecVT))
15261       return SDValue();
15262
15263     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15264                                          DAG.getUNDEF(WideVecVT),
15265                                          &ShuffleVec[0]);
15266     // At this point all of the data is stored at the bottom of the
15267     // register. We now need to save it to mem.
15268
15269     // Find the largest store unit
15270     MVT StoreType = MVT::i8;
15271     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15272          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15273       MVT Tp = (MVT::SimpleValueType)tp;
15274       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15275         StoreType = Tp;
15276     }
15277
15278     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15279     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15280         (64 <= NumElems * ToSz))
15281       StoreType = MVT::f64;
15282
15283     // Bitcast the original vector into a vector of store-size units
15284     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15285             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15286     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15287     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15288     SmallVector<SDValue, 8> Chains;
15289     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15290                                         TLI.getPointerTy());
15291     SDValue Ptr = St->getBasePtr();
15292
15293     // Perform one or more big stores into memory.
15294     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15295       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15296                                    StoreType, ShuffWide,
15297                                    DAG.getIntPtrConstant(i));
15298       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15299                                 St->getPointerInfo(), St->isVolatile(),
15300                                 St->isNonTemporal(), St->getAlignment());
15301       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15302       Chains.push_back(Ch);
15303     }
15304
15305     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15306                                Chains.size());
15307   }
15308
15309
15310   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15311   // the FP state in cases where an emms may be missing.
15312   // A preferable solution to the general problem is to figure out the right
15313   // places to insert EMMS.  This qualifies as a quick hack.
15314
15315   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15316   if (VT.getSizeInBits() != 64)
15317     return SDValue();
15318
15319   const Function *F = DAG.getMachineFunction().getFunction();
15320   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15321   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15322                      && Subtarget->hasSSE2();
15323   if ((VT.isVector() ||
15324        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15325       isa<LoadSDNode>(St->getValue()) &&
15326       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15327       St->getChain().hasOneUse() && !St->isVolatile()) {
15328     SDNode* LdVal = St->getValue().getNode();
15329     LoadSDNode *Ld = 0;
15330     int TokenFactorIndex = -1;
15331     SmallVector<SDValue, 8> Ops;
15332     SDNode* ChainVal = St->getChain().getNode();
15333     // Must be a store of a load.  We currently handle two cases:  the load
15334     // is a direct child, and it's under an intervening TokenFactor.  It is
15335     // possible to dig deeper under nested TokenFactors.
15336     if (ChainVal == LdVal)
15337       Ld = cast<LoadSDNode>(St->getChain());
15338     else if (St->getValue().hasOneUse() &&
15339              ChainVal->getOpcode() == ISD::TokenFactor) {
15340       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15341         if (ChainVal->getOperand(i).getNode() == LdVal) {
15342           TokenFactorIndex = i;
15343           Ld = cast<LoadSDNode>(St->getValue());
15344         } else
15345           Ops.push_back(ChainVal->getOperand(i));
15346       }
15347     }
15348
15349     if (!Ld || !ISD::isNormalLoad(Ld))
15350       return SDValue();
15351
15352     // If this is not the MMX case, i.e. we are just turning i64 load/store
15353     // into f64 load/store, avoid the transformation if there are multiple
15354     // uses of the loaded value.
15355     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15356       return SDValue();
15357
15358     DebugLoc LdDL = Ld->getDebugLoc();
15359     DebugLoc StDL = N->getDebugLoc();
15360     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15361     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15362     // pair instead.
15363     if (Subtarget->is64Bit() || F64IsLegal) {
15364       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15365       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15366                                   Ld->getPointerInfo(), Ld->isVolatile(),
15367                                   Ld->isNonTemporal(), Ld->isInvariant(),
15368                                   Ld->getAlignment());
15369       SDValue NewChain = NewLd.getValue(1);
15370       if (TokenFactorIndex != -1) {
15371         Ops.push_back(NewChain);
15372         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15373                                Ops.size());
15374       }
15375       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15376                           St->getPointerInfo(),
15377                           St->isVolatile(), St->isNonTemporal(),
15378                           St->getAlignment());
15379     }
15380
15381     // Otherwise, lower to two pairs of 32-bit loads / stores.
15382     SDValue LoAddr = Ld->getBasePtr();
15383     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15384                                  DAG.getConstant(4, MVT::i32));
15385
15386     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15387                                Ld->getPointerInfo(),
15388                                Ld->isVolatile(), Ld->isNonTemporal(),
15389                                Ld->isInvariant(), Ld->getAlignment());
15390     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15391                                Ld->getPointerInfo().getWithOffset(4),
15392                                Ld->isVolatile(), Ld->isNonTemporal(),
15393                                Ld->isInvariant(),
15394                                MinAlign(Ld->getAlignment(), 4));
15395
15396     SDValue NewChain = LoLd.getValue(1);
15397     if (TokenFactorIndex != -1) {
15398       Ops.push_back(LoLd);
15399       Ops.push_back(HiLd);
15400       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15401                              Ops.size());
15402     }
15403
15404     LoAddr = St->getBasePtr();
15405     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15406                          DAG.getConstant(4, MVT::i32));
15407
15408     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15409                                 St->getPointerInfo(),
15410                                 St->isVolatile(), St->isNonTemporal(),
15411                                 St->getAlignment());
15412     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15413                                 St->getPointerInfo().getWithOffset(4),
15414                                 St->isVolatile(),
15415                                 St->isNonTemporal(),
15416                                 MinAlign(St->getAlignment(), 4));
15417     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15418   }
15419   return SDValue();
15420 }
15421
15422 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15423 /// and return the operands for the horizontal operation in LHS and RHS.  A
15424 /// horizontal operation performs the binary operation on successive elements
15425 /// of its first operand, then on successive elements of its second operand,
15426 /// returning the resulting values in a vector.  For example, if
15427 ///   A = < float a0, float a1, float a2, float a3 >
15428 /// and
15429 ///   B = < float b0, float b1, float b2, float b3 >
15430 /// then the result of doing a horizontal operation on A and B is
15431 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15432 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15433 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15434 /// set to A, RHS to B, and the routine returns 'true'.
15435 /// Note that the binary operation should have the property that if one of the
15436 /// operands is UNDEF then the result is UNDEF.
15437 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15438   // Look for the following pattern: if
15439   //   A = < float a0, float a1, float a2, float a3 >
15440   //   B = < float b0, float b1, float b2, float b3 >
15441   // and
15442   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15443   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15444   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15445   // which is A horizontal-op B.
15446
15447   // At least one of the operands should be a vector shuffle.
15448   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15449       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15450     return false;
15451
15452   EVT VT = LHS.getValueType();
15453
15454   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15455          "Unsupported vector type for horizontal add/sub");
15456
15457   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15458   // operate independently on 128-bit lanes.
15459   unsigned NumElts = VT.getVectorNumElements();
15460   unsigned NumLanes = VT.getSizeInBits()/128;
15461   unsigned NumLaneElts = NumElts / NumLanes;
15462   assert((NumLaneElts % 2 == 0) &&
15463          "Vector type should have an even number of elements in each lane");
15464   unsigned HalfLaneElts = NumLaneElts/2;
15465
15466   // View LHS in the form
15467   //   LHS = VECTOR_SHUFFLE A, B, LMask
15468   // If LHS is not a shuffle then pretend it is the shuffle
15469   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15470   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15471   // type VT.
15472   SDValue A, B;
15473   SmallVector<int, 16> LMask(NumElts);
15474   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15475     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15476       A = LHS.getOperand(0);
15477     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15478       B = LHS.getOperand(1);
15479     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15480     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15481   } else {
15482     if (LHS.getOpcode() != ISD::UNDEF)
15483       A = LHS;
15484     for (unsigned i = 0; i != NumElts; ++i)
15485       LMask[i] = i;
15486   }
15487
15488   // Likewise, view RHS in the form
15489   //   RHS = VECTOR_SHUFFLE C, D, RMask
15490   SDValue C, D;
15491   SmallVector<int, 16> RMask(NumElts);
15492   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15493     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15494       C = RHS.getOperand(0);
15495     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15496       D = RHS.getOperand(1);
15497     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15498     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15499   } else {
15500     if (RHS.getOpcode() != ISD::UNDEF)
15501       C = RHS;
15502     for (unsigned i = 0; i != NumElts; ++i)
15503       RMask[i] = i;
15504   }
15505
15506   // Check that the shuffles are both shuffling the same vectors.
15507   if (!(A == C && B == D) && !(A == D && B == C))
15508     return false;
15509
15510   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15511   if (!A.getNode() && !B.getNode())
15512     return false;
15513
15514   // If A and B occur in reverse order in RHS, then "swap" them (which means
15515   // rewriting the mask).
15516   if (A != C)
15517     CommuteVectorShuffleMask(RMask, NumElts);
15518
15519   // At this point LHS and RHS are equivalent to
15520   //   LHS = VECTOR_SHUFFLE A, B, LMask
15521   //   RHS = VECTOR_SHUFFLE A, B, RMask
15522   // Check that the masks correspond to performing a horizontal operation.
15523   for (unsigned i = 0; i != NumElts; ++i) {
15524     int LIdx = LMask[i], RIdx = RMask[i];
15525
15526     // Ignore any UNDEF components.
15527     if (LIdx < 0 || RIdx < 0 ||
15528         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15529         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15530       continue;
15531
15532     // Check that successive elements are being operated on.  If not, this is
15533     // not a horizontal operation.
15534     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15535     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15536     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15537     if (!(LIdx == Index && RIdx == Index + 1) &&
15538         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15539       return false;
15540   }
15541
15542   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15543   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15544   return true;
15545 }
15546
15547 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15548 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15549                                   const X86Subtarget *Subtarget) {
15550   EVT VT = N->getValueType(0);
15551   SDValue LHS = N->getOperand(0);
15552   SDValue RHS = N->getOperand(1);
15553
15554   // Try to synthesize horizontal adds from adds of shuffles.
15555   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15556        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15557       isHorizontalBinOp(LHS, RHS, true))
15558     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15559   return SDValue();
15560 }
15561
15562 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15563 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15564                                   const X86Subtarget *Subtarget) {
15565   EVT VT = N->getValueType(0);
15566   SDValue LHS = N->getOperand(0);
15567   SDValue RHS = N->getOperand(1);
15568
15569   // Try to synthesize horizontal subs from subs of shuffles.
15570   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15571        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15572       isHorizontalBinOp(LHS, RHS, false))
15573     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15574   return SDValue();
15575 }
15576
15577 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15578 /// X86ISD::FXOR nodes.
15579 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15580   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15581   // F[X]OR(0.0, x) -> x
15582   // F[X]OR(x, 0.0) -> x
15583   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15584     if (C->getValueAPF().isPosZero())
15585       return N->getOperand(1);
15586   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15587     if (C->getValueAPF().isPosZero())
15588       return N->getOperand(0);
15589   return SDValue();
15590 }
15591
15592 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15593 /// X86ISD::FMAX nodes.
15594 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15595   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15596
15597   // Only perform optimizations if UnsafeMath is used.
15598   if (!DAG.getTarget().Options.UnsafeFPMath)
15599     return SDValue();
15600
15601   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15602   // into FMINC and FMAXC, which are Commutative operations.
15603   unsigned NewOp = 0;
15604   switch (N->getOpcode()) {
15605     default: llvm_unreachable("unknown opcode");
15606     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15607     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15608   }
15609
15610   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15611                      N->getOperand(0), N->getOperand(1));
15612 }
15613
15614
15615 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15616 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15617   // FAND(0.0, x) -> 0.0
15618   // FAND(x, 0.0) -> 0.0
15619   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15620     if (C->getValueAPF().isPosZero())
15621       return N->getOperand(0);
15622   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15623     if (C->getValueAPF().isPosZero())
15624       return N->getOperand(1);
15625   return SDValue();
15626 }
15627
15628 static SDValue PerformBTCombine(SDNode *N,
15629                                 SelectionDAG &DAG,
15630                                 TargetLowering::DAGCombinerInfo &DCI) {
15631   // BT ignores high bits in the bit index operand.
15632   SDValue Op1 = N->getOperand(1);
15633   if (Op1.hasOneUse()) {
15634     unsigned BitWidth = Op1.getValueSizeInBits();
15635     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15636     APInt KnownZero, KnownOne;
15637     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15638                                           !DCI.isBeforeLegalizeOps());
15639     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15640     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15641         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15642       DCI.CommitTargetLoweringOpt(TLO);
15643   }
15644   return SDValue();
15645 }
15646
15647 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15648   SDValue Op = N->getOperand(0);
15649   if (Op.getOpcode() == ISD::BITCAST)
15650     Op = Op.getOperand(0);
15651   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15652   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15653       VT.getVectorElementType().getSizeInBits() ==
15654       OpVT.getVectorElementType().getSizeInBits()) {
15655     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15656   }
15657   return SDValue();
15658 }
15659
15660 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15661                                   TargetLowering::DAGCombinerInfo &DCI,
15662                                   const X86Subtarget *Subtarget) {
15663   if (!DCI.isBeforeLegalizeOps())
15664     return SDValue();
15665
15666   if (!Subtarget->hasAVX())
15667     return SDValue();
15668
15669   EVT VT = N->getValueType(0);
15670   SDValue Op = N->getOperand(0);
15671   EVT OpVT = Op.getValueType();
15672   DebugLoc dl = N->getDebugLoc();
15673
15674   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15675       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15676
15677     if (Subtarget->hasAVX2())
15678       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15679
15680     // Optimize vectors in AVX mode
15681     // Sign extend  v8i16 to v8i32 and
15682     //              v4i32 to v4i64
15683     //
15684     // Divide input vector into two parts
15685     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15686     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15687     // concat the vectors to original VT
15688
15689     unsigned NumElems = OpVT.getVectorNumElements();
15690     SDValue Undef = DAG.getUNDEF(OpVT);
15691
15692     SmallVector<int,8> ShufMask1(NumElems, -1);
15693     for (unsigned i = 0; i != NumElems/2; ++i)
15694       ShufMask1[i] = i;
15695
15696     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15697
15698     SmallVector<int,8> ShufMask2(NumElems, -1);
15699     for (unsigned i = 0; i != NumElems/2; ++i)
15700       ShufMask2[i] = i + NumElems/2;
15701
15702     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15703
15704     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15705                                   VT.getVectorNumElements()/2);
15706
15707     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15708     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15709
15710     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15711   }
15712   return SDValue();
15713 }
15714
15715 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15716                                  const X86Subtarget* Subtarget) {
15717   DebugLoc dl = N->getDebugLoc();
15718   EVT VT = N->getValueType(0);
15719
15720   // Let legalize expand this if it isn't a legal type yet.
15721   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15722     return SDValue();
15723
15724   EVT ScalarVT = VT.getScalarType();
15725   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15726       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15727     return SDValue();
15728
15729   SDValue A = N->getOperand(0);
15730   SDValue B = N->getOperand(1);
15731   SDValue C = N->getOperand(2);
15732
15733   bool NegA = (A.getOpcode() == ISD::FNEG);
15734   bool NegB = (B.getOpcode() == ISD::FNEG);
15735   bool NegC = (C.getOpcode() == ISD::FNEG);
15736
15737   // Negative multiplication when NegA xor NegB
15738   bool NegMul = (NegA != NegB);
15739   if (NegA)
15740     A = A.getOperand(0);
15741   if (NegB)
15742     B = B.getOperand(0);
15743   if (NegC)
15744     C = C.getOperand(0);
15745
15746   unsigned Opcode;
15747   if (!NegMul)
15748     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15749   else
15750     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15751
15752   return DAG.getNode(Opcode, dl, VT, A, B, C);
15753 }
15754
15755 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15756                                   TargetLowering::DAGCombinerInfo &DCI,
15757                                   const X86Subtarget *Subtarget) {
15758   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15759   //           (and (i32 x86isd::setcc_carry), 1)
15760   // This eliminates the zext. This transformation is necessary because
15761   // ISD::SETCC is always legalized to i8.
15762   DebugLoc dl = N->getDebugLoc();
15763   SDValue N0 = N->getOperand(0);
15764   EVT VT = N->getValueType(0);
15765   EVT OpVT = N0.getValueType();
15766
15767   if (N0.getOpcode() == ISD::AND &&
15768       N0.hasOneUse() &&
15769       N0.getOperand(0).hasOneUse()) {
15770     SDValue N00 = N0.getOperand(0);
15771     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15772       return SDValue();
15773     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15774     if (!C || C->getZExtValue() != 1)
15775       return SDValue();
15776     return DAG.getNode(ISD::AND, dl, VT,
15777                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15778                                    N00.getOperand(0), N00.getOperand(1)),
15779                        DAG.getConstant(1, VT));
15780   }
15781
15782   // Optimize vectors in AVX mode:
15783   //
15784   //   v8i16 -> v8i32
15785   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15786   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15787   //   Concat upper and lower parts.
15788   //
15789   //   v4i32 -> v4i64
15790   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15791   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15792   //   Concat upper and lower parts.
15793   //
15794   if (!DCI.isBeforeLegalizeOps())
15795     return SDValue();
15796
15797   if (!Subtarget->hasAVX())
15798     return SDValue();
15799
15800   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15801       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15802
15803     if (Subtarget->hasAVX2())
15804       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15805
15806     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15807     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15808     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15809
15810     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15811                                VT.getVectorNumElements()/2);
15812
15813     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15814     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15815
15816     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15817   }
15818
15819   return SDValue();
15820 }
15821
15822 // Optimize x == -y --> x+y == 0
15823 //          x != -y --> x+y != 0
15824 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15825   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15826   SDValue LHS = N->getOperand(0);
15827   SDValue RHS = N->getOperand(1);
15828
15829   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15830     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15831       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15832         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15833                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15834         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15835                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15836       }
15837   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15838     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15839       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15840         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15841                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15842         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15843                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15844       }
15845   return SDValue();
15846 }
15847
15848 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15849 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15850                                    TargetLowering::DAGCombinerInfo &DCI,
15851                                    const X86Subtarget *Subtarget) {
15852   DebugLoc DL = N->getDebugLoc();
15853   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15854   SDValue EFLAGS = N->getOperand(1);
15855
15856   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15857   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15858   // cases.
15859   if (CC == X86::COND_B)
15860     return DAG.getNode(ISD::AND, DL, MVT::i8,
15861                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15862                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15863                        DAG.getConstant(1, MVT::i8));
15864
15865   SDValue Flags;
15866
15867   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15868   if (Flags.getNode()) {
15869     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15870     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15871   }
15872
15873   return SDValue();
15874 }
15875
15876 // Optimize branch condition evaluation.
15877 //
15878 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15879                                     TargetLowering::DAGCombinerInfo &DCI,
15880                                     const X86Subtarget *Subtarget) {
15881   DebugLoc DL = N->getDebugLoc();
15882   SDValue Chain = N->getOperand(0);
15883   SDValue Dest = N->getOperand(1);
15884   SDValue EFLAGS = N->getOperand(3);
15885   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15886
15887   SDValue Flags;
15888
15889   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15890   if (Flags.getNode()) {
15891     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15892     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15893                        Flags);
15894   }
15895
15896   return SDValue();
15897 }
15898
15899 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15900   SDValue Op0 = N->getOperand(0);
15901   EVT InVT = Op0->getValueType(0);
15902
15903   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15904   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15905     DebugLoc dl = N->getDebugLoc();
15906     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15907     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15908     // Notice that we use SINT_TO_FP because we know that the high bits
15909     // are zero and SINT_TO_FP is better supported by the hardware.
15910     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15911   }
15912
15913   return SDValue();
15914 }
15915
15916 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15917                                         const X86TargetLowering *XTLI) {
15918   SDValue Op0 = N->getOperand(0);
15919   EVT InVT = Op0->getValueType(0);
15920
15921   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15922   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15923     DebugLoc dl = N->getDebugLoc();
15924     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15925     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15926     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15927   }
15928
15929   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15930   // a 32-bit target where SSE doesn't support i64->FP operations.
15931   if (Op0.getOpcode() == ISD::LOAD) {
15932     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15933     EVT VT = Ld->getValueType(0);
15934     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15935         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15936         !XTLI->getSubtarget()->is64Bit() &&
15937         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15938       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15939                                           Ld->getChain(), Op0, DAG);
15940       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15941       return FILDChain;
15942     }
15943   }
15944   return SDValue();
15945 }
15946
15947 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15948   EVT VT = N->getValueType(0);
15949
15950   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15951   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15952     DebugLoc dl = N->getDebugLoc();
15953     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15954     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15955     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15956   }
15957
15958   return SDValue();
15959 }
15960
15961 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15962 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15963                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15964   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15965   // the result is either zero or one (depending on the input carry bit).
15966   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15967   if (X86::isZeroNode(N->getOperand(0)) &&
15968       X86::isZeroNode(N->getOperand(1)) &&
15969       // We don't have a good way to replace an EFLAGS use, so only do this when
15970       // dead right now.
15971       SDValue(N, 1).use_empty()) {
15972     DebugLoc DL = N->getDebugLoc();
15973     EVT VT = N->getValueType(0);
15974     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15975     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15976                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15977                                            DAG.getConstant(X86::COND_B,MVT::i8),
15978                                            N->getOperand(2)),
15979                                DAG.getConstant(1, VT));
15980     return DCI.CombineTo(N, Res1, CarryOut);
15981   }
15982
15983   return SDValue();
15984 }
15985
15986 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15987 //      (add Y, (setne X, 0)) -> sbb -1, Y
15988 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15989 //      (sub (setne X, 0), Y) -> adc -1, Y
15990 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15991   DebugLoc DL = N->getDebugLoc();
15992
15993   // Look through ZExts.
15994   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15995   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15996     return SDValue();
15997
15998   SDValue SetCC = Ext.getOperand(0);
15999   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16000     return SDValue();
16001
16002   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16003   if (CC != X86::COND_E && CC != X86::COND_NE)
16004     return SDValue();
16005
16006   SDValue Cmp = SetCC.getOperand(1);
16007   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16008       !X86::isZeroNode(Cmp.getOperand(1)) ||
16009       !Cmp.getOperand(0).getValueType().isInteger())
16010     return SDValue();
16011
16012   SDValue CmpOp0 = Cmp.getOperand(0);
16013   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16014                                DAG.getConstant(1, CmpOp0.getValueType()));
16015
16016   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16017   if (CC == X86::COND_NE)
16018     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16019                        DL, OtherVal.getValueType(), OtherVal,
16020                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16021   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16022                      DL, OtherVal.getValueType(), OtherVal,
16023                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16024 }
16025
16026 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16027 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16028                                  const X86Subtarget *Subtarget) {
16029   EVT VT = N->getValueType(0);
16030   SDValue Op0 = N->getOperand(0);
16031   SDValue Op1 = N->getOperand(1);
16032
16033   // Try to synthesize horizontal adds from adds of shuffles.
16034   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16035        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16036       isHorizontalBinOp(Op0, Op1, true))
16037     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16038
16039   return OptimizeConditionalInDecrement(N, DAG);
16040 }
16041
16042 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16043                                  const X86Subtarget *Subtarget) {
16044   SDValue Op0 = N->getOperand(0);
16045   SDValue Op1 = N->getOperand(1);
16046
16047   // X86 can't encode an immediate LHS of a sub. See if we can push the
16048   // negation into a preceding instruction.
16049   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16050     // If the RHS of the sub is a XOR with one use and a constant, invert the
16051     // immediate. Then add one to the LHS of the sub so we can turn
16052     // X-Y -> X+~Y+1, saving one register.
16053     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16054         isa<ConstantSDNode>(Op1.getOperand(1))) {
16055       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16056       EVT VT = Op0.getValueType();
16057       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16058                                    Op1.getOperand(0),
16059                                    DAG.getConstant(~XorC, VT));
16060       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16061                          DAG.getConstant(C->getAPIntValue()+1, VT));
16062     }
16063   }
16064
16065   // Try to synthesize horizontal adds from adds of shuffles.
16066   EVT VT = N->getValueType(0);
16067   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16068        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16069       isHorizontalBinOp(Op0, Op1, true))
16070     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16071
16072   return OptimizeConditionalInDecrement(N, DAG);
16073 }
16074
16075 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16076                                              DAGCombinerInfo &DCI) const {
16077   SelectionDAG &DAG = DCI.DAG;
16078   switch (N->getOpcode()) {
16079   default: break;
16080   case ISD::EXTRACT_VECTOR_ELT:
16081     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16082   case ISD::VSELECT:
16083   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16084   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16085   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16086   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16087   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16088   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16089   case ISD::SHL:
16090   case ISD::SRA:
16091   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16092   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16093   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16094   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16095   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16096   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16097   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16098   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16099   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16100   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16101   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16102   case X86ISD::FXOR:
16103   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16104   case X86ISD::FMIN:
16105   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16106   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16107   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16108   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16109   case ISD::ANY_EXTEND:
16110   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16111   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16112   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16113   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16114   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16115   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16116   case X86ISD::SHUFP:       // Handle all target specific shuffles
16117   case X86ISD::PALIGN:
16118   case X86ISD::UNPCKH:
16119   case X86ISD::UNPCKL:
16120   case X86ISD::MOVHLPS:
16121   case X86ISD::MOVLHPS:
16122   case X86ISD::PSHUFD:
16123   case X86ISD::PSHUFHW:
16124   case X86ISD::PSHUFLW:
16125   case X86ISD::MOVSS:
16126   case X86ISD::MOVSD:
16127   case X86ISD::VPERMILP:
16128   case X86ISD::VPERM2X128:
16129   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16130   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16131   }
16132
16133   return SDValue();
16134 }
16135
16136 /// isTypeDesirableForOp - Return true if the target has native support for
16137 /// the specified value type and it is 'desirable' to use the type for the
16138 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16139 /// instruction encodings are longer and some i16 instructions are slow.
16140 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16141   if (!isTypeLegal(VT))
16142     return false;
16143   if (VT != MVT::i16)
16144     return true;
16145
16146   switch (Opc) {
16147   default:
16148     return true;
16149   case ISD::LOAD:
16150   case ISD::SIGN_EXTEND:
16151   case ISD::ZERO_EXTEND:
16152   case ISD::ANY_EXTEND:
16153   case ISD::SHL:
16154   case ISD::SRL:
16155   case ISD::SUB:
16156   case ISD::ADD:
16157   case ISD::MUL:
16158   case ISD::AND:
16159   case ISD::OR:
16160   case ISD::XOR:
16161     return false;
16162   }
16163 }
16164
16165 /// IsDesirableToPromoteOp - This method query the target whether it is
16166 /// beneficial for dag combiner to promote the specified node. If true, it
16167 /// should return the desired promotion type by reference.
16168 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16169   EVT VT = Op.getValueType();
16170   if (VT != MVT::i16)
16171     return false;
16172
16173   bool Promote = false;
16174   bool Commute = false;
16175   switch (Op.getOpcode()) {
16176   default: break;
16177   case ISD::LOAD: {
16178     LoadSDNode *LD = cast<LoadSDNode>(Op);
16179     // If the non-extending load has a single use and it's not live out, then it
16180     // might be folded.
16181     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16182                                                      Op.hasOneUse()*/) {
16183       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16184              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16185         // The only case where we'd want to promote LOAD (rather then it being
16186         // promoted as an operand is when it's only use is liveout.
16187         if (UI->getOpcode() != ISD::CopyToReg)
16188           return false;
16189       }
16190     }
16191     Promote = true;
16192     break;
16193   }
16194   case ISD::SIGN_EXTEND:
16195   case ISD::ZERO_EXTEND:
16196   case ISD::ANY_EXTEND:
16197     Promote = true;
16198     break;
16199   case ISD::SHL:
16200   case ISD::SRL: {
16201     SDValue N0 = Op.getOperand(0);
16202     // Look out for (store (shl (load), x)).
16203     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16204       return false;
16205     Promote = true;
16206     break;
16207   }
16208   case ISD::ADD:
16209   case ISD::MUL:
16210   case ISD::AND:
16211   case ISD::OR:
16212   case ISD::XOR:
16213     Commute = true;
16214     // fallthrough
16215   case ISD::SUB: {
16216     SDValue N0 = Op.getOperand(0);
16217     SDValue N1 = Op.getOperand(1);
16218     if (!Commute && MayFoldLoad(N1))
16219       return false;
16220     // Avoid disabling potential load folding opportunities.
16221     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16222       return false;
16223     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16224       return false;
16225     Promote = true;
16226   }
16227   }
16228
16229   PVT = MVT::i32;
16230   return Promote;
16231 }
16232
16233 //===----------------------------------------------------------------------===//
16234 //                           X86 Inline Assembly Support
16235 //===----------------------------------------------------------------------===//
16236
16237 namespace {
16238   // Helper to match a string separated by whitespace.
16239   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16240     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16241
16242     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16243       StringRef piece(*args[i]);
16244       if (!s.startswith(piece)) // Check if the piece matches.
16245         return false;
16246
16247       s = s.substr(piece.size());
16248       StringRef::size_type pos = s.find_first_not_of(" \t");
16249       if (pos == 0) // We matched a prefix.
16250         return false;
16251
16252       s = s.substr(pos);
16253     }
16254
16255     return s.empty();
16256   }
16257   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16258 }
16259
16260 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16261   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16262
16263   std::string AsmStr = IA->getAsmString();
16264
16265   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16266   if (!Ty || Ty->getBitWidth() % 16 != 0)
16267     return false;
16268
16269   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16270   SmallVector<StringRef, 4> AsmPieces;
16271   SplitString(AsmStr, AsmPieces, ";\n");
16272
16273   switch (AsmPieces.size()) {
16274   default: return false;
16275   case 1:
16276     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16277     // we will turn this bswap into something that will be lowered to logical
16278     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16279     // lower so don't worry about this.
16280     // bswap $0
16281     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16282         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16283         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16284         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16285         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16286         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16287       // No need to check constraints, nothing other than the equivalent of
16288       // "=r,0" would be valid here.
16289       return IntrinsicLowering::LowerToByteSwap(CI);
16290     }
16291
16292     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16293     if (CI->getType()->isIntegerTy(16) &&
16294         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16295         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16296          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16297       AsmPieces.clear();
16298       const std::string &ConstraintsStr = IA->getConstraintString();
16299       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16300       std::sort(AsmPieces.begin(), AsmPieces.end());
16301       if (AsmPieces.size() == 4 &&
16302           AsmPieces[0] == "~{cc}" &&
16303           AsmPieces[1] == "~{dirflag}" &&
16304           AsmPieces[2] == "~{flags}" &&
16305           AsmPieces[3] == "~{fpsr}")
16306       return IntrinsicLowering::LowerToByteSwap(CI);
16307     }
16308     break;
16309   case 3:
16310     if (CI->getType()->isIntegerTy(32) &&
16311         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16312         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16313         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16314         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16315       AsmPieces.clear();
16316       const std::string &ConstraintsStr = IA->getConstraintString();
16317       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16318       std::sort(AsmPieces.begin(), AsmPieces.end());
16319       if (AsmPieces.size() == 4 &&
16320           AsmPieces[0] == "~{cc}" &&
16321           AsmPieces[1] == "~{dirflag}" &&
16322           AsmPieces[2] == "~{flags}" &&
16323           AsmPieces[3] == "~{fpsr}")
16324         return IntrinsicLowering::LowerToByteSwap(CI);
16325     }
16326
16327     if (CI->getType()->isIntegerTy(64)) {
16328       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16329       if (Constraints.size() >= 2 &&
16330           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16331           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16332         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16333         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16334             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16335             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16336           return IntrinsicLowering::LowerToByteSwap(CI);
16337       }
16338     }
16339     break;
16340   }
16341   return false;
16342 }
16343
16344
16345
16346 /// getConstraintType - Given a constraint letter, return the type of
16347 /// constraint it is for this target.
16348 X86TargetLowering::ConstraintType
16349 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16350   if (Constraint.size() == 1) {
16351     switch (Constraint[0]) {
16352     case 'R':
16353     case 'q':
16354     case 'Q':
16355     case 'f':
16356     case 't':
16357     case 'u':
16358     case 'y':
16359     case 'x':
16360     case 'Y':
16361     case 'l':
16362       return C_RegisterClass;
16363     case 'a':
16364     case 'b':
16365     case 'c':
16366     case 'd':
16367     case 'S':
16368     case 'D':
16369     case 'A':
16370       return C_Register;
16371     case 'I':
16372     case 'J':
16373     case 'K':
16374     case 'L':
16375     case 'M':
16376     case 'N':
16377     case 'G':
16378     case 'C':
16379     case 'e':
16380     case 'Z':
16381       return C_Other;
16382     default:
16383       break;
16384     }
16385   }
16386   return TargetLowering::getConstraintType(Constraint);
16387 }
16388
16389 /// Examine constraint type and operand type and determine a weight value.
16390 /// This object must already have been set up with the operand type
16391 /// and the current alternative constraint selected.
16392 TargetLowering::ConstraintWeight
16393   X86TargetLowering::getSingleConstraintMatchWeight(
16394     AsmOperandInfo &info, const char *constraint) const {
16395   ConstraintWeight weight = CW_Invalid;
16396   Value *CallOperandVal = info.CallOperandVal;
16397     // If we don't have a value, we can't do a match,
16398     // but allow it at the lowest weight.
16399   if (CallOperandVal == NULL)
16400     return CW_Default;
16401   Type *type = CallOperandVal->getType();
16402   // Look at the constraint type.
16403   switch (*constraint) {
16404   default:
16405     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16406   case 'R':
16407   case 'q':
16408   case 'Q':
16409   case 'a':
16410   case 'b':
16411   case 'c':
16412   case 'd':
16413   case 'S':
16414   case 'D':
16415   case 'A':
16416     if (CallOperandVal->getType()->isIntegerTy())
16417       weight = CW_SpecificReg;
16418     break;
16419   case 'f':
16420   case 't':
16421   case 'u':
16422       if (type->isFloatingPointTy())
16423         weight = CW_SpecificReg;
16424       break;
16425   case 'y':
16426       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16427         weight = CW_SpecificReg;
16428       break;
16429   case 'x':
16430   case 'Y':
16431     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16432         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16433       weight = CW_Register;
16434     break;
16435   case 'I':
16436     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16437       if (C->getZExtValue() <= 31)
16438         weight = CW_Constant;
16439     }
16440     break;
16441   case 'J':
16442     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16443       if (C->getZExtValue() <= 63)
16444         weight = CW_Constant;
16445     }
16446     break;
16447   case 'K':
16448     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16449       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16450         weight = CW_Constant;
16451     }
16452     break;
16453   case 'L':
16454     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16455       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16456         weight = CW_Constant;
16457     }
16458     break;
16459   case 'M':
16460     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16461       if (C->getZExtValue() <= 3)
16462         weight = CW_Constant;
16463     }
16464     break;
16465   case 'N':
16466     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16467       if (C->getZExtValue() <= 0xff)
16468         weight = CW_Constant;
16469     }
16470     break;
16471   case 'G':
16472   case 'C':
16473     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16474       weight = CW_Constant;
16475     }
16476     break;
16477   case 'e':
16478     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16479       if ((C->getSExtValue() >= -0x80000000LL) &&
16480           (C->getSExtValue() <= 0x7fffffffLL))
16481         weight = CW_Constant;
16482     }
16483     break;
16484   case 'Z':
16485     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16486       if (C->getZExtValue() <= 0xffffffff)
16487         weight = CW_Constant;
16488     }
16489     break;
16490   }
16491   return weight;
16492 }
16493
16494 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16495 /// with another that has more specific requirements based on the type of the
16496 /// corresponding operand.
16497 const char *X86TargetLowering::
16498 LowerXConstraint(EVT ConstraintVT) const {
16499   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16500   // 'f' like normal targets.
16501   if (ConstraintVT.isFloatingPoint()) {
16502     if (Subtarget->hasSSE2())
16503       return "Y";
16504     if (Subtarget->hasSSE1())
16505       return "x";
16506   }
16507
16508   return TargetLowering::LowerXConstraint(ConstraintVT);
16509 }
16510
16511 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16512 /// vector.  If it is invalid, don't add anything to Ops.
16513 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16514                                                      std::string &Constraint,
16515                                                      std::vector<SDValue>&Ops,
16516                                                      SelectionDAG &DAG) const {
16517   SDValue Result(0, 0);
16518
16519   // Only support length 1 constraints for now.
16520   if (Constraint.length() > 1) return;
16521
16522   char ConstraintLetter = Constraint[0];
16523   switch (ConstraintLetter) {
16524   default: break;
16525   case 'I':
16526     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16527       if (C->getZExtValue() <= 31) {
16528         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16529         break;
16530       }
16531     }
16532     return;
16533   case 'J':
16534     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16535       if (C->getZExtValue() <= 63) {
16536         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16537         break;
16538       }
16539     }
16540     return;
16541   case 'K':
16542     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16543       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16544         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16545         break;
16546       }
16547     }
16548     return;
16549   case 'N':
16550     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16551       if (C->getZExtValue() <= 255) {
16552         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16553         break;
16554       }
16555     }
16556     return;
16557   case 'e': {
16558     // 32-bit signed value
16559     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16560       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16561                                            C->getSExtValue())) {
16562         // Widen to 64 bits here to get it sign extended.
16563         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16564         break;
16565       }
16566     // FIXME gcc accepts some relocatable values here too, but only in certain
16567     // memory models; it's complicated.
16568     }
16569     return;
16570   }
16571   case 'Z': {
16572     // 32-bit unsigned value
16573     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16574       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16575                                            C->getZExtValue())) {
16576         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16577         break;
16578       }
16579     }
16580     // FIXME gcc accepts some relocatable values here too, but only in certain
16581     // memory models; it's complicated.
16582     return;
16583   }
16584   case 'i': {
16585     // Literal immediates are always ok.
16586     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16587       // Widen to 64 bits here to get it sign extended.
16588       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16589       break;
16590     }
16591
16592     // In any sort of PIC mode addresses need to be computed at runtime by
16593     // adding in a register or some sort of table lookup.  These can't
16594     // be used as immediates.
16595     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16596       return;
16597
16598     // If we are in non-pic codegen mode, we allow the address of a global (with
16599     // an optional displacement) to be used with 'i'.
16600     GlobalAddressSDNode *GA = 0;
16601     int64_t Offset = 0;
16602
16603     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16604     while (1) {
16605       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16606         Offset += GA->getOffset();
16607         break;
16608       } else if (Op.getOpcode() == ISD::ADD) {
16609         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16610           Offset += C->getZExtValue();
16611           Op = Op.getOperand(0);
16612           continue;
16613         }
16614       } else if (Op.getOpcode() == ISD::SUB) {
16615         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16616           Offset += -C->getZExtValue();
16617           Op = Op.getOperand(0);
16618           continue;
16619         }
16620       }
16621
16622       // Otherwise, this isn't something we can handle, reject it.
16623       return;
16624     }
16625
16626     const GlobalValue *GV = GA->getGlobal();
16627     // If we require an extra load to get this address, as in PIC mode, we
16628     // can't accept it.
16629     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16630                                                         getTargetMachine())))
16631       return;
16632
16633     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16634                                         GA->getValueType(0), Offset);
16635     break;
16636   }
16637   }
16638
16639   if (Result.getNode()) {
16640     Ops.push_back(Result);
16641     return;
16642   }
16643   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16644 }
16645
16646 std::pair<unsigned, const TargetRegisterClass*>
16647 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16648                                                 EVT VT) const {
16649   // First, see if this is a constraint that directly corresponds to an LLVM
16650   // register class.
16651   if (Constraint.size() == 1) {
16652     // GCC Constraint Letters
16653     switch (Constraint[0]) {
16654     default: break;
16655       // TODO: Slight differences here in allocation order and leaving
16656       // RIP in the class. Do they matter any more here than they do
16657       // in the normal allocation?
16658     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16659       if (Subtarget->is64Bit()) {
16660         if (VT == MVT::i32 || VT == MVT::f32)
16661           return std::make_pair(0U, &X86::GR32RegClass);
16662         if (VT == MVT::i16)
16663           return std::make_pair(0U, &X86::GR16RegClass);
16664         if (VT == MVT::i8 || VT == MVT::i1)
16665           return std::make_pair(0U, &X86::GR8RegClass);
16666         if (VT == MVT::i64 || VT == MVT::f64)
16667           return std::make_pair(0U, &X86::GR64RegClass);
16668         break;
16669       }
16670       // 32-bit fallthrough
16671     case 'Q':   // Q_REGS
16672       if (VT == MVT::i32 || VT == MVT::f32)
16673         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16674       if (VT == MVT::i16)
16675         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16676       if (VT == MVT::i8 || VT == MVT::i1)
16677         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16678       if (VT == MVT::i64)
16679         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16680       break;
16681     case 'r':   // GENERAL_REGS
16682     case 'l':   // INDEX_REGS
16683       if (VT == MVT::i8 || VT == MVT::i1)
16684         return std::make_pair(0U, &X86::GR8RegClass);
16685       if (VT == MVT::i16)
16686         return std::make_pair(0U, &X86::GR16RegClass);
16687       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16688         return std::make_pair(0U, &X86::GR32RegClass);
16689       return std::make_pair(0U, &X86::GR64RegClass);
16690     case 'R':   // LEGACY_REGS
16691       if (VT == MVT::i8 || VT == MVT::i1)
16692         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16693       if (VT == MVT::i16)
16694         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16695       if (VT == MVT::i32 || !Subtarget->is64Bit())
16696         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16697       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16698     case 'f':  // FP Stack registers.
16699       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16700       // value to the correct fpstack register class.
16701       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16702         return std::make_pair(0U, &X86::RFP32RegClass);
16703       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16704         return std::make_pair(0U, &X86::RFP64RegClass);
16705       return std::make_pair(0U, &X86::RFP80RegClass);
16706     case 'y':   // MMX_REGS if MMX allowed.
16707       if (!Subtarget->hasMMX()) break;
16708       return std::make_pair(0U, &X86::VR64RegClass);
16709     case 'Y':   // SSE_REGS if SSE2 allowed
16710       if (!Subtarget->hasSSE2()) break;
16711       // FALL THROUGH.
16712     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16713       if (!Subtarget->hasSSE1()) break;
16714
16715       switch (VT.getSimpleVT().SimpleTy) {
16716       default: break;
16717       // Scalar SSE types.
16718       case MVT::f32:
16719       case MVT::i32:
16720         return std::make_pair(0U, &X86::FR32RegClass);
16721       case MVT::f64:
16722       case MVT::i64:
16723         return std::make_pair(0U, &X86::FR64RegClass);
16724       // Vector types.
16725       case MVT::v16i8:
16726       case MVT::v8i16:
16727       case MVT::v4i32:
16728       case MVT::v2i64:
16729       case MVT::v4f32:
16730       case MVT::v2f64:
16731         return std::make_pair(0U, &X86::VR128RegClass);
16732       // AVX types.
16733       case MVT::v32i8:
16734       case MVT::v16i16:
16735       case MVT::v8i32:
16736       case MVT::v4i64:
16737       case MVT::v8f32:
16738       case MVT::v4f64:
16739         return std::make_pair(0U, &X86::VR256RegClass);
16740       }
16741       break;
16742     }
16743   }
16744
16745   // Use the default implementation in TargetLowering to convert the register
16746   // constraint into a member of a register class.
16747   std::pair<unsigned, const TargetRegisterClass*> Res;
16748   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16749
16750   // Not found as a standard register?
16751   if (Res.second == 0) {
16752     // Map st(0) -> st(7) -> ST0
16753     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16754         tolower(Constraint[1]) == 's' &&
16755         tolower(Constraint[2]) == 't' &&
16756         Constraint[3] == '(' &&
16757         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16758         Constraint[5] == ')' &&
16759         Constraint[6] == '}') {
16760
16761       Res.first = X86::ST0+Constraint[4]-'0';
16762       Res.second = &X86::RFP80RegClass;
16763       return Res;
16764     }
16765
16766     // GCC allows "st(0)" to be called just plain "st".
16767     if (StringRef("{st}").equals_lower(Constraint)) {
16768       Res.first = X86::ST0;
16769       Res.second = &X86::RFP80RegClass;
16770       return Res;
16771     }
16772
16773     // flags -> EFLAGS
16774     if (StringRef("{flags}").equals_lower(Constraint)) {
16775       Res.first = X86::EFLAGS;
16776       Res.second = &X86::CCRRegClass;
16777       return Res;
16778     }
16779
16780     // 'A' means EAX + EDX.
16781     if (Constraint == "A") {
16782       Res.first = X86::EAX;
16783       Res.second = &X86::GR32_ADRegClass;
16784       return Res;
16785     }
16786     return Res;
16787   }
16788
16789   // Otherwise, check to see if this is a register class of the wrong value
16790   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16791   // turn into {ax},{dx}.
16792   if (Res.second->hasType(VT))
16793     return Res;   // Correct type already, nothing to do.
16794
16795   // All of the single-register GCC register classes map their values onto
16796   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16797   // really want an 8-bit or 32-bit register, map to the appropriate register
16798   // class and return the appropriate register.
16799   if (Res.second == &X86::GR16RegClass) {
16800     if (VT == MVT::i8) {
16801       unsigned DestReg = 0;
16802       switch (Res.first) {
16803       default: break;
16804       case X86::AX: DestReg = X86::AL; break;
16805       case X86::DX: DestReg = X86::DL; break;
16806       case X86::CX: DestReg = X86::CL; break;
16807       case X86::BX: DestReg = X86::BL; break;
16808       }
16809       if (DestReg) {
16810         Res.first = DestReg;
16811         Res.second = &X86::GR8RegClass;
16812       }
16813     } else if (VT == MVT::i32) {
16814       unsigned DestReg = 0;
16815       switch (Res.first) {
16816       default: break;
16817       case X86::AX: DestReg = X86::EAX; break;
16818       case X86::DX: DestReg = X86::EDX; break;
16819       case X86::CX: DestReg = X86::ECX; break;
16820       case X86::BX: DestReg = X86::EBX; break;
16821       case X86::SI: DestReg = X86::ESI; break;
16822       case X86::DI: DestReg = X86::EDI; break;
16823       case X86::BP: DestReg = X86::EBP; break;
16824       case X86::SP: DestReg = X86::ESP; break;
16825       }
16826       if (DestReg) {
16827         Res.first = DestReg;
16828         Res.second = &X86::GR32RegClass;
16829       }
16830     } else if (VT == MVT::i64) {
16831       unsigned DestReg = 0;
16832       switch (Res.first) {
16833       default: break;
16834       case X86::AX: DestReg = X86::RAX; break;
16835       case X86::DX: DestReg = X86::RDX; break;
16836       case X86::CX: DestReg = X86::RCX; break;
16837       case X86::BX: DestReg = X86::RBX; break;
16838       case X86::SI: DestReg = X86::RSI; break;
16839       case X86::DI: DestReg = X86::RDI; break;
16840       case X86::BP: DestReg = X86::RBP; break;
16841       case X86::SP: DestReg = X86::RSP; break;
16842       }
16843       if (DestReg) {
16844         Res.first = DestReg;
16845         Res.second = &X86::GR64RegClass;
16846       }
16847     }
16848   } else if (Res.second == &X86::FR32RegClass ||
16849              Res.second == &X86::FR64RegClass ||
16850              Res.second == &X86::VR128RegClass) {
16851     // Handle references to XMM physical registers that got mapped into the
16852     // wrong class.  This can happen with constraints like {xmm0} where the
16853     // target independent register mapper will just pick the first match it can
16854     // find, ignoring the required type.
16855
16856     if (VT == MVT::f32 || VT == MVT::i32)
16857       Res.second = &X86::FR32RegClass;
16858     else if (VT == MVT::f64 || VT == MVT::i64)
16859       Res.second = &X86::FR64RegClass;
16860     else if (X86::VR128RegClass.hasType(VT))
16861       Res.second = &X86::VR128RegClass;
16862     else if (X86::VR256RegClass.hasType(VT))
16863       Res.second = &X86::VR256RegClass;
16864   }
16865
16866   return Res;
16867 }