a3973ed963faf890e5dfcd9256aaf103c1f10c12
[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 = getDataLayout();
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     addBypassSlowDiv(32, 8);
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   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462   // support continuation, user-level threading, and etc.. As a result, no
463   // other SjLj exception interfaces are implemented and please don't build
464   // your own exception handling based on them.
465   // LLVM/Clang supports zero-cost DWARF exception handling.
466   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
468
469   // Darwin ABI issue.
470   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
471   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
473   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
474   if (Subtarget->is64Bit())
475     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
477   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
480     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
481     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
482     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
483     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
484   }
485   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
488   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
489   if (Subtarget->is64Bit()) {
490     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
492     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasSSE1())
496     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
497
498   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
499   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
500
501   // On X86 and X86-64, atomic operations are lowered to locked instructions.
502   // Locked instructions, in turn, have implicit fence semantics (all memory
503   // operations are flushed before issuing the locked instruction, and they
504   // are not buffered), so we can fold away the common pattern of
505   // fence-atomic-fence.
506   setShouldFoldAtomicFences(true);
507
508   // Expand certain atomics
509   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510     MVT VT = IntVTs[i];
511     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
514   }
515
516   if (!Subtarget->is64Bit()) {
517     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
529   }
530
531   if (Subtarget->hasCmpxchg16b()) {
532     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
533   }
534
535   // FIXME - use subtarget debug flags
536   if (!Subtarget->isTargetDarwin() &&
537       !Subtarget->isTargetELF() &&
538       !Subtarget->isTargetCygMing()) {
539     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
540   }
541
542   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
544   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
546   if (Subtarget->is64Bit()) {
547     setExceptionPointerRegister(X86::RAX);
548     setExceptionSelectorRegister(X86::RDX);
549   } else {
550     setExceptionPointerRegister(X86::EAX);
551     setExceptionSelectorRegister(X86::EDX);
552   }
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555
556   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558
559   setOperationAction(ISD::TRAP, MVT::Other, Legal);
560   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561
562   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
564   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
567     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
568   } else {
569     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
570     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
571   }
572
573   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
574   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
575
576   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578                        MVT::i64 : MVT::i32, Custom);
579   else if (TM.Options.EnableSegmentedStacks)
580     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581                        MVT::i64 : MVT::i32, Custom);
582   else
583     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584                        MVT::i64 : MVT::i32, Expand);
585
586   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587     // f32 and f64 use SSE.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, &X86::FR32RegClass);
590     addRegisterClass(MVT::f64, &X86::FR64RegClass);
591
592     // Use ANDPD to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f64, Custom);
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f64, Custom);
598     setOperationAction(ISD::FNEG , MVT::f32, Custom);
599
600     // Use ANDPD and ORPD to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // Lower this to FGETSIGNx86 plus an AND.
605     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607
608     // We don't support sin/cos/fmod
609     setOperationAction(ISD::FSIN , MVT::f64, Expand);
610     setOperationAction(ISD::FCOS , MVT::f64, Expand);
611     setOperationAction(ISD::FSIN , MVT::f32, Expand);
612     setOperationAction(ISD::FCOS , MVT::f32, Expand);
613
614     // Expand FP immediates into loads from the stack, except for the special
615     // cases we handle.
616     addLegalFPImmediate(APFloat(+0.0)); // xorpd
617     addLegalFPImmediate(APFloat(+0.0f)); // xorps
618   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619     // Use SSE for f32, x87 for f64.
620     // Set up the FP register classes.
621     addRegisterClass(MVT::f32, &X86::FR32RegClass);
622     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623
624     // Use ANDPS to simulate FABS.
625     setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627     // Use XORP to simulate FNEG.
628     setOperationAction(ISD::FNEG , MVT::f32, Custom);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631
632     // Use ANDPS and ORPS to simulate FCOPYSIGN.
633     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635
636     // We don't support sin/cos/fmod
637     setOperationAction(ISD::FSIN , MVT::f32, Expand);
638     setOperationAction(ISD::FCOS , MVT::f32, Expand);
639
640     // Special cases we handle for FP constants.
641     addLegalFPImmediate(APFloat(+0.0f)); // xorps
642     addLegalFPImmediate(APFloat(+0.0)); // FLD0
643     addLegalFPImmediate(APFloat(+1.0)); // FLD1
644     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646
647     if (!TM.Options.UnsafeFPMath) {
648       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
649       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
650     }
651   } else if (!TM.Options.UseSoftFloat) {
652     // f32 and f64 in x87.
653     // Set up the FP register classes.
654     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656
657     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
658     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661
662     if (!TM.Options.UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
664       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
666       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
667     }
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
676   }
677
678   // We don't support FMA.
679   setOperationAction(ISD::FMA, MVT::f64, Expand);
680   setOperationAction(ISD::FMA, MVT::f32, Expand);
681
682   // Long double always uses X87.
683   if (!TM.Options.UseSoftFloat) {
684     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687     {
688       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689       addLegalFPImmediate(TmpFlt);  // FLD0
690       TmpFlt.changeSign();
691       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
692
693       bool ignored;
694       APFloat TmpFlt2(+1.0);
695       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696                       &ignored);
697       addLegalFPImmediate(TmpFlt2);  // FLD1
698       TmpFlt2.changeSign();
699       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
700     }
701
702     if (!TM.Options.UnsafeFPMath) {
703       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
704       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
705     }
706
707     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
709     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
711     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712     setOperationAction(ISD::FMA, MVT::f80, Expand);
713   }
714
715   // Always use a library call for pow.
716   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
718   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
719
720   setOperationAction(ISD::FLOG, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP, MVT::f80, Expand);
724   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725
726   // First set operation action for all vector types to either promote
727   // (for widening) or expand (for scalarization). Then we will selectively
728   // turn on ones that can be effectively codegen'd.
729   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
789     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
790     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792       setTruncStoreAction((MVT::SimpleValueType)VT,
793                           (MVT::SimpleValueType)InnerVT, Expand);
794     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
797   }
798
799   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800   // with -msoft-float, disable use of MMX as well.
801   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803     // No operations on x86mmx supported, everything uses intrinsics.
804   }
805
806   // MMX-sized vectors (other than x86mmx) are expected to be expanded
807   // into smaller operations.
808   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
809   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
811   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
812   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
813   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
814   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
815   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
816   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
817   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
818   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
819   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
820   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
821   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
822   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
823   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
827   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
828   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
829   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
830   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
832   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
836   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
837
838   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
840
841     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
845     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
846     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
847     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
848     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
849     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
850     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
851     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
853   }
854
855   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
857
858     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859     // registers cannot be used even for integer operations.
860     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
864
865     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
866     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
867     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
868     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
869     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
870     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
871     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
872     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
873     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
874     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
875     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
879     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
880     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
881     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
882
883     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
886     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
887
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
889     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
892     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
893
894     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897       // Do not attempt to custom lower non-power-of-2 vectors
898       if (!isPowerOf2_32(VT.getVectorNumElements()))
899         continue;
900       // Do not attempt to custom lower non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
904       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
906     }
907
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
909     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
911     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
913     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
914
915     if (Subtarget->is64Bit()) {
916       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
917       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
918     }
919
920     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922       MVT VT = (MVT::SimpleValueType)i;
923
924       // Do not attempt to promote non-128-bit vectors
925       if (!VT.is128BitVector())
926         continue;
927
928       setOperationAction(ISD::AND,    VT, Promote);
929       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
930       setOperationAction(ISD::OR,     VT, Promote);
931       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
932       setOperationAction(ISD::XOR,    VT, Promote);
933       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
934       setOperationAction(ISD::LOAD,   VT, Promote);
935       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
936       setOperationAction(ISD::SELECT, VT, Promote);
937       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
938     }
939
940     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
941
942     // Custom lower v2i64 and v2f64 selects.
943     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
944     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
945     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
946     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
947
948     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
949     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
950
951     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
952     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
953
954     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
955     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
956
957     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
958   }
959
960   if (Subtarget->hasSSE41()) {
961     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
962     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
963     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
964     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
965     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
966     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
967     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
968     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
969     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
970     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
971
972     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
973     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
974
975     // FIXME: Do we need to handle scalar-to-vector here?
976     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
977
978     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
979     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
980     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
981     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
982     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
983
984     // i8 and i16 vectors are custom , because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal but thats only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     if (Subtarget->hasAVX2()) {
1017       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1018       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1019
1020       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1021       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1022
1023       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1024     } else {
1025       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1026       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1027
1028       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1029       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1030
1031       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1032     }
1033   }
1034
1035   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1036     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1039     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1042
1043     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1046
1047     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1066
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1071     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1072
1073     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1076
1077     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1080     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1081
1082     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1083     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1084
1085     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1089     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1090     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1092
1093     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1094     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1095     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1096
1097     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1098     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1099     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1100     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1101
1102     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1103       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1104       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1105       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1106       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1107       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1108       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1109     }
1110
1111     if (Subtarget->hasAVX2()) {
1112       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1113       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1114       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1115       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1116
1117       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1118       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1119       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1120       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1121
1122       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1123       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1125       // Don't lower v32i8 because there is no 128-bit byte mul
1126
1127       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1128
1129       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1130       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1131
1132       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1133       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1134
1135       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1136     } else {
1137       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1138       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1139       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1140       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1141
1142       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1143       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1144       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1145       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1146
1147       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1148       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1149       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1150       // Don't lower v32i8 because there is no 128-bit byte mul
1151
1152       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1153       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1154
1155       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1156       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1157
1158       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1159     }
1160
1161     // Custom lower several nodes for 256-bit types.
1162     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1163              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1164       MVT VT = (MVT::SimpleValueType)i;
1165
1166       // Extract subvector is special because the value type
1167       // (result) is 128-bit but the source is 256-bit wide.
1168       if (VT.is128BitVector())
1169         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1170
1171       // Do not attempt to custom lower other non-256-bit vectors
1172       if (!VT.is256BitVector())
1173         continue;
1174
1175       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1176       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1177       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1178       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1179       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1180       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1181       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1182     }
1183
1184     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1185     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1186       MVT VT = (MVT::SimpleValueType)i;
1187
1188       // Do not attempt to promote non-256-bit vectors
1189       if (!VT.is256BitVector())
1190         continue;
1191
1192       setOperationAction(ISD::AND,    VT, Promote);
1193       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1194       setOperationAction(ISD::OR,     VT, Promote);
1195       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1196       setOperationAction(ISD::XOR,    VT, Promote);
1197       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1198       setOperationAction(ISD::LOAD,   VT, Promote);
1199       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1200       setOperationAction(ISD::SELECT, VT, Promote);
1201       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1202     }
1203   }
1204
1205   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1206   // of this type with custom code.
1207   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1208            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1209     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1210                        Custom);
1211   }
1212
1213   // We want to custom lower some of our intrinsics.
1214   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1215   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1216
1217
1218   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1219   // handle type legalization for these operations here.
1220   //
1221   // FIXME: We really should do custom legalization for addition and
1222   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1223   // than generic legalization for 64-bit multiplication-with-overflow, though.
1224   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1225     // Add/Sub/Mul with overflow operations are custom lowered.
1226     MVT VT = IntVTs[i];
1227     setOperationAction(ISD::SADDO, VT, Custom);
1228     setOperationAction(ISD::UADDO, VT, Custom);
1229     setOperationAction(ISD::SSUBO, VT, Custom);
1230     setOperationAction(ISD::USUBO, VT, Custom);
1231     setOperationAction(ISD::SMULO, VT, Custom);
1232     setOperationAction(ISD::UMULO, VT, Custom);
1233   }
1234
1235   // There are no 8-bit 3-address imul/mul instructions
1236   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1237   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1238
1239   if (!Subtarget->is64Bit()) {
1240     // These libcalls are not available in 32-bit.
1241     setLibcallName(RTLIB::SHL_I128, 0);
1242     setLibcallName(RTLIB::SRL_I128, 0);
1243     setLibcallName(RTLIB::SRA_I128, 0);
1244   }
1245
1246   // We have target-specific dag combine patterns for the following nodes:
1247   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1248   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1249   setTargetDAGCombine(ISD::VSELECT);
1250   setTargetDAGCombine(ISD::SELECT);
1251   setTargetDAGCombine(ISD::SHL);
1252   setTargetDAGCombine(ISD::SRA);
1253   setTargetDAGCombine(ISD::SRL);
1254   setTargetDAGCombine(ISD::OR);
1255   setTargetDAGCombine(ISD::AND);
1256   setTargetDAGCombine(ISD::ADD);
1257   setTargetDAGCombine(ISD::FADD);
1258   setTargetDAGCombine(ISD::FSUB);
1259   setTargetDAGCombine(ISD::FMA);
1260   setTargetDAGCombine(ISD::SUB);
1261   setTargetDAGCombine(ISD::LOAD);
1262   setTargetDAGCombine(ISD::STORE);
1263   setTargetDAGCombine(ISD::ZERO_EXTEND);
1264   setTargetDAGCombine(ISD::ANY_EXTEND);
1265   setTargetDAGCombine(ISD::SIGN_EXTEND);
1266   setTargetDAGCombine(ISD::TRUNCATE);
1267   setTargetDAGCombine(ISD::SINT_TO_FP);
1268   setTargetDAGCombine(ISD::SETCC);
1269   if (Subtarget->is64Bit())
1270     setTargetDAGCombine(ISD::MUL);
1271   setTargetDAGCombine(ISD::XOR);
1272
1273   computeRegisterProperties();
1274
1275   // On Darwin, -Os means optimize for size without hurting performance,
1276   // do not reduce the limit.
1277   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1278   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1279   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1280   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1281   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1282   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1283   setPrefLoopAlignment(4); // 2^4 bytes.
1284   benefitFromCodePlacementOpt = true;
1285
1286   // Predictable cmov don't hurt on atom because it's in-order.
1287   predictableSelectIsExpensive = !Subtarget->isAtom();
1288
1289   setPrefFunctionAlignment(4); // 2^4 bytes.
1290 }
1291
1292
1293 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1294   if (!VT.isVector()) return MVT::i8;
1295   return VT.changeVectorElementTypeToInteger();
1296 }
1297
1298
1299 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1300 /// the desired ByVal argument alignment.
1301 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1302   if (MaxAlign == 16)
1303     return;
1304   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1305     if (VTy->getBitWidth() == 128)
1306       MaxAlign = 16;
1307   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1308     unsigned EltAlign = 0;
1309     getMaxByValAlign(ATy->getElementType(), EltAlign);
1310     if (EltAlign > MaxAlign)
1311       MaxAlign = EltAlign;
1312   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1313     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1314       unsigned EltAlign = 0;
1315       getMaxByValAlign(STy->getElementType(i), EltAlign);
1316       if (EltAlign > MaxAlign)
1317         MaxAlign = EltAlign;
1318       if (MaxAlign == 16)
1319         break;
1320     }
1321   }
1322 }
1323
1324 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1325 /// function arguments in the caller parameter area. For X86, aggregates
1326 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1327 /// are at 4-byte boundaries.
1328 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1329   if (Subtarget->is64Bit()) {
1330     // Max of 8 and alignment of type.
1331     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1332     if (TyAlign > 8)
1333       return TyAlign;
1334     return 8;
1335   }
1336
1337   unsigned Align = 4;
1338   if (Subtarget->hasSSE1())
1339     getMaxByValAlign(Ty, Align);
1340   return Align;
1341 }
1342
1343 /// getOptimalMemOpType - Returns the target specific optimal type for load
1344 /// and store operations as a result of memset, memcpy, and memmove
1345 /// lowering. If DstAlign is zero that means it's safe to destination
1346 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1347 /// means there isn't a need to check it against alignment requirement,
1348 /// probably because the source does not need to be loaded. If
1349 /// 'IsZeroVal' is true, that means it's safe to return a
1350 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1351 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1352 /// constant so it does not need to be loaded.
1353 /// It returns EVT::Other if the type should be determined using generic
1354 /// target-independent logic.
1355 EVT
1356 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1357                                        unsigned DstAlign, unsigned SrcAlign,
1358                                        bool IsZeroVal,
1359                                        bool MemcpyStrSrc,
1360                                        MachineFunction &MF) const {
1361   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1362   // linux.  This is because the stack realignment code can't handle certain
1363   // cases like PR2962.  This should be removed when PR2962 is fixed.
1364   const Function *F = MF.getFunction();
1365   if (IsZeroVal &&
1366       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1367     if (Size >= 16 &&
1368         (Subtarget->isUnalignedMemAccessFast() ||
1369          ((DstAlign == 0 || DstAlign >= 16) &&
1370           (SrcAlign == 0 || SrcAlign >= 16))) &&
1371         Subtarget->getStackAlignment() >= 16) {
1372       if (Subtarget->getStackAlignment() >= 32) {
1373         if (Subtarget->hasAVX2())
1374           return MVT::v8i32;
1375         if (Subtarget->hasAVX())
1376           return MVT::v8f32;
1377       }
1378       if (Subtarget->hasSSE2())
1379         return MVT::v4i32;
1380       if (Subtarget->hasSSE1())
1381         return MVT::v4f32;
1382     } else if (!MemcpyStrSrc && Size >= 8 &&
1383                !Subtarget->is64Bit() &&
1384                Subtarget->getStackAlignment() >= 8 &&
1385                Subtarget->hasSSE2()) {
1386       // Do not use f64 to lower memcpy if source is string constant. It's
1387       // better to use i32 to avoid the loads.
1388       return MVT::f64;
1389     }
1390   }
1391   if (Subtarget->is64Bit() && Size >= 8)
1392     return MVT::i64;
1393   return MVT::i32;
1394 }
1395
1396 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1397 /// current function.  The returned value is a member of the
1398 /// MachineJumpTableInfo::JTEntryKind enum.
1399 unsigned X86TargetLowering::getJumpTableEncoding() const {
1400   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1401   // symbol.
1402   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1403       Subtarget->isPICStyleGOT())
1404     return MachineJumpTableInfo::EK_Custom32;
1405
1406   // Otherwise, use the normal jump table encoding heuristics.
1407   return TargetLowering::getJumpTableEncoding();
1408 }
1409
1410 const MCExpr *
1411 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1412                                              const MachineBasicBlock *MBB,
1413                                              unsigned uid,MCContext &Ctx) const{
1414   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1415          Subtarget->isPICStyleGOT());
1416   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1417   // entries.
1418   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1419                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1420 }
1421
1422 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1423 /// jumptable.
1424 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1425                                                     SelectionDAG &DAG) const {
1426   if (!Subtarget->is64Bit())
1427     // This doesn't have DebugLoc associated with it, but is not really the
1428     // same as a Register.
1429     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1430   return Table;
1431 }
1432
1433 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1434 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1435 /// MCExpr.
1436 const MCExpr *X86TargetLowering::
1437 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1438                              MCContext &Ctx) const {
1439   // X86-64 uses RIP relative addressing based on the jump table label.
1440   if (Subtarget->isPICStyleRIPRel())
1441     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1442
1443   // Otherwise, the reference is relative to the PIC base.
1444   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1445 }
1446
1447 // FIXME: Why this routine is here? Move to RegInfo!
1448 std::pair<const TargetRegisterClass*, uint8_t>
1449 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1450   const TargetRegisterClass *RRC = 0;
1451   uint8_t Cost = 1;
1452   switch (VT.getSimpleVT().SimpleTy) {
1453   default:
1454     return TargetLowering::findRepresentativeClass(VT);
1455   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1456     RRC = Subtarget->is64Bit() ?
1457       (const TargetRegisterClass*)&X86::GR64RegClass :
1458       (const TargetRegisterClass*)&X86::GR32RegClass;
1459     break;
1460   case MVT::x86mmx:
1461     RRC = &X86::VR64RegClass;
1462     break;
1463   case MVT::f32: case MVT::f64:
1464   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1465   case MVT::v4f32: case MVT::v2f64:
1466   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1467   case MVT::v4f64:
1468     RRC = &X86::VR128RegClass;
1469     break;
1470   }
1471   return std::make_pair(RRC, Cost);
1472 }
1473
1474 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1475                                                unsigned &Offset) const {
1476   if (!Subtarget->isTargetLinux())
1477     return false;
1478
1479   if (Subtarget->is64Bit()) {
1480     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1481     Offset = 0x28;
1482     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1483       AddressSpace = 256;
1484     else
1485       AddressSpace = 257;
1486   } else {
1487     // %gs:0x14 on i386
1488     Offset = 0x14;
1489     AddressSpace = 256;
1490   }
1491   return true;
1492 }
1493
1494
1495 //===----------------------------------------------------------------------===//
1496 //               Return Value Calling Convention Implementation
1497 //===----------------------------------------------------------------------===//
1498
1499 #include "X86GenCallingConv.inc"
1500
1501 bool
1502 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1503                                   MachineFunction &MF, bool isVarArg,
1504                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1505                         LLVMContext &Context) const {
1506   SmallVector<CCValAssign, 16> RVLocs;
1507   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1508                  RVLocs, Context);
1509   return CCInfo.CheckReturn(Outs, RetCC_X86);
1510 }
1511
1512 SDValue
1513 X86TargetLowering::LowerReturn(SDValue Chain,
1514                                CallingConv::ID CallConv, bool isVarArg,
1515                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1516                                const SmallVectorImpl<SDValue> &OutVals,
1517                                DebugLoc dl, SelectionDAG &DAG) const {
1518   MachineFunction &MF = DAG.getMachineFunction();
1519   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1520
1521   SmallVector<CCValAssign, 16> RVLocs;
1522   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1523                  RVLocs, *DAG.getContext());
1524   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1525
1526   // Add the regs to the liveout set for the function.
1527   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1528   for (unsigned i = 0; i != RVLocs.size(); ++i)
1529     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1530       MRI.addLiveOut(RVLocs[i].getLocReg());
1531
1532   SDValue Flag;
1533
1534   SmallVector<SDValue, 6> RetOps;
1535   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1536   // Operand #1 = Bytes To Pop
1537   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1538                    MVT::i16));
1539
1540   // Copy the result values into the output registers.
1541   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1542     CCValAssign &VA = RVLocs[i];
1543     assert(VA.isRegLoc() && "Can only return in registers!");
1544     SDValue ValToCopy = OutVals[i];
1545     EVT ValVT = ValToCopy.getValueType();
1546
1547     // Promote values to the appropriate types
1548     if (VA.getLocInfo() == CCValAssign::SExt)
1549       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1550     else if (VA.getLocInfo() == CCValAssign::ZExt)
1551       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1552     else if (VA.getLocInfo() == CCValAssign::AExt)
1553       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1554     else if (VA.getLocInfo() == CCValAssign::BCvt)
1555       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1556
1557     // If this is x86-64, and we disabled SSE, we can't return FP values,
1558     // or SSE or MMX vectors.
1559     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1560          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1561           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1562       report_fatal_error("SSE register return with SSE disabled");
1563     }
1564     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1565     // llvm-gcc has never done it right and no one has noticed, so this
1566     // should be OK for now.
1567     if (ValVT == MVT::f64 &&
1568         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1569       report_fatal_error("SSE2 register return with SSE2 disabled");
1570
1571     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1572     // the RET instruction and handled by the FP Stackifier.
1573     if (VA.getLocReg() == X86::ST0 ||
1574         VA.getLocReg() == X86::ST1) {
1575       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1576       // change the value to the FP stack register class.
1577       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1578         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1579       RetOps.push_back(ValToCopy);
1580       // Don't emit a copytoreg.
1581       continue;
1582     }
1583
1584     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1585     // which is returned in RAX / RDX.
1586     if (Subtarget->is64Bit()) {
1587       if (ValVT == MVT::x86mmx) {
1588         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1589           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1590           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1591                                   ValToCopy);
1592           // If we don't have SSE2 available, convert to v4f32 so the generated
1593           // register is legal.
1594           if (!Subtarget->hasSSE2())
1595             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1596         }
1597       }
1598     }
1599
1600     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1601     Flag = Chain.getValue(1);
1602   }
1603
1604   // The x86-64 ABI for returning structs by value requires that we copy
1605   // the sret argument into %rax for the return. We saved the argument into
1606   // a virtual register in the entry block, so now we copy the value out
1607   // and into %rax.
1608   if (Subtarget->is64Bit() &&
1609       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1610     MachineFunction &MF = DAG.getMachineFunction();
1611     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1612     unsigned Reg = FuncInfo->getSRetReturnReg();
1613     assert(Reg &&
1614            "SRetReturnReg should have been set in LowerFormalArguments().");
1615     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1616
1617     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1618     Flag = Chain.getValue(1);
1619
1620     // RAX now acts like a return value.
1621     MRI.addLiveOut(X86::RAX);
1622   }
1623
1624   RetOps[0] = Chain;  // Update chain.
1625
1626   // Add the flag if we have it.
1627   if (Flag.getNode())
1628     RetOps.push_back(Flag);
1629
1630   return DAG.getNode(X86ISD::RET_FLAG, dl,
1631                      MVT::Other, &RetOps[0], RetOps.size());
1632 }
1633
1634 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1635   if (N->getNumValues() != 1)
1636     return false;
1637   if (!N->hasNUsesOfValue(1, 0))
1638     return false;
1639
1640   SDValue TCChain = Chain;
1641   SDNode *Copy = *N->use_begin();
1642   if (Copy->getOpcode() == ISD::CopyToReg) {
1643     // If the copy has a glue operand, we conservatively assume it isn't safe to
1644     // perform a tail call.
1645     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1646       return false;
1647     TCChain = Copy->getOperand(0);
1648   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1649     return false;
1650
1651   bool HasRet = false;
1652   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1653        UI != UE; ++UI) {
1654     if (UI->getOpcode() != X86ISD::RET_FLAG)
1655       return false;
1656     HasRet = true;
1657   }
1658
1659   if (!HasRet)
1660     return false;
1661
1662   Chain = TCChain;
1663   return true;
1664 }
1665
1666 EVT
1667 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1668                                             ISD::NodeType ExtendKind) const {
1669   MVT ReturnMVT;
1670   // TODO: Is this also valid on 32-bit?
1671   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1672     ReturnMVT = MVT::i8;
1673   else
1674     ReturnMVT = MVT::i32;
1675
1676   EVT MinVT = getRegisterType(Context, ReturnMVT);
1677   return VT.bitsLT(MinVT) ? MinVT : VT;
1678 }
1679
1680 /// LowerCallResult - Lower the result values of a call into the
1681 /// appropriate copies out of appropriate physical registers.
1682 ///
1683 SDValue
1684 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1685                                    CallingConv::ID CallConv, bool isVarArg,
1686                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1687                                    DebugLoc dl, SelectionDAG &DAG,
1688                                    SmallVectorImpl<SDValue> &InVals) const {
1689
1690   // Assign locations to each value returned by this call.
1691   SmallVector<CCValAssign, 16> RVLocs;
1692   bool Is64Bit = Subtarget->is64Bit();
1693   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1694                  getTargetMachine(), RVLocs, *DAG.getContext());
1695   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1696
1697   // Copy all of the result registers out of their specified physreg.
1698   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1699     CCValAssign &VA = RVLocs[i];
1700     EVT CopyVT = VA.getValVT();
1701
1702     // If this is x86-64, and we disabled SSE, we can't return FP values
1703     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1704         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1705       report_fatal_error("SSE register return with SSE disabled");
1706     }
1707
1708     SDValue Val;
1709
1710     // If this is a call to a function that returns an fp value on the floating
1711     // point stack, we must guarantee the value is popped from the stack, so
1712     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1713     // if the return value is not used. We use the FpPOP_RETVAL instruction
1714     // instead.
1715     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1716       // If we prefer to use the value in xmm registers, copy it out as f80 and
1717       // use a truncate to move it from fp stack reg to xmm reg.
1718       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1719       SDValue Ops[] = { Chain, InFlag };
1720       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1721                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1722       Val = Chain.getValue(0);
1723
1724       // Round the f80 to the right size, which also moves it to the appropriate
1725       // xmm register.
1726       if (CopyVT != VA.getValVT())
1727         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1728                           // This truncation won't change the value.
1729                           DAG.getIntPtrConstant(1));
1730     } else {
1731       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1732                                  CopyVT, InFlag).getValue(1);
1733       Val = Chain.getValue(0);
1734     }
1735     InFlag = Chain.getValue(2);
1736     InVals.push_back(Val);
1737   }
1738
1739   return Chain;
1740 }
1741
1742
1743 //===----------------------------------------------------------------------===//
1744 //                C & StdCall & Fast Calling Convention implementation
1745 //===----------------------------------------------------------------------===//
1746 //  StdCall calling convention seems to be standard for many Windows' API
1747 //  routines and around. It differs from C calling convention just a little:
1748 //  callee should clean up the stack, not caller. Symbols should be also
1749 //  decorated in some fancy way :) It doesn't support any vector arguments.
1750 //  For info on fast calling convention see Fast Calling Convention (tail call)
1751 //  implementation LowerX86_32FastCCCallTo.
1752
1753 /// CallIsStructReturn - Determines whether a call uses struct return
1754 /// semantics.
1755 enum StructReturnType {
1756   NotStructReturn,
1757   RegStructReturn,
1758   StackStructReturn
1759 };
1760 static StructReturnType
1761 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1762   if (Outs.empty())
1763     return NotStructReturn;
1764
1765   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1766   if (!Flags.isSRet())
1767     return NotStructReturn;
1768   if (Flags.isInReg())
1769     return RegStructReturn;
1770   return StackStructReturn;
1771 }
1772
1773 /// ArgsAreStructReturn - Determines whether a function uses struct
1774 /// return semantics.
1775 static StructReturnType
1776 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1777   if (Ins.empty())
1778     return NotStructReturn;
1779
1780   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1781   if (!Flags.isSRet())
1782     return NotStructReturn;
1783   if (Flags.isInReg())
1784     return RegStructReturn;
1785   return StackStructReturn;
1786 }
1787
1788 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1789 /// by "Src" to address "Dst" with size and alignment information specified by
1790 /// the specific parameter attribute. The copy will be passed as a byval
1791 /// function parameter.
1792 static SDValue
1793 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1794                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1795                           DebugLoc dl) {
1796   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1797
1798   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1799                        /*isVolatile*/false, /*AlwaysInline=*/true,
1800                        MachinePointerInfo(), MachinePointerInfo());
1801 }
1802
1803 /// IsTailCallConvention - Return true if the calling convention is one that
1804 /// supports tail call optimization.
1805 static bool IsTailCallConvention(CallingConv::ID CC) {
1806   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1807 }
1808
1809 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1810   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1811     return false;
1812
1813   CallSite CS(CI);
1814   CallingConv::ID CalleeCC = CS.getCallingConv();
1815   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1816     return false;
1817
1818   return true;
1819 }
1820
1821 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1822 /// a tailcall target by changing its ABI.
1823 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1824                                    bool GuaranteedTailCallOpt) {
1825   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1826 }
1827
1828 SDValue
1829 X86TargetLowering::LowerMemArgument(SDValue Chain,
1830                                     CallingConv::ID CallConv,
1831                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1832                                     DebugLoc dl, SelectionDAG &DAG,
1833                                     const CCValAssign &VA,
1834                                     MachineFrameInfo *MFI,
1835                                     unsigned i) const {
1836   // Create the nodes corresponding to a load from this parameter slot.
1837   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1838   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1839                               getTargetMachine().Options.GuaranteedTailCallOpt);
1840   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1841   EVT ValVT;
1842
1843   // If value is passed by pointer we have address passed instead of the value
1844   // itself.
1845   if (VA.getLocInfo() == CCValAssign::Indirect)
1846     ValVT = VA.getLocVT();
1847   else
1848     ValVT = VA.getValVT();
1849
1850   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1851   // changed with more analysis.
1852   // In case of tail call optimization mark all arguments mutable. Since they
1853   // could be overwritten by lowering of arguments in case of a tail call.
1854   if (Flags.isByVal()) {
1855     unsigned Bytes = Flags.getByValSize();
1856     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1857     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1858     return DAG.getFrameIndex(FI, getPointerTy());
1859   } else {
1860     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1861                                     VA.getLocMemOffset(), isImmutable);
1862     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1863     return DAG.getLoad(ValVT, dl, Chain, FIN,
1864                        MachinePointerInfo::getFixedStack(FI),
1865                        false, false, false, 0);
1866   }
1867 }
1868
1869 SDValue
1870 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1871                                         CallingConv::ID CallConv,
1872                                         bool isVarArg,
1873                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1874                                         DebugLoc dl,
1875                                         SelectionDAG &DAG,
1876                                         SmallVectorImpl<SDValue> &InVals)
1877                                           const {
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880
1881   const Function* Fn = MF.getFunction();
1882   if (Fn->hasExternalLinkage() &&
1883       Subtarget->isTargetCygMing() &&
1884       Fn->getName() == "main")
1885     FuncInfo->setForceFramePointer(true);
1886
1887   MachineFrameInfo *MFI = MF.getFrameInfo();
1888   bool Is64Bit = Subtarget->is64Bit();
1889   bool IsWindows = Subtarget->isTargetWindows();
1890   bool IsWin64 = Subtarget->isTargetWin64();
1891
1892   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1893          "Var args not supported with calling convention fastcc or ghc");
1894
1895   // Assign locations to all of the incoming arguments.
1896   SmallVector<CCValAssign, 16> ArgLocs;
1897   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1898                  ArgLocs, *DAG.getContext());
1899
1900   // Allocate shadow area for Win64
1901   if (IsWin64) {
1902     CCInfo.AllocateStack(32, 8);
1903   }
1904
1905   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1906
1907   unsigned LastVal = ~0U;
1908   SDValue ArgValue;
1909   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1910     CCValAssign &VA = ArgLocs[i];
1911     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1912     // places.
1913     assert(VA.getValNo() != LastVal &&
1914            "Don't support value assigned to multiple locs yet");
1915     (void)LastVal;
1916     LastVal = VA.getValNo();
1917
1918     if (VA.isRegLoc()) {
1919       EVT RegVT = VA.getLocVT();
1920       const TargetRegisterClass *RC;
1921       if (RegVT == MVT::i32)
1922         RC = &X86::GR32RegClass;
1923       else if (Is64Bit && RegVT == MVT::i64)
1924         RC = &X86::GR64RegClass;
1925       else if (RegVT == MVT::f32)
1926         RC = &X86::FR32RegClass;
1927       else if (RegVT == MVT::f64)
1928         RC = &X86::FR64RegClass;
1929       else if (RegVT.is256BitVector())
1930         RC = &X86::VR256RegClass;
1931       else if (RegVT.is128BitVector())
1932         RC = &X86::VR128RegClass;
1933       else if (RegVT == MVT::x86mmx)
1934         RC = &X86::VR64RegClass;
1935       else
1936         llvm_unreachable("Unknown argument type!");
1937
1938       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1939       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1940
1941       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1942       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1943       // right size.
1944       if (VA.getLocInfo() == CCValAssign::SExt)
1945         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1946                                DAG.getValueType(VA.getValVT()));
1947       else if (VA.getLocInfo() == CCValAssign::ZExt)
1948         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1949                                DAG.getValueType(VA.getValVT()));
1950       else if (VA.getLocInfo() == CCValAssign::BCvt)
1951         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1952
1953       if (VA.isExtInLoc()) {
1954         // Handle MMX values passed in XMM regs.
1955         if (RegVT.isVector()) {
1956           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1957                                  ArgValue);
1958         } else
1959           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1960       }
1961     } else {
1962       assert(VA.isMemLoc());
1963       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1964     }
1965
1966     // If value is passed via pointer - do a load.
1967     if (VA.getLocInfo() == CCValAssign::Indirect)
1968       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1969                              MachinePointerInfo(), false, false, false, 0);
1970
1971     InVals.push_back(ArgValue);
1972   }
1973
1974   // The x86-64 ABI for returning structs by value requires that we copy
1975   // the sret argument into %rax for the return. Save the argument into
1976   // a virtual register so that we can access it from the return points.
1977   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1978     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1979     unsigned Reg = FuncInfo->getSRetReturnReg();
1980     if (!Reg) {
1981       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1982       FuncInfo->setSRetReturnReg(Reg);
1983     }
1984     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1985     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1986   }
1987
1988   unsigned StackSize = CCInfo.getNextStackOffset();
1989   // Align stack specially for tail calls.
1990   if (FuncIsMadeTailCallSafe(CallConv,
1991                              MF.getTarget().Options.GuaranteedTailCallOpt))
1992     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1993
1994   // If the function takes variable number of arguments, make a frame index for
1995   // the start of the first vararg value... for expansion of llvm.va_start.
1996   if (isVarArg) {
1997     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1998                     CallConv != CallingConv::X86_ThisCall)) {
1999       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2000     }
2001     if (Is64Bit) {
2002       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2003
2004       // FIXME: We should really autogenerate these arrays
2005       static const uint16_t GPR64ArgRegsWin64[] = {
2006         X86::RCX, X86::RDX, X86::R8,  X86::R9
2007       };
2008       static const uint16_t GPR64ArgRegs64Bit[] = {
2009         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2010       };
2011       static const uint16_t XMMArgRegs64Bit[] = {
2012         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2013         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2014       };
2015       const uint16_t *GPR64ArgRegs;
2016       unsigned NumXMMRegs = 0;
2017
2018       if (IsWin64) {
2019         // The XMM registers which might contain var arg parameters are shadowed
2020         // in their paired GPR.  So we only need to save the GPR to their home
2021         // slots.
2022         TotalNumIntRegs = 4;
2023         GPR64ArgRegs = GPR64ArgRegsWin64;
2024       } else {
2025         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2026         GPR64ArgRegs = GPR64ArgRegs64Bit;
2027
2028         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2029                                                 TotalNumXMMRegs);
2030       }
2031       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2032                                                        TotalNumIntRegs);
2033
2034       bool NoImplicitFloatOps = Fn->getFnAttributes().
2035         hasAttribute(Attributes::NoImplicitFloat);
2036       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2037              "SSE register cannot be used when SSE is disabled!");
2038       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2039                NoImplicitFloatOps) &&
2040              "SSE register cannot be used when SSE is disabled!");
2041       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2042           !Subtarget->hasSSE1())
2043         // Kernel mode asks for SSE to be disabled, so don't push them
2044         // on the stack.
2045         TotalNumXMMRegs = 0;
2046
2047       if (IsWin64) {
2048         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2049         // Get to the caller-allocated home save location.  Add 8 to account
2050         // for the return address.
2051         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2052         FuncInfo->setRegSaveFrameIndex(
2053           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2054         // Fixup to set vararg frame on shadow area (4 x i64).
2055         if (NumIntRegs < 4)
2056           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2057       } else {
2058         // For X86-64, if there are vararg parameters that are passed via
2059         // registers, then we must store them to their spots on the stack so
2060         // they may be loaded by deferencing the result of va_next.
2061         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2062         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2063         FuncInfo->setRegSaveFrameIndex(
2064           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2065                                false));
2066       }
2067
2068       // Store the integer parameter registers.
2069       SmallVector<SDValue, 8> MemOps;
2070       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2071                                         getPointerTy());
2072       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2073       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2074         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2075                                   DAG.getIntPtrConstant(Offset));
2076         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2077                                      &X86::GR64RegClass);
2078         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2079         SDValue Store =
2080           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2081                        MachinePointerInfo::getFixedStack(
2082                          FuncInfo->getRegSaveFrameIndex(), Offset),
2083                        false, false, 0);
2084         MemOps.push_back(Store);
2085         Offset += 8;
2086       }
2087
2088       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2089         // Now store the XMM (fp + vector) parameter registers.
2090         SmallVector<SDValue, 11> SaveXMMOps;
2091         SaveXMMOps.push_back(Chain);
2092
2093         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2094         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2095         SaveXMMOps.push_back(ALVal);
2096
2097         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2098                                FuncInfo->getRegSaveFrameIndex()));
2099         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2100                                FuncInfo->getVarArgsFPOffset()));
2101
2102         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2103           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2104                                        &X86::VR128RegClass);
2105           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2106           SaveXMMOps.push_back(Val);
2107         }
2108         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2109                                      MVT::Other,
2110                                      &SaveXMMOps[0], SaveXMMOps.size()));
2111       }
2112
2113       if (!MemOps.empty())
2114         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115                             &MemOps[0], MemOps.size());
2116     }
2117   }
2118
2119   // Some CCs need callee pop.
2120   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2121                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2122     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2123   } else {
2124     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2125     // If this is an sret function, the return should pop the hidden pointer.
2126     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2127         argsAreStructReturn(Ins) == StackStructReturn)
2128       FuncInfo->setBytesToPopOnReturn(4);
2129   }
2130
2131   if (!Is64Bit) {
2132     // RegSaveFrameIndex is X86-64 only.
2133     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2134     if (CallConv == CallingConv::X86_FastCall ||
2135         CallConv == CallingConv::X86_ThisCall)
2136       // fastcc functions can't have varargs.
2137       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2138   }
2139
2140   FuncInfo->setArgumentStackSize(StackSize);
2141
2142   return Chain;
2143 }
2144
2145 SDValue
2146 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2147                                     SDValue StackPtr, SDValue Arg,
2148                                     DebugLoc dl, SelectionDAG &DAG,
2149                                     const CCValAssign &VA,
2150                                     ISD::ArgFlagsTy Flags) const {
2151   unsigned LocMemOffset = VA.getLocMemOffset();
2152   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2153   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2154   if (Flags.isByVal())
2155     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2156
2157   return DAG.getStore(Chain, dl, Arg, PtrOff,
2158                       MachinePointerInfo::getStack(LocMemOffset),
2159                       false, false, 0);
2160 }
2161
2162 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2163 /// optimization is performed and it is required.
2164 SDValue
2165 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2166                                            SDValue &OutRetAddr, SDValue Chain,
2167                                            bool IsTailCall, bool Is64Bit,
2168                                            int FPDiff, DebugLoc dl) const {
2169   // Adjust the Return address stack slot.
2170   EVT VT = getPointerTy();
2171   OutRetAddr = getReturnAddressFrameIndex(DAG);
2172
2173   // Load the "old" Return address.
2174   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2175                            false, false, false, 0);
2176   return SDValue(OutRetAddr.getNode(), 1);
2177 }
2178
2179 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2180 /// optimization is performed and it is required (FPDiff!=0).
2181 static SDValue
2182 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2183                          SDValue Chain, SDValue RetAddrFrIdx,
2184                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2185   // Store the return address to the appropriate stack slot.
2186   if (!FPDiff) return Chain;
2187   // Calculate the new stack slot for the return address.
2188   int SlotSize = Is64Bit ? 8 : 4;
2189   int NewReturnAddrFI =
2190     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2191   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2192   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2193   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2194                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2195                        false, false, 0);
2196   return Chain;
2197 }
2198
2199 SDValue
2200 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2201                              SmallVectorImpl<SDValue> &InVals) const {
2202   SelectionDAG &DAG                     = CLI.DAG;
2203   DebugLoc &dl                          = CLI.DL;
2204   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2205   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2206   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2207   SDValue Chain                         = CLI.Chain;
2208   SDValue Callee                        = CLI.Callee;
2209   CallingConv::ID CallConv              = CLI.CallConv;
2210   bool &isTailCall                      = CLI.IsTailCall;
2211   bool isVarArg                         = CLI.IsVarArg;
2212
2213   MachineFunction &MF = DAG.getMachineFunction();
2214   bool Is64Bit        = Subtarget->is64Bit();
2215   bool IsWin64        = Subtarget->isTargetWin64();
2216   bool IsWindows      = Subtarget->isTargetWindows();
2217   StructReturnType SR = callIsStructReturn(Outs);
2218   bool IsSibcall      = false;
2219
2220   if (MF.getTarget().Options.DisableTailCalls)
2221     isTailCall = false;
2222
2223   if (isTailCall) {
2224     // Check if it's really possible to do a tail call.
2225     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2226                     isVarArg, SR != NotStructReturn,
2227                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2228                     Outs, OutVals, Ins, DAG);
2229
2230     // Sibcalls are automatically detected tailcalls which do not require
2231     // ABI changes.
2232     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2233       IsSibcall = true;
2234
2235     if (isTailCall)
2236       ++NumTailCalls;
2237   }
2238
2239   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2240          "Var args not supported with calling convention fastcc or ghc");
2241
2242   // Analyze operands of the call, assigning locations to each operand.
2243   SmallVector<CCValAssign, 16> ArgLocs;
2244   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2245                  ArgLocs, *DAG.getContext());
2246
2247   // Allocate shadow area for Win64
2248   if (IsWin64) {
2249     CCInfo.AllocateStack(32, 8);
2250   }
2251
2252   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2253
2254   // Get a count of how many bytes are to be pushed on the stack.
2255   unsigned NumBytes = CCInfo.getNextStackOffset();
2256   if (IsSibcall)
2257     // This is a sibcall. The memory operands are available in caller's
2258     // own caller's stack.
2259     NumBytes = 0;
2260   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2261            IsTailCallConvention(CallConv))
2262     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2263
2264   int FPDiff = 0;
2265   if (isTailCall && !IsSibcall) {
2266     // Lower arguments at fp - stackoffset + fpdiff.
2267     unsigned NumBytesCallerPushed =
2268       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2269     FPDiff = NumBytesCallerPushed - NumBytes;
2270
2271     // Set the delta of movement of the returnaddr stackslot.
2272     // But only set if delta is greater than previous delta.
2273     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2274       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2275   }
2276
2277   if (!IsSibcall)
2278     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2279
2280   SDValue RetAddrFrIdx;
2281   // Load return address for tail calls.
2282   if (isTailCall && FPDiff)
2283     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2284                                     Is64Bit, FPDiff, dl);
2285
2286   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2287   SmallVector<SDValue, 8> MemOpChains;
2288   SDValue StackPtr;
2289
2290   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2291   // of tail call optimization arguments are handle later.
2292   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2293     CCValAssign &VA = ArgLocs[i];
2294     EVT RegVT = VA.getLocVT();
2295     SDValue Arg = OutVals[i];
2296     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2297     bool isByVal = Flags.isByVal();
2298
2299     // Promote the value if needed.
2300     switch (VA.getLocInfo()) {
2301     default: llvm_unreachable("Unknown loc info!");
2302     case CCValAssign::Full: break;
2303     case CCValAssign::SExt:
2304       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2305       break;
2306     case CCValAssign::ZExt:
2307       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2308       break;
2309     case CCValAssign::AExt:
2310       if (RegVT.is128BitVector()) {
2311         // Special case: passing MMX values in XMM registers.
2312         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2313         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2314         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2315       } else
2316         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2317       break;
2318     case CCValAssign::BCvt:
2319       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2320       break;
2321     case CCValAssign::Indirect: {
2322       // Store the argument.
2323       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2324       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2325       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2326                            MachinePointerInfo::getFixedStack(FI),
2327                            false, false, 0);
2328       Arg = SpillSlot;
2329       break;
2330     }
2331     }
2332
2333     if (VA.isRegLoc()) {
2334       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2335       if (isVarArg && IsWin64) {
2336         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2337         // shadow reg if callee is a varargs function.
2338         unsigned ShadowReg = 0;
2339         switch (VA.getLocReg()) {
2340         case X86::XMM0: ShadowReg = X86::RCX; break;
2341         case X86::XMM1: ShadowReg = X86::RDX; break;
2342         case X86::XMM2: ShadowReg = X86::R8; break;
2343         case X86::XMM3: ShadowReg = X86::R9; break;
2344         }
2345         if (ShadowReg)
2346           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2347       }
2348     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2349       assert(VA.isMemLoc());
2350       if (StackPtr.getNode() == 0)
2351         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2352       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2353                                              dl, DAG, VA, Flags));
2354     }
2355   }
2356
2357   if (!MemOpChains.empty())
2358     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2359                         &MemOpChains[0], MemOpChains.size());
2360
2361   if (Subtarget->isPICStyleGOT()) {
2362     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2363     // GOT pointer.
2364     if (!isTailCall) {
2365       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2366                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2367     } else {
2368       // If we are tail calling and generating PIC/GOT style code load the
2369       // address of the callee into ECX. The value in ecx is used as target of
2370       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2371       // for tail calls on PIC/GOT architectures. Normally we would just put the
2372       // address of GOT into ebx and then call target@PLT. But for tail calls
2373       // ebx would be restored (since ebx is callee saved) before jumping to the
2374       // target@PLT.
2375
2376       // Note: The actual moving to ECX is done further down.
2377       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2378       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2379           !G->getGlobal()->hasProtectedVisibility())
2380         Callee = LowerGlobalAddress(Callee, DAG);
2381       else if (isa<ExternalSymbolSDNode>(Callee))
2382         Callee = LowerExternalSymbol(Callee, DAG);
2383     }
2384   }
2385
2386   if (Is64Bit && isVarArg && !IsWin64) {
2387     // From AMD64 ABI document:
2388     // For calls that may call functions that use varargs or stdargs
2389     // (prototype-less calls or calls to functions containing ellipsis (...) in
2390     // the declaration) %al is used as hidden argument to specify the number
2391     // of SSE registers used. The contents of %al do not need to match exactly
2392     // the number of registers, but must be an ubound on the number of SSE
2393     // registers used and is in the range 0 - 8 inclusive.
2394
2395     // Count the number of XMM registers allocated.
2396     static const uint16_t XMMArgRegs[] = {
2397       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2398       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2399     };
2400     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2401     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2402            && "SSE registers cannot be used when SSE is disabled");
2403
2404     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2405                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2406   }
2407
2408   // For tail calls lower the arguments to the 'real' stack slot.
2409   if (isTailCall) {
2410     // Force all the incoming stack arguments to be loaded from the stack
2411     // before any new outgoing arguments are stored to the stack, because the
2412     // outgoing stack slots may alias the incoming argument stack slots, and
2413     // the alias isn't otherwise explicit. This is slightly more conservative
2414     // than necessary, because it means that each store effectively depends
2415     // on every argument instead of just those arguments it would clobber.
2416     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2417
2418     SmallVector<SDValue, 8> MemOpChains2;
2419     SDValue FIN;
2420     int FI = 0;
2421     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2422       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2423         CCValAssign &VA = ArgLocs[i];
2424         if (VA.isRegLoc())
2425           continue;
2426         assert(VA.isMemLoc());
2427         SDValue Arg = OutVals[i];
2428         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2429         // Create frame index.
2430         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2431         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2432         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2433         FIN = DAG.getFrameIndex(FI, getPointerTy());
2434
2435         if (Flags.isByVal()) {
2436           // Copy relative to framepointer.
2437           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2438           if (StackPtr.getNode() == 0)
2439             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2440                                           getPointerTy());
2441           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2442
2443           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2444                                                            ArgChain,
2445                                                            Flags, DAG, dl));
2446         } else {
2447           // Store relative to framepointer.
2448           MemOpChains2.push_back(
2449             DAG.getStore(ArgChain, dl, Arg, FIN,
2450                          MachinePointerInfo::getFixedStack(FI),
2451                          false, false, 0));
2452         }
2453       }
2454     }
2455
2456     if (!MemOpChains2.empty())
2457       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2458                           &MemOpChains2[0], MemOpChains2.size());
2459
2460     // Store the return address to the appropriate stack slot.
2461     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2462                                      FPDiff, dl);
2463   }
2464
2465   // Build a sequence of copy-to-reg nodes chained together with token chain
2466   // and flag operands which copy the outgoing args into registers.
2467   SDValue InFlag;
2468   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2469     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2470                              RegsToPass[i].second, InFlag);
2471     InFlag = Chain.getValue(1);
2472   }
2473
2474   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2475     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2476     // In the 64-bit large code model, we have to make all calls
2477     // through a register, since the call instruction's 32-bit
2478     // pc-relative offset may not be large enough to hold the whole
2479     // address.
2480   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2481     // If the callee is a GlobalAddress node (quite common, every direct call
2482     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2483     // it.
2484
2485     // We should use extra load for direct calls to dllimported functions in
2486     // non-JIT mode.
2487     const GlobalValue *GV = G->getGlobal();
2488     if (!GV->hasDLLImportLinkage()) {
2489       unsigned char OpFlags = 0;
2490       bool ExtraLoad = false;
2491       unsigned WrapperKind = ISD::DELETED_NODE;
2492
2493       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2494       // external symbols most go through the PLT in PIC mode.  If the symbol
2495       // has hidden or protected visibility, or if it is static or local, then
2496       // we don't need to use the PLT - we can directly call it.
2497       if (Subtarget->isTargetELF() &&
2498           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2499           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2500         OpFlags = X86II::MO_PLT;
2501       } else if (Subtarget->isPICStyleStubAny() &&
2502                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2503                  (!Subtarget->getTargetTriple().isMacOSX() ||
2504                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2505         // PC-relative references to external symbols should go through $stub,
2506         // unless we're building with the leopard linker or later, which
2507         // automatically synthesizes these stubs.
2508         OpFlags = X86II::MO_DARWIN_STUB;
2509       } else if (Subtarget->isPICStyleRIPRel() &&
2510                  isa<Function>(GV) &&
2511                  cast<Function>(GV)->getFnAttributes().
2512                    hasAttribute(Attributes::NonLazyBind)) {
2513         // If the function is marked as non-lazy, generate an indirect call
2514         // which loads from the GOT directly. This avoids runtime overhead
2515         // at the cost of eager binding (and one extra byte of encoding).
2516         OpFlags = X86II::MO_GOTPCREL;
2517         WrapperKind = X86ISD::WrapperRIP;
2518         ExtraLoad = true;
2519       }
2520
2521       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2522                                           G->getOffset(), OpFlags);
2523
2524       // Add a wrapper if needed.
2525       if (WrapperKind != ISD::DELETED_NODE)
2526         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2527       // Add extra indirection if needed.
2528       if (ExtraLoad)
2529         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2530                              MachinePointerInfo::getGOT(),
2531                              false, false, false, 0);
2532     }
2533   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2534     unsigned char OpFlags = 0;
2535
2536     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2537     // external symbols should go through the PLT.
2538     if (Subtarget->isTargetELF() &&
2539         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2540       OpFlags = X86II::MO_PLT;
2541     } else if (Subtarget->isPICStyleStubAny() &&
2542                (!Subtarget->getTargetTriple().isMacOSX() ||
2543                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2544       // PC-relative references to external symbols should go through $stub,
2545       // unless we're building with the leopard linker or later, which
2546       // automatically synthesizes these stubs.
2547       OpFlags = X86II::MO_DARWIN_STUB;
2548     }
2549
2550     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2551                                          OpFlags);
2552   }
2553
2554   // Returns a chain & a flag for retval copy to use.
2555   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2556   SmallVector<SDValue, 8> Ops;
2557
2558   if (!IsSibcall && isTailCall) {
2559     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2560                            DAG.getIntPtrConstant(0, true), InFlag);
2561     InFlag = Chain.getValue(1);
2562   }
2563
2564   Ops.push_back(Chain);
2565   Ops.push_back(Callee);
2566
2567   if (isTailCall)
2568     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2569
2570   // Add argument registers to the end of the list so that they are known live
2571   // into the call.
2572   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2573     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2574                                   RegsToPass[i].second.getValueType()));
2575
2576   // Add a register mask operand representing the call-preserved registers.
2577   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2578   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2579   assert(Mask && "Missing call preserved mask for calling convention");
2580   Ops.push_back(DAG.getRegisterMask(Mask));
2581
2582   if (InFlag.getNode())
2583     Ops.push_back(InFlag);
2584
2585   if (isTailCall) {
2586     // We used to do:
2587     //// If this is the first return lowered for this function, add the regs
2588     //// to the liveout set for the function.
2589     // This isn't right, although it's probably harmless on x86; liveouts
2590     // should be computed from returns not tail calls.  Consider a void
2591     // function making a tail call to a function returning int.
2592     return DAG.getNode(X86ISD::TC_RETURN, dl,
2593                        NodeTys, &Ops[0], Ops.size());
2594   }
2595
2596   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2597   InFlag = Chain.getValue(1);
2598
2599   // Create the CALLSEQ_END node.
2600   unsigned NumBytesForCalleeToPush;
2601   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2602                        getTargetMachine().Options.GuaranteedTailCallOpt))
2603     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2604   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2605            SR == StackStructReturn)
2606     // If this is a call to a struct-return function, the callee
2607     // pops the hidden struct pointer, so we have to push it back.
2608     // This is common for Darwin/X86, Linux & Mingw32 targets.
2609     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2610     NumBytesForCalleeToPush = 4;
2611   else
2612     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2613
2614   // Returns a flag for retval copy to use.
2615   if (!IsSibcall) {
2616     Chain = DAG.getCALLSEQ_END(Chain,
2617                                DAG.getIntPtrConstant(NumBytes, true),
2618                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2619                                                      true),
2620                                InFlag);
2621     InFlag = Chain.getValue(1);
2622   }
2623
2624   // Handle result values, copying them out of physregs into vregs that we
2625   // return.
2626   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2627                          Ins, dl, DAG, InVals);
2628 }
2629
2630
2631 //===----------------------------------------------------------------------===//
2632 //                Fast Calling Convention (tail call) implementation
2633 //===----------------------------------------------------------------------===//
2634
2635 //  Like std call, callee cleans arguments, convention except that ECX is
2636 //  reserved for storing the tail called function address. Only 2 registers are
2637 //  free for argument passing (inreg). Tail call optimization is performed
2638 //  provided:
2639 //                * tailcallopt is enabled
2640 //                * caller/callee are fastcc
2641 //  On X86_64 architecture with GOT-style position independent code only local
2642 //  (within module) calls are supported at the moment.
2643 //  To keep the stack aligned according to platform abi the function
2644 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2645 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2646 //  If a tail called function callee has more arguments than the caller the
2647 //  caller needs to make sure that there is room to move the RETADDR to. This is
2648 //  achieved by reserving an area the size of the argument delta right after the
2649 //  original REtADDR, but before the saved framepointer or the spilled registers
2650 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2651 //  stack layout:
2652 //    arg1
2653 //    arg2
2654 //    RETADDR
2655 //    [ new RETADDR
2656 //      move area ]
2657 //    (possible EBP)
2658 //    ESI
2659 //    EDI
2660 //    local1 ..
2661
2662 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2663 /// for a 16 byte align requirement.
2664 unsigned
2665 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2666                                                SelectionDAG& DAG) const {
2667   MachineFunction &MF = DAG.getMachineFunction();
2668   const TargetMachine &TM = MF.getTarget();
2669   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2670   unsigned StackAlignment = TFI.getStackAlignment();
2671   uint64_t AlignMask = StackAlignment - 1;
2672   int64_t Offset = StackSize;
2673   uint64_t SlotSize = TD->getPointerSize(0);
2674   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2675     // Number smaller than 12 so just add the difference.
2676     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2677   } else {
2678     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2679     Offset = ((~AlignMask) & Offset) + StackAlignment +
2680       (StackAlignment-SlotSize);
2681   }
2682   return Offset;
2683 }
2684
2685 /// MatchingStackOffset - Return true if the given stack call argument is
2686 /// already available in the same position (relatively) of the caller's
2687 /// incoming argument stack.
2688 static
2689 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2690                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2691                          const X86InstrInfo *TII) {
2692   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2693   int FI = INT_MAX;
2694   if (Arg.getOpcode() == ISD::CopyFromReg) {
2695     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2696     if (!TargetRegisterInfo::isVirtualRegister(VR))
2697       return false;
2698     MachineInstr *Def = MRI->getVRegDef(VR);
2699     if (!Def)
2700       return false;
2701     if (!Flags.isByVal()) {
2702       if (!TII->isLoadFromStackSlot(Def, FI))
2703         return false;
2704     } else {
2705       unsigned Opcode = Def->getOpcode();
2706       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2707           Def->getOperand(1).isFI()) {
2708         FI = Def->getOperand(1).getIndex();
2709         Bytes = Flags.getByValSize();
2710       } else
2711         return false;
2712     }
2713   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2714     if (Flags.isByVal())
2715       // ByVal argument is passed in as a pointer but it's now being
2716       // dereferenced. e.g.
2717       // define @foo(%struct.X* %A) {
2718       //   tail call @bar(%struct.X* byval %A)
2719       // }
2720       return false;
2721     SDValue Ptr = Ld->getBasePtr();
2722     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2723     if (!FINode)
2724       return false;
2725     FI = FINode->getIndex();
2726   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2727     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2728     FI = FINode->getIndex();
2729     Bytes = Flags.getByValSize();
2730   } else
2731     return false;
2732
2733   assert(FI != INT_MAX);
2734   if (!MFI->isFixedObjectIndex(FI))
2735     return false;
2736   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2737 }
2738
2739 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2740 /// for tail call optimization. Targets which want to do tail call
2741 /// optimization should implement this function.
2742 bool
2743 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2744                                                      CallingConv::ID CalleeCC,
2745                                                      bool isVarArg,
2746                                                      bool isCalleeStructRet,
2747                                                      bool isCallerStructRet,
2748                                                      Type *RetTy,
2749                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2750                                     const SmallVectorImpl<SDValue> &OutVals,
2751                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2752                                                      SelectionDAG& DAG) const {
2753   if (!IsTailCallConvention(CalleeCC) &&
2754       CalleeCC != CallingConv::C)
2755     return false;
2756
2757   // If -tailcallopt is specified, make fastcc functions tail-callable.
2758   const MachineFunction &MF = DAG.getMachineFunction();
2759   const Function *CallerF = DAG.getMachineFunction().getFunction();
2760
2761   // If the function return type is x86_fp80 and the callee return type is not,
2762   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2763   // perform a tailcall optimization here.
2764   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2765     return false;
2766
2767   CallingConv::ID CallerCC = CallerF->getCallingConv();
2768   bool CCMatch = CallerCC == CalleeCC;
2769
2770   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2771     if (IsTailCallConvention(CalleeCC) && CCMatch)
2772       return true;
2773     return false;
2774   }
2775
2776   // Look for obvious safe cases to perform tail call optimization that do not
2777   // require ABI changes. This is what gcc calls sibcall.
2778
2779   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2780   // emit a special epilogue.
2781   if (RegInfo->needsStackRealignment(MF))
2782     return false;
2783
2784   // Also avoid sibcall optimization if either caller or callee uses struct
2785   // return semantics.
2786   if (isCalleeStructRet || isCallerStructRet)
2787     return false;
2788
2789   // An stdcall caller is expected to clean up its arguments; the callee
2790   // isn't going to do that.
2791   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2792     return false;
2793
2794   // Do not sibcall optimize vararg calls unless all arguments are passed via
2795   // registers.
2796   if (isVarArg && !Outs.empty()) {
2797
2798     // Optimizing for varargs on Win64 is unlikely to be safe without
2799     // additional testing.
2800     if (Subtarget->isTargetWin64())
2801       return false;
2802
2803     SmallVector<CCValAssign, 16> ArgLocs;
2804     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2805                    getTargetMachine(), ArgLocs, *DAG.getContext());
2806
2807     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2808     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2809       if (!ArgLocs[i].isRegLoc())
2810         return false;
2811   }
2812
2813   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2814   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2815   // this into a sibcall.
2816   bool Unused = false;
2817   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2818     if (!Ins[i].Used) {
2819       Unused = true;
2820       break;
2821     }
2822   }
2823   if (Unused) {
2824     SmallVector<CCValAssign, 16> RVLocs;
2825     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2826                    getTargetMachine(), RVLocs, *DAG.getContext());
2827     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2828     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2829       CCValAssign &VA = RVLocs[i];
2830       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2831         return false;
2832     }
2833   }
2834
2835   // If the calling conventions do not match, then we'd better make sure the
2836   // results are returned in the same way as what the caller expects.
2837   if (!CCMatch) {
2838     SmallVector<CCValAssign, 16> RVLocs1;
2839     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2840                     getTargetMachine(), RVLocs1, *DAG.getContext());
2841     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2842
2843     SmallVector<CCValAssign, 16> RVLocs2;
2844     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2845                     getTargetMachine(), RVLocs2, *DAG.getContext());
2846     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2847
2848     if (RVLocs1.size() != RVLocs2.size())
2849       return false;
2850     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2851       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2852         return false;
2853       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2854         return false;
2855       if (RVLocs1[i].isRegLoc()) {
2856         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2857           return false;
2858       } else {
2859         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2860           return false;
2861       }
2862     }
2863   }
2864
2865   // If the callee takes no arguments then go on to check the results of the
2866   // call.
2867   if (!Outs.empty()) {
2868     // Check if stack adjustment is needed. For now, do not do this if any
2869     // argument is passed on the stack.
2870     SmallVector<CCValAssign, 16> ArgLocs;
2871     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2872                    getTargetMachine(), ArgLocs, *DAG.getContext());
2873
2874     // Allocate shadow area for Win64
2875     if (Subtarget->isTargetWin64()) {
2876       CCInfo.AllocateStack(32, 8);
2877     }
2878
2879     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2880     if (CCInfo.getNextStackOffset()) {
2881       MachineFunction &MF = DAG.getMachineFunction();
2882       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2883         return false;
2884
2885       // Check if the arguments are already laid out in the right way as
2886       // the caller's fixed stack objects.
2887       MachineFrameInfo *MFI = MF.getFrameInfo();
2888       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2889       const X86InstrInfo *TII =
2890         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2891       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2892         CCValAssign &VA = ArgLocs[i];
2893         SDValue Arg = OutVals[i];
2894         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2895         if (VA.getLocInfo() == CCValAssign::Indirect)
2896           return false;
2897         if (!VA.isRegLoc()) {
2898           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2899                                    MFI, MRI, TII))
2900             return false;
2901         }
2902       }
2903     }
2904
2905     // If the tailcall address may be in a register, then make sure it's
2906     // possible to register allocate for it. In 32-bit, the call address can
2907     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2908     // callee-saved registers are restored. These happen to be the same
2909     // registers used to pass 'inreg' arguments so watch out for those.
2910     if (!Subtarget->is64Bit() &&
2911         !isa<GlobalAddressSDNode>(Callee) &&
2912         !isa<ExternalSymbolSDNode>(Callee)) {
2913       unsigned NumInRegs = 0;
2914       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2915         CCValAssign &VA = ArgLocs[i];
2916         if (!VA.isRegLoc())
2917           continue;
2918         unsigned Reg = VA.getLocReg();
2919         switch (Reg) {
2920         default: break;
2921         case X86::EAX: case X86::EDX: case X86::ECX:
2922           if (++NumInRegs == 3)
2923             return false;
2924           break;
2925         }
2926       }
2927     }
2928   }
2929
2930   return true;
2931 }
2932
2933 FastISel *
2934 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2935                                   const TargetLibraryInfo *libInfo) const {
2936   return X86::createFastISel(funcInfo, libInfo);
2937 }
2938
2939
2940 //===----------------------------------------------------------------------===//
2941 //                           Other Lowering Hooks
2942 //===----------------------------------------------------------------------===//
2943
2944 static bool MayFoldLoad(SDValue Op) {
2945   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2946 }
2947
2948 static bool MayFoldIntoStore(SDValue Op) {
2949   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2950 }
2951
2952 static bool isTargetShuffle(unsigned Opcode) {
2953   switch(Opcode) {
2954   default: return false;
2955   case X86ISD::PSHUFD:
2956   case X86ISD::PSHUFHW:
2957   case X86ISD::PSHUFLW:
2958   case X86ISD::SHUFP:
2959   case X86ISD::PALIGN:
2960   case X86ISD::MOVLHPS:
2961   case X86ISD::MOVLHPD:
2962   case X86ISD::MOVHLPS:
2963   case X86ISD::MOVLPS:
2964   case X86ISD::MOVLPD:
2965   case X86ISD::MOVSHDUP:
2966   case X86ISD::MOVSLDUP:
2967   case X86ISD::MOVDDUP:
2968   case X86ISD::MOVSS:
2969   case X86ISD::MOVSD:
2970   case X86ISD::UNPCKL:
2971   case X86ISD::UNPCKH:
2972   case X86ISD::VPERMILP:
2973   case X86ISD::VPERM2X128:
2974   case X86ISD::VPERMI:
2975     return true;
2976   }
2977 }
2978
2979 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2980                                     SDValue V1, SelectionDAG &DAG) {
2981   switch(Opc) {
2982   default: llvm_unreachable("Unknown x86 shuffle node");
2983   case X86ISD::MOVSHDUP:
2984   case X86ISD::MOVSLDUP:
2985   case X86ISD::MOVDDUP:
2986     return DAG.getNode(Opc, dl, VT, V1);
2987   }
2988 }
2989
2990 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2991                                     SDValue V1, unsigned TargetMask,
2992                                     SelectionDAG &DAG) {
2993   switch(Opc) {
2994   default: llvm_unreachable("Unknown x86 shuffle node");
2995   case X86ISD::PSHUFD:
2996   case X86ISD::PSHUFHW:
2997   case X86ISD::PSHUFLW:
2998   case X86ISD::VPERMILP:
2999   case X86ISD::VPERMI:
3000     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3001   }
3002 }
3003
3004 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3005                                     SDValue V1, SDValue V2, unsigned TargetMask,
3006                                     SelectionDAG &DAG) {
3007   switch(Opc) {
3008   default: llvm_unreachable("Unknown x86 shuffle node");
3009   case X86ISD::PALIGN:
3010   case X86ISD::SHUFP:
3011   case X86ISD::VPERM2X128:
3012     return DAG.getNode(Opc, dl, VT, V1, V2,
3013                        DAG.getConstant(TargetMask, MVT::i8));
3014   }
3015 }
3016
3017 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3018                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3019   switch(Opc) {
3020   default: llvm_unreachable("Unknown x86 shuffle node");
3021   case X86ISD::MOVLHPS:
3022   case X86ISD::MOVLHPD:
3023   case X86ISD::MOVHLPS:
3024   case X86ISD::MOVLPS:
3025   case X86ISD::MOVLPD:
3026   case X86ISD::MOVSS:
3027   case X86ISD::MOVSD:
3028   case X86ISD::UNPCKL:
3029   case X86ISD::UNPCKH:
3030     return DAG.getNode(Opc, dl, VT, V1, V2);
3031   }
3032 }
3033
3034 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3035   MachineFunction &MF = DAG.getMachineFunction();
3036   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3037   int ReturnAddrIndex = FuncInfo->getRAIndex();
3038
3039   if (ReturnAddrIndex == 0) {
3040     // Set up a frame object for the return address.
3041     uint64_t SlotSize = TD->getPointerSize(0);
3042     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3043                                                            false);
3044     FuncInfo->setRAIndex(ReturnAddrIndex);
3045   }
3046
3047   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3048 }
3049
3050
3051 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3052                                        bool hasSymbolicDisplacement) {
3053   // Offset should fit into 32 bit immediate field.
3054   if (!isInt<32>(Offset))
3055     return false;
3056
3057   // If we don't have a symbolic displacement - we don't have any extra
3058   // restrictions.
3059   if (!hasSymbolicDisplacement)
3060     return true;
3061
3062   // FIXME: Some tweaks might be needed for medium code model.
3063   if (M != CodeModel::Small && M != CodeModel::Kernel)
3064     return false;
3065
3066   // For small code model we assume that latest object is 16MB before end of 31
3067   // bits boundary. We may also accept pretty large negative constants knowing
3068   // that all objects are in the positive half of address space.
3069   if (M == CodeModel::Small && Offset < 16*1024*1024)
3070     return true;
3071
3072   // For kernel code model we know that all object resist in the negative half
3073   // of 32bits address space. We may not accept negative offsets, since they may
3074   // be just off and we may accept pretty large positive ones.
3075   if (M == CodeModel::Kernel && Offset > 0)
3076     return true;
3077
3078   return false;
3079 }
3080
3081 /// isCalleePop - Determines whether the callee is required to pop its
3082 /// own arguments. Callee pop is necessary to support tail calls.
3083 bool X86::isCalleePop(CallingConv::ID CallingConv,
3084                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3085   if (IsVarArg)
3086     return false;
3087
3088   switch (CallingConv) {
3089   default:
3090     return false;
3091   case CallingConv::X86_StdCall:
3092     return !is64Bit;
3093   case CallingConv::X86_FastCall:
3094     return !is64Bit;
3095   case CallingConv::X86_ThisCall:
3096     return !is64Bit;
3097   case CallingConv::Fast:
3098     return TailCallOpt;
3099   case CallingConv::GHC:
3100     return TailCallOpt;
3101   }
3102 }
3103
3104 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3105 /// specific condition code, returning the condition code and the LHS/RHS of the
3106 /// comparison to make.
3107 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3108                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3109   if (!isFP) {
3110     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3111       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3112         // X > -1   -> X == 0, jump !sign.
3113         RHS = DAG.getConstant(0, RHS.getValueType());
3114         return X86::COND_NS;
3115       }
3116       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3117         // X < 0   -> X == 0, jump on sign.
3118         return X86::COND_S;
3119       }
3120       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3121         // X < 1   -> X <= 0
3122         RHS = DAG.getConstant(0, RHS.getValueType());
3123         return X86::COND_LE;
3124       }
3125     }
3126
3127     switch (SetCCOpcode) {
3128     default: llvm_unreachable("Invalid integer condition!");
3129     case ISD::SETEQ:  return X86::COND_E;
3130     case ISD::SETGT:  return X86::COND_G;
3131     case ISD::SETGE:  return X86::COND_GE;
3132     case ISD::SETLT:  return X86::COND_L;
3133     case ISD::SETLE:  return X86::COND_LE;
3134     case ISD::SETNE:  return X86::COND_NE;
3135     case ISD::SETULT: return X86::COND_B;
3136     case ISD::SETUGT: return X86::COND_A;
3137     case ISD::SETULE: return X86::COND_BE;
3138     case ISD::SETUGE: return X86::COND_AE;
3139     }
3140   }
3141
3142   // First determine if it is required or is profitable to flip the operands.
3143
3144   // If LHS is a foldable load, but RHS is not, flip the condition.
3145   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3146       !ISD::isNON_EXTLoad(RHS.getNode())) {
3147     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3148     std::swap(LHS, RHS);
3149   }
3150
3151   switch (SetCCOpcode) {
3152   default: break;
3153   case ISD::SETOLT:
3154   case ISD::SETOLE:
3155   case ISD::SETUGT:
3156   case ISD::SETUGE:
3157     std::swap(LHS, RHS);
3158     break;
3159   }
3160
3161   // On a floating point condition, the flags are set as follows:
3162   // ZF  PF  CF   op
3163   //  0 | 0 | 0 | X > Y
3164   //  0 | 0 | 1 | X < Y
3165   //  1 | 0 | 0 | X == Y
3166   //  1 | 1 | 1 | unordered
3167   switch (SetCCOpcode) {
3168   default: llvm_unreachable("Condcode should be pre-legalized away");
3169   case ISD::SETUEQ:
3170   case ISD::SETEQ:   return X86::COND_E;
3171   case ISD::SETOLT:              // flipped
3172   case ISD::SETOGT:
3173   case ISD::SETGT:   return X86::COND_A;
3174   case ISD::SETOLE:              // flipped
3175   case ISD::SETOGE:
3176   case ISD::SETGE:   return X86::COND_AE;
3177   case ISD::SETUGT:              // flipped
3178   case ISD::SETULT:
3179   case ISD::SETLT:   return X86::COND_B;
3180   case ISD::SETUGE:              // flipped
3181   case ISD::SETULE:
3182   case ISD::SETLE:   return X86::COND_BE;
3183   case ISD::SETONE:
3184   case ISD::SETNE:   return X86::COND_NE;
3185   case ISD::SETUO:   return X86::COND_P;
3186   case ISD::SETO:    return X86::COND_NP;
3187   case ISD::SETOEQ:
3188   case ISD::SETUNE:  return X86::COND_INVALID;
3189   }
3190 }
3191
3192 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3193 /// code. Current x86 isa includes the following FP cmov instructions:
3194 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3195 static bool hasFPCMov(unsigned X86CC) {
3196   switch (X86CC) {
3197   default:
3198     return false;
3199   case X86::COND_B:
3200   case X86::COND_BE:
3201   case X86::COND_E:
3202   case X86::COND_P:
3203   case X86::COND_A:
3204   case X86::COND_AE:
3205   case X86::COND_NE:
3206   case X86::COND_NP:
3207     return true;
3208   }
3209 }
3210
3211 /// isFPImmLegal - Returns true if the target can instruction select the
3212 /// specified FP immediate natively. If false, the legalizer will
3213 /// materialize the FP immediate as a load from a constant pool.
3214 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3215   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3216     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3217       return true;
3218   }
3219   return false;
3220 }
3221
3222 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3223 /// the specified range (L, H].
3224 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3225   return (Val < 0) || (Val >= Low && Val < Hi);
3226 }
3227
3228 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3229 /// specified value.
3230 static bool isUndefOrEqual(int Val, int CmpVal) {
3231   if (Val < 0 || Val == CmpVal)
3232     return true;
3233   return false;
3234 }
3235
3236 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3237 /// from position Pos and ending in Pos+Size, falls within the specified
3238 /// sequential range (L, L+Pos]. or is undef.
3239 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3240                                        unsigned Pos, unsigned Size, int Low) {
3241   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3242     if (!isUndefOrEqual(Mask[i], Low))
3243       return false;
3244   return true;
3245 }
3246
3247 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3248 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3249 /// the second operand.
3250 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3251   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3252     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3253   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3254     return (Mask[0] < 2 && Mask[1] < 2);
3255   return false;
3256 }
3257
3258 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3259 /// is suitable for input to PSHUFHW.
3260 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3261   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3262     return false;
3263
3264   // Lower quadword copied in order or undef.
3265   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3266     return false;
3267
3268   // Upper quadword shuffled.
3269   for (unsigned i = 4; i != 8; ++i)
3270     if (!isUndefOrInRange(Mask[i], 4, 8))
3271       return false;
3272
3273   if (VT == MVT::v16i16) {
3274     // Lower quadword copied in order or undef.
3275     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3276       return false;
3277
3278     // Upper quadword shuffled.
3279     for (unsigned i = 12; i != 16; ++i)
3280       if (!isUndefOrInRange(Mask[i], 12, 16))
3281         return false;
3282   }
3283
3284   return true;
3285 }
3286
3287 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3288 /// is suitable for input to PSHUFLW.
3289 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3290   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3291     return false;
3292
3293   // Upper quadword copied in order.
3294   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3295     return false;
3296
3297   // Lower quadword shuffled.
3298   for (unsigned i = 0; i != 4; ++i)
3299     if (!isUndefOrInRange(Mask[i], 0, 4))
3300       return false;
3301
3302   if (VT == MVT::v16i16) {
3303     // Upper quadword copied in order.
3304     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3305       return false;
3306
3307     // Lower quadword shuffled.
3308     for (unsigned i = 8; i != 12; ++i)
3309       if (!isUndefOrInRange(Mask[i], 8, 12))
3310         return false;
3311   }
3312
3313   return true;
3314 }
3315
3316 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PALIGNR.
3318 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3319                           const X86Subtarget *Subtarget) {
3320   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3321       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3322     return false;
3323
3324   unsigned NumElts = VT.getVectorNumElements();
3325   unsigned NumLanes = VT.getSizeInBits()/128;
3326   unsigned NumLaneElts = NumElts/NumLanes;
3327
3328   // Do not handle 64-bit element shuffles with palignr.
3329   if (NumLaneElts == 2)
3330     return false;
3331
3332   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3333     unsigned i;
3334     for (i = 0; i != NumLaneElts; ++i) {
3335       if (Mask[i+l] >= 0)
3336         break;
3337     }
3338
3339     // Lane is all undef, go to next lane
3340     if (i == NumLaneElts)
3341       continue;
3342
3343     int Start = Mask[i+l];
3344
3345     // Make sure its in this lane in one of the sources
3346     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3347         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3348       return false;
3349
3350     // If not lane 0, then we must match lane 0
3351     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3352       return false;
3353
3354     // Correct second source to be contiguous with first source
3355     if (Start >= (int)NumElts)
3356       Start -= NumElts - NumLaneElts;
3357
3358     // Make sure we're shifting in the right direction.
3359     if (Start <= (int)(i+l))
3360       return false;
3361
3362     Start -= i;
3363
3364     // Check the rest of the elements to see if they are consecutive.
3365     for (++i; i != NumLaneElts; ++i) {
3366       int Idx = Mask[i+l];
3367
3368       // Make sure its in this lane
3369       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3370           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3371         return false;
3372
3373       // If not lane 0, then we must match lane 0
3374       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3375         return false;
3376
3377       if (Idx >= (int)NumElts)
3378         Idx -= NumElts - NumLaneElts;
3379
3380       if (!isUndefOrEqual(Idx, Start+i))
3381         return false;
3382
3383     }
3384   }
3385
3386   return true;
3387 }
3388
3389 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3390 /// the two vector operands have swapped position.
3391 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3392                                      unsigned NumElems) {
3393   for (unsigned i = 0; i != NumElems; ++i) {
3394     int idx = Mask[i];
3395     if (idx < 0)
3396       continue;
3397     else if (idx < (int)NumElems)
3398       Mask[i] = idx + NumElems;
3399     else
3400       Mask[i] = idx - NumElems;
3401   }
3402 }
3403
3404 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3406 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3407 /// reverse of what x86 shuffles want.
3408 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3409                         bool Commuted = false) {
3410   if (!HasAVX && VT.getSizeInBits() == 256)
3411     return false;
3412
3413   unsigned NumElems = VT.getVectorNumElements();
3414   unsigned NumLanes = VT.getSizeInBits()/128;
3415   unsigned NumLaneElems = NumElems/NumLanes;
3416
3417   if (NumLaneElems != 2 && NumLaneElems != 4)
3418     return false;
3419
3420   // VSHUFPSY divides the resulting vector into 4 chunks.
3421   // The sources are also splitted into 4 chunks, and each destination
3422   // chunk must come from a different source chunk.
3423   //
3424   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3425   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3426   //
3427   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3428   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3429   //
3430   // VSHUFPDY divides the resulting vector into 4 chunks.
3431   // The sources are also splitted into 4 chunks, and each destination
3432   // chunk must come from a different source chunk.
3433   //
3434   //  SRC1 =>      X3       X2       X1       X0
3435   //  SRC2 =>      Y3       Y2       Y1       Y0
3436   //
3437   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3438   //
3439   unsigned HalfLaneElems = NumLaneElems/2;
3440   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3441     for (unsigned i = 0; i != NumLaneElems; ++i) {
3442       int Idx = Mask[i+l];
3443       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3444       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3445         return false;
3446       // For VSHUFPSY, the mask of the second half must be the same as the
3447       // first but with the appropriate offsets. This works in the same way as
3448       // VPERMILPS works with masks.
3449       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3450         continue;
3451       if (!isUndefOrEqual(Idx, Mask[i]+l))
3452         return false;
3453     }
3454   }
3455
3456   return true;
3457 }
3458
3459 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3460 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3461 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3462   if (!VT.is128BitVector())
3463     return false;
3464
3465   unsigned NumElems = VT.getVectorNumElements();
3466
3467   if (NumElems != 4)
3468     return false;
3469
3470   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3471   return isUndefOrEqual(Mask[0], 6) &&
3472          isUndefOrEqual(Mask[1], 7) &&
3473          isUndefOrEqual(Mask[2], 2) &&
3474          isUndefOrEqual(Mask[3], 3);
3475 }
3476
3477 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3478 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3479 /// <2, 3, 2, 3>
3480 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3481   if (!VT.is128BitVector())
3482     return false;
3483
3484   unsigned NumElems = VT.getVectorNumElements();
3485
3486   if (NumElems != 4)
3487     return false;
3488
3489   return isUndefOrEqual(Mask[0], 2) &&
3490          isUndefOrEqual(Mask[1], 3) &&
3491          isUndefOrEqual(Mask[2], 2) &&
3492          isUndefOrEqual(Mask[3], 3);
3493 }
3494
3495 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3497 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3498   if (!VT.is128BitVector())
3499     return false;
3500
3501   unsigned NumElems = VT.getVectorNumElements();
3502
3503   if (NumElems != 2 && NumElems != 4)
3504     return false;
3505
3506   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3507     if (!isUndefOrEqual(Mask[i], i + NumElems))
3508       return false;
3509
3510   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3511     if (!isUndefOrEqual(Mask[i], i))
3512       return false;
3513
3514   return true;
3515 }
3516
3517 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3518 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3519 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3520   if (!VT.is128BitVector())
3521     return false;
3522
3523   unsigned NumElems = VT.getVectorNumElements();
3524
3525   if (NumElems != 2 && NumElems != 4)
3526     return false;
3527
3528   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3529     if (!isUndefOrEqual(Mask[i], i))
3530       return false;
3531
3532   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3533     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3534       return false;
3535
3536   return true;
3537 }
3538
3539 //
3540 // Some special combinations that can be optimized.
3541 //
3542 static
3543 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3544                                SelectionDAG &DAG) {
3545   EVT VT = SVOp->getValueType(0);
3546   DebugLoc dl = SVOp->getDebugLoc();
3547
3548   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3549     return SDValue();
3550
3551   ArrayRef<int> Mask = SVOp->getMask();
3552
3553   // These are the special masks that may be optimized.
3554   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3555   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3556   bool MatchEvenMask = true;
3557   bool MatchOddMask  = true;
3558   for (int i=0; i<8; ++i) {
3559     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3560       MatchEvenMask = false;
3561     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3562       MatchOddMask = false;
3563   }
3564
3565   if (!MatchEvenMask && !MatchOddMask)
3566     return SDValue();
3567
3568   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3569
3570   SDValue Op0 = SVOp->getOperand(0);
3571   SDValue Op1 = SVOp->getOperand(1);
3572
3573   if (MatchEvenMask) {
3574     // Shift the second operand right to 32 bits.
3575     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3576     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3577   } else {
3578     // Shift the first operand left to 32 bits.
3579     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3580     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3581   }
3582   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3583   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3584 }
3585
3586 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3587 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3588 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3589                          bool HasAVX2, bool V2IsSplat = false) {
3590   unsigned NumElts = VT.getVectorNumElements();
3591
3592   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3593          "Unsupported vector type for unpckh");
3594
3595   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3596       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3597     return false;
3598
3599   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3600   // independently on 128-bit lanes.
3601   unsigned NumLanes = VT.getSizeInBits()/128;
3602   unsigned NumLaneElts = NumElts/NumLanes;
3603
3604   for (unsigned l = 0; l != NumLanes; ++l) {
3605     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3606          i != (l+1)*NumLaneElts;
3607          i += 2, ++j) {
3608       int BitI  = Mask[i];
3609       int BitI1 = Mask[i+1];
3610       if (!isUndefOrEqual(BitI, j))
3611         return false;
3612       if (V2IsSplat) {
3613         if (!isUndefOrEqual(BitI1, NumElts))
3614           return false;
3615       } else {
3616         if (!isUndefOrEqual(BitI1, j + NumElts))
3617           return false;
3618       }
3619     }
3620   }
3621
3622   return true;
3623 }
3624
3625 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3626 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3627 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3628                          bool HasAVX2, bool V2IsSplat = false) {
3629   unsigned NumElts = VT.getVectorNumElements();
3630
3631   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3632          "Unsupported vector type for unpckh");
3633
3634   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3635       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3636     return false;
3637
3638   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3639   // independently on 128-bit lanes.
3640   unsigned NumLanes = VT.getSizeInBits()/128;
3641   unsigned NumLaneElts = NumElts/NumLanes;
3642
3643   for (unsigned l = 0; l != NumLanes; ++l) {
3644     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3645          i != (l+1)*NumLaneElts; i += 2, ++j) {
3646       int BitI  = Mask[i];
3647       int BitI1 = Mask[i+1];
3648       if (!isUndefOrEqual(BitI, j))
3649         return false;
3650       if (V2IsSplat) {
3651         if (isUndefOrEqual(BitI1, NumElts))
3652           return false;
3653       } else {
3654         if (!isUndefOrEqual(BitI1, j+NumElts))
3655           return false;
3656       }
3657     }
3658   }
3659   return true;
3660 }
3661
3662 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3663 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3664 /// <0, 0, 1, 1>
3665 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3666                                   bool HasAVX2) {
3667   unsigned NumElts = VT.getVectorNumElements();
3668
3669   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3670          "Unsupported vector type for unpckh");
3671
3672   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3673       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3674     return false;
3675
3676   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3677   // FIXME: Need a better way to get rid of this, there's no latency difference
3678   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3679   // the former later. We should also remove the "_undef" special mask.
3680   if (NumElts == 4 && VT.getSizeInBits() == 256)
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;
3690          i != (l+1)*NumLaneElts;
3691          i += 2, ++j) {
3692       int BitI  = Mask[i];
3693       int BitI1 = Mask[i+1];
3694
3695       if (!isUndefOrEqual(BitI, j))
3696         return false;
3697       if (!isUndefOrEqual(BitI1, j))
3698         return false;
3699     }
3700   }
3701
3702   return true;
3703 }
3704
3705 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3706 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3707 /// <2, 2, 3, 3>
3708 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3709   unsigned NumElts = VT.getVectorNumElements();
3710
3711   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3712          "Unsupported vector type for unpckh");
3713
3714   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3715       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3716     return false;
3717
3718   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3719   // independently on 128-bit lanes.
3720   unsigned NumLanes = VT.getSizeInBits()/128;
3721   unsigned NumLaneElts = NumElts/NumLanes;
3722
3723   for (unsigned l = 0; l != NumLanes; ++l) {
3724     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3725          i != (l+1)*NumLaneElts; i += 2, ++j) {
3726       int BitI  = Mask[i];
3727       int BitI1 = Mask[i+1];
3728       if (!isUndefOrEqual(BitI, j))
3729         return false;
3730       if (!isUndefOrEqual(BitI1, j))
3731         return false;
3732     }
3733   }
3734   return true;
3735 }
3736
3737 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3738 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3739 /// MOVSD, and MOVD, i.e. setting the lowest element.
3740 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3741   if (VT.getVectorElementType().getSizeInBits() < 32)
3742     return false;
3743   if (!VT.is128BitVector())
3744     return false;
3745
3746   unsigned NumElts = VT.getVectorNumElements();
3747
3748   if (!isUndefOrEqual(Mask[0], NumElts))
3749     return false;
3750
3751   for (unsigned i = 1; i != NumElts; ++i)
3752     if (!isUndefOrEqual(Mask[i], i))
3753       return false;
3754
3755   return true;
3756 }
3757
3758 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3759 /// as permutations between 128-bit chunks or halves. As an example: this
3760 /// shuffle bellow:
3761 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3762 /// The first half comes from the second half of V1 and the second half from the
3763 /// the second half of V2.
3764 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3765   if (!HasAVX || !VT.is256BitVector())
3766     return false;
3767
3768   // The shuffle result is divided into half A and half B. In total the two
3769   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3770   // B must come from C, D, E or F.
3771   unsigned HalfSize = VT.getVectorNumElements()/2;
3772   bool MatchA = false, MatchB = false;
3773
3774   // Check if A comes from one of C, D, E, F.
3775   for (unsigned Half = 0; Half != 4; ++Half) {
3776     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3777       MatchA = true;
3778       break;
3779     }
3780   }
3781
3782   // Check if B comes from one of C, D, E, F.
3783   for (unsigned Half = 0; Half != 4; ++Half) {
3784     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3785       MatchB = true;
3786       break;
3787     }
3788   }
3789
3790   return MatchA && MatchB;
3791 }
3792
3793 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3794 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3795 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3796   EVT VT = SVOp->getValueType(0);
3797
3798   unsigned HalfSize = VT.getVectorNumElements()/2;
3799
3800   unsigned FstHalf = 0, SndHalf = 0;
3801   for (unsigned i = 0; i < HalfSize; ++i) {
3802     if (SVOp->getMaskElt(i) > 0) {
3803       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3804       break;
3805     }
3806   }
3807   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3808     if (SVOp->getMaskElt(i) > 0) {
3809       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3810       break;
3811     }
3812   }
3813
3814   return (FstHalf | (SndHalf << 4));
3815 }
3816
3817 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3818 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3819 /// Note that VPERMIL mask matching is different depending whether theunderlying
3820 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3821 /// to the same elements of the low, but to the higher half of the source.
3822 /// In VPERMILPD the two lanes could be shuffled independently of each other
3823 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3824 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3825   if (!HasAVX)
3826     return false;
3827
3828   unsigned NumElts = VT.getVectorNumElements();
3829   // Only match 256-bit with 32/64-bit types
3830   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3831     return false;
3832
3833   unsigned NumLanes = VT.getSizeInBits()/128;
3834   unsigned LaneSize = NumElts/NumLanes;
3835   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3836     for (unsigned i = 0; i != LaneSize; ++i) {
3837       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3838         return false;
3839       if (NumElts != 8 || l == 0)
3840         continue;
3841       // VPERMILPS handling
3842       if (Mask[i] < 0)
3843         continue;
3844       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3845         return false;
3846     }
3847   }
3848
3849   return true;
3850 }
3851
3852 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3853 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3854 /// element of vector 2 and the other elements to come from vector 1 in order.
3855 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3856                                bool V2IsSplat = false, bool V2IsUndef = false) {
3857   if (!VT.is128BitVector())
3858     return false;
3859
3860   unsigned NumOps = VT.getVectorNumElements();
3861   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3862     return false;
3863
3864   if (!isUndefOrEqual(Mask[0], 0))
3865     return false;
3866
3867   for (unsigned i = 1; i != NumOps; ++i)
3868     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3869           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3870           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3871       return false;
3872
3873   return true;
3874 }
3875
3876 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3877 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3878 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3879 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3880                            const X86Subtarget *Subtarget) {
3881   if (!Subtarget->hasSSE3())
3882     return false;
3883
3884   unsigned NumElems = VT.getVectorNumElements();
3885
3886   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3887       (VT.getSizeInBits() == 256 && NumElems != 8))
3888     return false;
3889
3890   // "i+1" is the value the indexed mask element must have
3891   for (unsigned i = 0; i != NumElems; i += 2)
3892     if (!isUndefOrEqual(Mask[i], i+1) ||
3893         !isUndefOrEqual(Mask[i+1], i+1))
3894       return false;
3895
3896   return true;
3897 }
3898
3899 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3900 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3901 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3902 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3903                            const X86Subtarget *Subtarget) {
3904   if (!Subtarget->hasSSE3())
3905     return false;
3906
3907   unsigned NumElems = VT.getVectorNumElements();
3908
3909   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3910       (VT.getSizeInBits() == 256 && NumElems != 8))
3911     return false;
3912
3913   // "i" is the value the indexed mask element must have
3914   for (unsigned i = 0; i != NumElems; i += 2)
3915     if (!isUndefOrEqual(Mask[i], i) ||
3916         !isUndefOrEqual(Mask[i+1], i))
3917       return false;
3918
3919   return true;
3920 }
3921
3922 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3923 /// specifies a shuffle of elements that is suitable for input to 256-bit
3924 /// version of MOVDDUP.
3925 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3926   if (!HasAVX || !VT.is256BitVector())
3927     return false;
3928
3929   unsigned NumElts = VT.getVectorNumElements();
3930   if (NumElts != 4)
3931     return false;
3932
3933   for (unsigned i = 0; i != NumElts/2; ++i)
3934     if (!isUndefOrEqual(Mask[i], 0))
3935       return false;
3936   for (unsigned i = NumElts/2; i != NumElts; ++i)
3937     if (!isUndefOrEqual(Mask[i], NumElts/2))
3938       return false;
3939   return true;
3940 }
3941
3942 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3943 /// specifies a shuffle of elements that is suitable for input to 128-bit
3944 /// version of MOVDDUP.
3945 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3946   if (!VT.is128BitVector())
3947     return false;
3948
3949   unsigned e = VT.getVectorNumElements() / 2;
3950   for (unsigned i = 0; i != e; ++i)
3951     if (!isUndefOrEqual(Mask[i], i))
3952       return false;
3953   for (unsigned i = 0; i != e; ++i)
3954     if (!isUndefOrEqual(Mask[e+i], i))
3955       return false;
3956   return true;
3957 }
3958
3959 /// isVEXTRACTF128Index - Return true if the specified
3960 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3961 /// suitable for input to VEXTRACTF128.
3962 bool X86::isVEXTRACTF128Index(SDNode *N) {
3963   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3964     return false;
3965
3966   // The index should be aligned on a 128-bit boundary.
3967   uint64_t Index =
3968     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3969
3970   unsigned VL = N->getValueType(0).getVectorNumElements();
3971   unsigned VBits = N->getValueType(0).getSizeInBits();
3972   unsigned ElSize = VBits / VL;
3973   bool Result = (Index * ElSize) % 128 == 0;
3974
3975   return Result;
3976 }
3977
3978 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3979 /// operand specifies a subvector insert that is suitable for input to
3980 /// VINSERTF128.
3981 bool X86::isVINSERTF128Index(SDNode *N) {
3982   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3983     return false;
3984
3985   // The index should be aligned on a 128-bit boundary.
3986   uint64_t Index =
3987     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3988
3989   unsigned VL = N->getValueType(0).getVectorNumElements();
3990   unsigned VBits = N->getValueType(0).getSizeInBits();
3991   unsigned ElSize = VBits / VL;
3992   bool Result = (Index * ElSize) % 128 == 0;
3993
3994   return Result;
3995 }
3996
3997 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3998 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3999 /// Handles 128-bit and 256-bit.
4000 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4001   EVT VT = N->getValueType(0);
4002
4003   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4004          "Unsupported vector type for PSHUF/SHUFP");
4005
4006   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4007   // independently on 128-bit lanes.
4008   unsigned NumElts = VT.getVectorNumElements();
4009   unsigned NumLanes = VT.getSizeInBits()/128;
4010   unsigned NumLaneElts = NumElts/NumLanes;
4011
4012   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4013          "Only supports 2 or 4 elements per lane");
4014
4015   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4016   unsigned Mask = 0;
4017   for (unsigned i = 0; i != NumElts; ++i) {
4018     int Elt = N->getMaskElt(i);
4019     if (Elt < 0) continue;
4020     Elt &= NumLaneElts - 1;
4021     unsigned ShAmt = (i << Shift) % 8;
4022     Mask |= Elt << ShAmt;
4023   }
4024
4025   return Mask;
4026 }
4027
4028 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4029 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4030 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4031   EVT VT = N->getValueType(0);
4032
4033   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4034          "Unsupported vector type for PSHUFHW");
4035
4036   unsigned NumElts = VT.getVectorNumElements();
4037
4038   unsigned Mask = 0;
4039   for (unsigned l = 0; l != NumElts; l += 8) {
4040     // 8 nodes per lane, but we only care about the last 4.
4041     for (unsigned i = 0; i < 4; ++i) {
4042       int Elt = N->getMaskElt(l+i+4);
4043       if (Elt < 0) continue;
4044       Elt &= 0x3; // only 2-bits.
4045       Mask |= Elt << (i * 2);
4046     }
4047   }
4048
4049   return Mask;
4050 }
4051
4052 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4053 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4054 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4055   EVT VT = N->getValueType(0);
4056
4057   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4058          "Unsupported vector type for PSHUFHW");
4059
4060   unsigned NumElts = VT.getVectorNumElements();
4061
4062   unsigned Mask = 0;
4063   for (unsigned l = 0; l != NumElts; l += 8) {
4064     // 8 nodes per lane, but we only care about the first 4.
4065     for (unsigned i = 0; i < 4; ++i) {
4066       int Elt = N->getMaskElt(l+i);
4067       if (Elt < 0) continue;
4068       Elt &= 0x3; // only 2-bits
4069       Mask |= Elt << (i * 2);
4070     }
4071   }
4072
4073   return Mask;
4074 }
4075
4076 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4077 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4078 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4079   EVT VT = SVOp->getValueType(0);
4080   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4081
4082   unsigned NumElts = VT.getVectorNumElements();
4083   unsigned NumLanes = VT.getSizeInBits()/128;
4084   unsigned NumLaneElts = NumElts/NumLanes;
4085
4086   int Val = 0;
4087   unsigned i;
4088   for (i = 0; i != NumElts; ++i) {
4089     Val = SVOp->getMaskElt(i);
4090     if (Val >= 0)
4091       break;
4092   }
4093   if (Val >= (int)NumElts)
4094     Val -= NumElts - NumLaneElts;
4095
4096   assert(Val - i > 0 && "PALIGNR imm should be positive");
4097   return (Val - i) * EltSize;
4098 }
4099
4100 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4101 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4102 /// instructions.
4103 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4104   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4105     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4106
4107   uint64_t Index =
4108     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4109
4110   EVT VecVT = N->getOperand(0).getValueType();
4111   EVT ElVT = VecVT.getVectorElementType();
4112
4113   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4114   return Index / NumElemsPerChunk;
4115 }
4116
4117 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4118 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4119 /// instructions.
4120 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4121   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4122     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4123
4124   uint64_t Index =
4125     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4126
4127   EVT VecVT = N->getValueType(0);
4128   EVT ElVT = VecVT.getVectorElementType();
4129
4130   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4131   return Index / NumElemsPerChunk;
4132 }
4133
4134 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4135 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4136 /// Handles 256-bit.
4137 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4138   EVT VT = N->getValueType(0);
4139
4140   unsigned NumElts = VT.getVectorNumElements();
4141
4142   assert((VT.is256BitVector() && NumElts == 4) &&
4143          "Unsupported vector type for VPERMQ/VPERMPD");
4144
4145   unsigned Mask = 0;
4146   for (unsigned i = 0; i != NumElts; ++i) {
4147     int Elt = N->getMaskElt(i);
4148     if (Elt < 0)
4149       continue;
4150     Mask |= Elt << (i*2);
4151   }
4152
4153   return Mask;
4154 }
4155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4156 /// constant +0.0.
4157 bool X86::isZeroNode(SDValue Elt) {
4158   return ((isa<ConstantSDNode>(Elt) &&
4159            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4160           (isa<ConstantFPSDNode>(Elt) &&
4161            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4162 }
4163
4164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4165 /// their permute mask.
4166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4167                                     SelectionDAG &DAG) {
4168   EVT VT = SVOp->getValueType(0);
4169   unsigned NumElems = VT.getVectorNumElements();
4170   SmallVector<int, 8> MaskVec;
4171
4172   for (unsigned i = 0; i != NumElems; ++i) {
4173     int Idx = SVOp->getMaskElt(i);
4174     if (Idx >= 0) {
4175       if (Idx < (int)NumElems)
4176         Idx += NumElems;
4177       else
4178         Idx -= NumElems;
4179     }
4180     MaskVec.push_back(Idx);
4181   }
4182   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4183                               SVOp->getOperand(0), &MaskVec[0]);
4184 }
4185
4186 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4187 /// match movhlps. The lower half elements should come from upper half of
4188 /// V1 (and in order), and the upper half elements should come from the upper
4189 /// half of V2 (and in order).
4190 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4191   if (!VT.is128BitVector())
4192     return false;
4193   if (VT.getVectorNumElements() != 4)
4194     return false;
4195   for (unsigned i = 0, e = 2; i != e; ++i)
4196     if (!isUndefOrEqual(Mask[i], i+2))
4197       return false;
4198   for (unsigned i = 2; i != 4; ++i)
4199     if (!isUndefOrEqual(Mask[i], i+4))
4200       return false;
4201   return true;
4202 }
4203
4204 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4205 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4206 /// required.
4207 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4208   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4209     return false;
4210   N = N->getOperand(0).getNode();
4211   if (!ISD::isNON_EXTLoad(N))
4212     return false;
4213   if (LD)
4214     *LD = cast<LoadSDNode>(N);
4215   return true;
4216 }
4217
4218 // Test whether the given value is a vector value which will be legalized
4219 // into a load.
4220 static bool WillBeConstantPoolLoad(SDNode *N) {
4221   if (N->getOpcode() != ISD::BUILD_VECTOR)
4222     return false;
4223
4224   // Check for any non-constant elements.
4225   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4226     switch (N->getOperand(i).getNode()->getOpcode()) {
4227     case ISD::UNDEF:
4228     case ISD::ConstantFP:
4229     case ISD::Constant:
4230       break;
4231     default:
4232       return false;
4233     }
4234
4235   // Vectors of all-zeros and all-ones are materialized with special
4236   // instructions rather than being loaded.
4237   return !ISD::isBuildVectorAllZeros(N) &&
4238          !ISD::isBuildVectorAllOnes(N);
4239 }
4240
4241 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4242 /// match movlp{s|d}. The lower half elements should come from lower half of
4243 /// V1 (and in order), and the upper half elements should come from the upper
4244 /// half of V2 (and in order). And since V1 will become the source of the
4245 /// MOVLP, it must be either a vector load or a scalar load to vector.
4246 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4247                                ArrayRef<int> Mask, EVT VT) {
4248   if (!VT.is128BitVector())
4249     return false;
4250
4251   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4252     return false;
4253   // Is V2 is a vector load, don't do this transformation. We will try to use
4254   // load folding shufps op.
4255   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4256     return false;
4257
4258   unsigned NumElems = VT.getVectorNumElements();
4259
4260   if (NumElems != 2 && NumElems != 4)
4261     return false;
4262   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4263     if (!isUndefOrEqual(Mask[i], i))
4264       return false;
4265   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4266     if (!isUndefOrEqual(Mask[i], i+NumElems))
4267       return false;
4268   return true;
4269 }
4270
4271 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4272 /// all the same.
4273 static bool isSplatVector(SDNode *N) {
4274   if (N->getOpcode() != ISD::BUILD_VECTOR)
4275     return false;
4276
4277   SDValue SplatValue = N->getOperand(0);
4278   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4279     if (N->getOperand(i) != SplatValue)
4280       return false;
4281   return true;
4282 }
4283
4284 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4285 /// to an zero vector.
4286 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4287 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4288   SDValue V1 = N->getOperand(0);
4289   SDValue V2 = N->getOperand(1);
4290   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4291   for (unsigned i = 0; i != NumElems; ++i) {
4292     int Idx = N->getMaskElt(i);
4293     if (Idx >= (int)NumElems) {
4294       unsigned Opc = V2.getOpcode();
4295       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4296         continue;
4297       if (Opc != ISD::BUILD_VECTOR ||
4298           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4299         return false;
4300     } else if (Idx >= 0) {
4301       unsigned Opc = V1.getOpcode();
4302       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4303         continue;
4304       if (Opc != ISD::BUILD_VECTOR ||
4305           !X86::isZeroNode(V1.getOperand(Idx)))
4306         return false;
4307     }
4308   }
4309   return true;
4310 }
4311
4312 /// getZeroVector - Returns a vector of specified type with all zero elements.
4313 ///
4314 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4315                              SelectionDAG &DAG, DebugLoc dl) {
4316   assert(VT.isVector() && "Expected a vector type");
4317   unsigned Size = VT.getSizeInBits();
4318
4319   // Always build SSE zero vectors as <4 x i32> bitcasted
4320   // to their dest type. This ensures they get CSE'd.
4321   SDValue Vec;
4322   if (Size == 128) {  // SSE
4323     if (Subtarget->hasSSE2()) {  // SSE2
4324       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4325       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4326     } else { // SSE1
4327       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4328       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4329     }
4330   } else if (Size == 256) { // AVX
4331     if (Subtarget->hasAVX2()) { // AVX2
4332       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4333       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4335     } else {
4336       // 256-bit logic and arithmetic instructions in AVX are all
4337       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4338       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4339       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4340       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4341     }
4342   } else
4343     llvm_unreachable("Unexpected vector type");
4344
4345   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4346 }
4347
4348 /// getOnesVector - Returns a vector of specified type with all bits set.
4349 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4350 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4351 /// Then bitcast to their original type, ensuring they get CSE'd.
4352 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4353                              DebugLoc dl) {
4354   assert(VT.isVector() && "Expected a vector type");
4355   unsigned Size = VT.getSizeInBits();
4356
4357   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4358   SDValue Vec;
4359   if (Size == 256) {
4360     if (HasAVX2) { // AVX2
4361       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4362       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4363     } else { // AVX
4364       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4365       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4366     }
4367   } else if (Size == 128) {
4368     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4369   } else
4370     llvm_unreachable("Unexpected vector type");
4371
4372   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4373 }
4374
4375 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4376 /// that point to V2 points to its first element.
4377 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4378   for (unsigned i = 0; i != NumElems; ++i) {
4379     if (Mask[i] > (int)NumElems) {
4380       Mask[i] = NumElems;
4381     }
4382   }
4383 }
4384
4385 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4386 /// operation of specified width.
4387 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4388                        SDValue V2) {
4389   unsigned NumElems = VT.getVectorNumElements();
4390   SmallVector<int, 8> Mask;
4391   Mask.push_back(NumElems);
4392   for (unsigned i = 1; i != NumElems; ++i)
4393     Mask.push_back(i);
4394   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4395 }
4396
4397 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4398 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4399                           SDValue V2) {
4400   unsigned NumElems = VT.getVectorNumElements();
4401   SmallVector<int, 8> Mask;
4402   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4403     Mask.push_back(i);
4404     Mask.push_back(i + NumElems);
4405   }
4406   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4407 }
4408
4409 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4410 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4411                           SDValue V2) {
4412   unsigned NumElems = VT.getVectorNumElements();
4413   SmallVector<int, 8> Mask;
4414   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4415     Mask.push_back(i + Half);
4416     Mask.push_back(i + NumElems + Half);
4417   }
4418   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4419 }
4420
4421 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4422 // a generic shuffle instruction because the target has no such instructions.
4423 // Generate shuffles which repeat i16 and i8 several times until they can be
4424 // represented by v4f32 and then be manipulated by target suported shuffles.
4425 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4426   EVT VT = V.getValueType();
4427   int NumElems = VT.getVectorNumElements();
4428   DebugLoc dl = V.getDebugLoc();
4429
4430   while (NumElems > 4) {
4431     if (EltNo < NumElems/2) {
4432       V = getUnpackl(DAG, dl, VT, V, V);
4433     } else {
4434       V = getUnpackh(DAG, dl, VT, V, V);
4435       EltNo -= NumElems/2;
4436     }
4437     NumElems >>= 1;
4438   }
4439   return V;
4440 }
4441
4442 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4443 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4444   EVT VT = V.getValueType();
4445   DebugLoc dl = V.getDebugLoc();
4446   unsigned Size = VT.getSizeInBits();
4447
4448   if (Size == 128) {
4449     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4450     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4451     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4452                              &SplatMask[0]);
4453   } else if (Size == 256) {
4454     // To use VPERMILPS to splat scalars, the second half of indicies must
4455     // refer to the higher part, which is a duplication of the lower one,
4456     // because VPERMILPS can only handle in-lane permutations.
4457     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4458                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4459
4460     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4461     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4462                              &SplatMask[0]);
4463   } else
4464     llvm_unreachable("Vector size not supported");
4465
4466   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4467 }
4468
4469 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4470 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4471   EVT SrcVT = SV->getValueType(0);
4472   SDValue V1 = SV->getOperand(0);
4473   DebugLoc dl = SV->getDebugLoc();
4474
4475   int EltNo = SV->getSplatIndex();
4476   int NumElems = SrcVT.getVectorNumElements();
4477   unsigned Size = SrcVT.getSizeInBits();
4478
4479   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4480           "Unknown how to promote splat for type");
4481
4482   // Extract the 128-bit part containing the splat element and update
4483   // the splat element index when it refers to the higher register.
4484   if (Size == 256) {
4485     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4486     if (EltNo >= NumElems/2)
4487       EltNo -= NumElems/2;
4488   }
4489
4490   // All i16 and i8 vector types can't be used directly by a generic shuffle
4491   // instruction because the target has no such instruction. Generate shuffles
4492   // which repeat i16 and i8 several times until they fit in i32, and then can
4493   // be manipulated by target suported shuffles.
4494   EVT EltVT = SrcVT.getVectorElementType();
4495   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4496     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4497
4498   // Recreate the 256-bit vector and place the same 128-bit vector
4499   // into the low and high part. This is necessary because we want
4500   // to use VPERM* to shuffle the vectors
4501   if (Size == 256) {
4502     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4503   }
4504
4505   return getLegalSplat(DAG, V1, EltNo);
4506 }
4507
4508 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4509 /// vector of zero or undef vector.  This produces a shuffle where the low
4510 /// element of V2 is swizzled into the zero/undef vector, landing at element
4511 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4512 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4513                                            bool IsZero,
4514                                            const X86Subtarget *Subtarget,
4515                                            SelectionDAG &DAG) {
4516   EVT VT = V2.getValueType();
4517   SDValue V1 = IsZero
4518     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4519   unsigned NumElems = VT.getVectorNumElements();
4520   SmallVector<int, 16> MaskVec;
4521   for (unsigned i = 0; i != NumElems; ++i)
4522     // If this is the insertion idx, put the low elt of V2 here.
4523     MaskVec.push_back(i == Idx ? NumElems : i);
4524   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4525 }
4526
4527 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4528 /// target specific opcode. Returns true if the Mask could be calculated.
4529 /// Sets IsUnary to true if only uses one source.
4530 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4531                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4532   unsigned NumElems = VT.getVectorNumElements();
4533   SDValue ImmN;
4534
4535   IsUnary = false;
4536   switch(N->getOpcode()) {
4537   case X86ISD::SHUFP:
4538     ImmN = N->getOperand(N->getNumOperands()-1);
4539     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4540     break;
4541   case X86ISD::UNPCKH:
4542     DecodeUNPCKHMask(VT, Mask);
4543     break;
4544   case X86ISD::UNPCKL:
4545     DecodeUNPCKLMask(VT, Mask);
4546     break;
4547   case X86ISD::MOVHLPS:
4548     DecodeMOVHLPSMask(NumElems, Mask);
4549     break;
4550   case X86ISD::MOVLHPS:
4551     DecodeMOVLHPSMask(NumElems, Mask);
4552     break;
4553   case X86ISD::PSHUFD:
4554   case X86ISD::VPERMILP:
4555     ImmN = N->getOperand(N->getNumOperands()-1);
4556     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4557     IsUnary = true;
4558     break;
4559   case X86ISD::PSHUFHW:
4560     ImmN = N->getOperand(N->getNumOperands()-1);
4561     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4562     IsUnary = true;
4563     break;
4564   case X86ISD::PSHUFLW:
4565     ImmN = N->getOperand(N->getNumOperands()-1);
4566     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4567     IsUnary = true;
4568     break;
4569   case X86ISD::VPERMI:
4570     ImmN = N->getOperand(N->getNumOperands()-1);
4571     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4572     IsUnary = true;
4573     break;
4574   case X86ISD::MOVSS:
4575   case X86ISD::MOVSD: {
4576     // The index 0 always comes from the first element of the second source,
4577     // this is why MOVSS and MOVSD are used in the first place. The other
4578     // elements come from the other positions of the first source vector
4579     Mask.push_back(NumElems);
4580     for (unsigned i = 1; i != NumElems; ++i) {
4581       Mask.push_back(i);
4582     }
4583     break;
4584   }
4585   case X86ISD::VPERM2X128:
4586     ImmN = N->getOperand(N->getNumOperands()-1);
4587     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4588     if (Mask.empty()) return false;
4589     break;
4590   case X86ISD::MOVDDUP:
4591   case X86ISD::MOVLHPD:
4592   case X86ISD::MOVLPD:
4593   case X86ISD::MOVLPS:
4594   case X86ISD::MOVSHDUP:
4595   case X86ISD::MOVSLDUP:
4596   case X86ISD::PALIGN:
4597     // Not yet implemented
4598     return false;
4599   default: llvm_unreachable("unknown target shuffle node");
4600   }
4601
4602   return true;
4603 }
4604
4605 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4606 /// element of the result of the vector shuffle.
4607 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4608                                    unsigned Depth) {
4609   if (Depth == 6)
4610     return SDValue();  // Limit search depth.
4611
4612   SDValue V = SDValue(N, 0);
4613   EVT VT = V.getValueType();
4614   unsigned Opcode = V.getOpcode();
4615
4616   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4617   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4618     int Elt = SV->getMaskElt(Index);
4619
4620     if (Elt < 0)
4621       return DAG.getUNDEF(VT.getVectorElementType());
4622
4623     unsigned NumElems = VT.getVectorNumElements();
4624     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4625                                          : SV->getOperand(1);
4626     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4627   }
4628
4629   // Recurse into target specific vector shuffles to find scalars.
4630   if (isTargetShuffle(Opcode)) {
4631     MVT ShufVT = V.getValueType().getSimpleVT();
4632     unsigned NumElems = ShufVT.getVectorNumElements();
4633     SmallVector<int, 16> ShuffleMask;
4634     SDValue ImmN;
4635     bool IsUnary;
4636
4637     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4638       return SDValue();
4639
4640     int Elt = ShuffleMask[Index];
4641     if (Elt < 0)
4642       return DAG.getUNDEF(ShufVT.getVectorElementType());
4643
4644     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4645                                          : N->getOperand(1);
4646     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4647                                Depth+1);
4648   }
4649
4650   // Actual nodes that may contain scalar elements
4651   if (Opcode == ISD::BITCAST) {
4652     V = V.getOperand(0);
4653     EVT SrcVT = V.getValueType();
4654     unsigned NumElems = VT.getVectorNumElements();
4655
4656     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4657       return SDValue();
4658   }
4659
4660   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4661     return (Index == 0) ? V.getOperand(0)
4662                         : DAG.getUNDEF(VT.getVectorElementType());
4663
4664   if (V.getOpcode() == ISD::BUILD_VECTOR)
4665     return V.getOperand(Index);
4666
4667   return SDValue();
4668 }
4669
4670 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4671 /// shuffle operation which come from a consecutively from a zero. The
4672 /// search can start in two different directions, from left or right.
4673 static
4674 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4675                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4676   unsigned i;
4677   for (i = 0; i != NumElems; ++i) {
4678     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4679     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4680     if (!(Elt.getNode() &&
4681          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4682       break;
4683   }
4684
4685   return i;
4686 }
4687
4688 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4689 /// correspond consecutively to elements from one of the vector operands,
4690 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4691 static
4692 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4693                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4694                               unsigned NumElems, unsigned &OpNum) {
4695   bool SeenV1 = false;
4696   bool SeenV2 = false;
4697
4698   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4699     int Idx = SVOp->getMaskElt(i);
4700     // Ignore undef indicies
4701     if (Idx < 0)
4702       continue;
4703
4704     if (Idx < (int)NumElems)
4705       SeenV1 = true;
4706     else
4707       SeenV2 = true;
4708
4709     // Only accept consecutive elements from the same vector
4710     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4711       return false;
4712   }
4713
4714   OpNum = SeenV1 ? 0 : 1;
4715   return true;
4716 }
4717
4718 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4719 /// logical left shift of a vector.
4720 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4721                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4722   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4723   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4724               false /* check zeros from right */, DAG);
4725   unsigned OpSrc;
4726
4727   if (!NumZeros)
4728     return false;
4729
4730   // Considering the elements in the mask that are not consecutive zeros,
4731   // check if they consecutively come from only one of the source vectors.
4732   //
4733   //               V1 = {X, A, B, C}     0
4734   //                         \  \  \    /
4735   //   vector_shuffle V1, V2 <1, 2, 3, X>
4736   //
4737   if (!isShuffleMaskConsecutive(SVOp,
4738             0,                   // Mask Start Index
4739             NumElems-NumZeros,   // Mask End Index(exclusive)
4740             NumZeros,            // Where to start looking in the src vector
4741             NumElems,            // Number of elements in vector
4742             OpSrc))              // Which source operand ?
4743     return false;
4744
4745   isLeft = false;
4746   ShAmt = NumZeros;
4747   ShVal = SVOp->getOperand(OpSrc);
4748   return true;
4749 }
4750
4751 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4752 /// logical left shift of a vector.
4753 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4754                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4755   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4756   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4757               true /* check zeros from left */, DAG);
4758   unsigned OpSrc;
4759
4760   if (!NumZeros)
4761     return false;
4762
4763   // Considering the elements in the mask that are not consecutive zeros,
4764   // check if they consecutively come from only one of the source vectors.
4765   //
4766   //                           0    { A, B, X, X } = V2
4767   //                          / \    /  /
4768   //   vector_shuffle V1, V2 <X, X, 4, 5>
4769   //
4770   if (!isShuffleMaskConsecutive(SVOp,
4771             NumZeros,     // Mask Start Index
4772             NumElems,     // Mask End Index(exclusive)
4773             0,            // Where to start looking in the src vector
4774             NumElems,     // Number of elements in vector
4775             OpSrc))       // Which source operand ?
4776     return false;
4777
4778   isLeft = true;
4779   ShAmt = NumZeros;
4780   ShVal = SVOp->getOperand(OpSrc);
4781   return true;
4782 }
4783
4784 /// isVectorShift - Returns true if the shuffle can be implemented as a
4785 /// logical left or right shift of a vector.
4786 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4787                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4788   // Although the logic below support any bitwidth size, there are no
4789   // shift instructions which handle more than 128-bit vectors.
4790   if (!SVOp->getValueType(0).is128BitVector())
4791     return false;
4792
4793   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4794       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4795     return true;
4796
4797   return false;
4798 }
4799
4800 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4801 ///
4802 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4803                                        unsigned NumNonZero, unsigned NumZero,
4804                                        SelectionDAG &DAG,
4805                                        const X86Subtarget* Subtarget,
4806                                        const TargetLowering &TLI) {
4807   if (NumNonZero > 8)
4808     return SDValue();
4809
4810   DebugLoc dl = Op.getDebugLoc();
4811   SDValue V(0, 0);
4812   bool First = true;
4813   for (unsigned i = 0; i < 16; ++i) {
4814     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4815     if (ThisIsNonZero && First) {
4816       if (NumZero)
4817         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4818       else
4819         V = DAG.getUNDEF(MVT::v8i16);
4820       First = false;
4821     }
4822
4823     if ((i & 1) != 0) {
4824       SDValue ThisElt(0, 0), LastElt(0, 0);
4825       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4826       if (LastIsNonZero) {
4827         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4828                               MVT::i16, Op.getOperand(i-1));
4829       }
4830       if (ThisIsNonZero) {
4831         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4832         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4833                               ThisElt, DAG.getConstant(8, MVT::i8));
4834         if (LastIsNonZero)
4835           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4836       } else
4837         ThisElt = LastElt;
4838
4839       if (ThisElt.getNode())
4840         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4841                         DAG.getIntPtrConstant(i/2));
4842     }
4843   }
4844
4845   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4846 }
4847
4848 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4849 ///
4850 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4851                                      unsigned NumNonZero, unsigned NumZero,
4852                                      SelectionDAG &DAG,
4853                                      const X86Subtarget* Subtarget,
4854                                      const TargetLowering &TLI) {
4855   if (NumNonZero > 4)
4856     return SDValue();
4857
4858   DebugLoc dl = Op.getDebugLoc();
4859   SDValue V(0, 0);
4860   bool First = true;
4861   for (unsigned i = 0; i < 8; ++i) {
4862     bool isNonZero = (NonZeros & (1 << i)) != 0;
4863     if (isNonZero) {
4864       if (First) {
4865         if (NumZero)
4866           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4867         else
4868           V = DAG.getUNDEF(MVT::v8i16);
4869         First = false;
4870       }
4871       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4872                       MVT::v8i16, V, Op.getOperand(i),
4873                       DAG.getIntPtrConstant(i));
4874     }
4875   }
4876
4877   return V;
4878 }
4879
4880 /// getVShift - Return a vector logical shift node.
4881 ///
4882 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4883                          unsigned NumBits, SelectionDAG &DAG,
4884                          const TargetLowering &TLI, DebugLoc dl) {
4885   assert(VT.is128BitVector() && "Unknown type for VShift");
4886   EVT ShVT = MVT::v2i64;
4887   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4888   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4889   return DAG.getNode(ISD::BITCAST, dl, VT,
4890                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4891                              DAG.getConstant(NumBits,
4892                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4893 }
4894
4895 SDValue
4896 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4897                                           SelectionDAG &DAG) const {
4898
4899   // Check if the scalar load can be widened into a vector load. And if
4900   // the address is "base + cst" see if the cst can be "absorbed" into
4901   // the shuffle mask.
4902   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4903     SDValue Ptr = LD->getBasePtr();
4904     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4905       return SDValue();
4906     EVT PVT = LD->getValueType(0);
4907     if (PVT != MVT::i32 && PVT != MVT::f32)
4908       return SDValue();
4909
4910     int FI = -1;
4911     int64_t Offset = 0;
4912     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4913       FI = FINode->getIndex();
4914       Offset = 0;
4915     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4916                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4917       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4918       Offset = Ptr.getConstantOperandVal(1);
4919       Ptr = Ptr.getOperand(0);
4920     } else {
4921       return SDValue();
4922     }
4923
4924     // FIXME: 256-bit vector instructions don't require a strict alignment,
4925     // improve this code to support it better.
4926     unsigned RequiredAlign = VT.getSizeInBits()/8;
4927     SDValue Chain = LD->getChain();
4928     // Make sure the stack object alignment is at least 16 or 32.
4929     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4930     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4931       if (MFI->isFixedObjectIndex(FI)) {
4932         // Can't change the alignment. FIXME: It's possible to compute
4933         // the exact stack offset and reference FI + adjust offset instead.
4934         // If someone *really* cares about this. That's the way to implement it.
4935         return SDValue();
4936       } else {
4937         MFI->setObjectAlignment(FI, RequiredAlign);
4938       }
4939     }
4940
4941     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4942     // Ptr + (Offset & ~15).
4943     if (Offset < 0)
4944       return SDValue();
4945     if ((Offset % RequiredAlign) & 3)
4946       return SDValue();
4947     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4948     if (StartOffset)
4949       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4950                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4951
4952     int EltNo = (Offset - StartOffset) >> 2;
4953     unsigned NumElems = VT.getVectorNumElements();
4954
4955     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4956     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4957                              LD->getPointerInfo().getWithOffset(StartOffset),
4958                              false, false, false, 0);
4959
4960     SmallVector<int, 8> Mask;
4961     for (unsigned i = 0; i != NumElems; ++i)
4962       Mask.push_back(EltNo);
4963
4964     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4965   }
4966
4967   return SDValue();
4968 }
4969
4970 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4971 /// vector of type 'VT', see if the elements can be replaced by a single large
4972 /// load which has the same value as a build_vector whose operands are 'elts'.
4973 ///
4974 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4975 ///
4976 /// FIXME: we'd also like to handle the case where the last elements are zero
4977 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4978 /// There's even a handy isZeroNode for that purpose.
4979 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4980                                         DebugLoc &DL, SelectionDAG &DAG) {
4981   EVT EltVT = VT.getVectorElementType();
4982   unsigned NumElems = Elts.size();
4983
4984   LoadSDNode *LDBase = NULL;
4985   unsigned LastLoadedElt = -1U;
4986
4987   // For each element in the initializer, see if we've found a load or an undef.
4988   // If we don't find an initial load element, or later load elements are
4989   // non-consecutive, bail out.
4990   for (unsigned i = 0; i < NumElems; ++i) {
4991     SDValue Elt = Elts[i];
4992
4993     if (!Elt.getNode() ||
4994         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4995       return SDValue();
4996     if (!LDBase) {
4997       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4998         return SDValue();
4999       LDBase = cast<LoadSDNode>(Elt.getNode());
5000       LastLoadedElt = i;
5001       continue;
5002     }
5003     if (Elt.getOpcode() == ISD::UNDEF)
5004       continue;
5005
5006     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5007     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5008       return SDValue();
5009     LastLoadedElt = i;
5010   }
5011
5012   // If we have found an entire vector of loads and undefs, then return a large
5013   // load of the entire vector width starting at the base pointer.  If we found
5014   // consecutive loads for the low half, generate a vzext_load node.
5015   if (LastLoadedElt == NumElems - 1) {
5016     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5017       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5018                          LDBase->getPointerInfo(),
5019                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5020                          LDBase->isInvariant(), 0);
5021     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5022                        LDBase->getPointerInfo(),
5023                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5024                        LDBase->isInvariant(), LDBase->getAlignment());
5025   }
5026   if (NumElems == 4 && LastLoadedElt == 1 &&
5027       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5028     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5029     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5030     SDValue ResNode =
5031         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5032                                 LDBase->getPointerInfo(),
5033                                 LDBase->getAlignment(),
5034                                 false/*isVolatile*/, true/*ReadMem*/,
5035                                 false/*WriteMem*/);
5036
5037     // Make sure the newly-created LOAD is in the same position as LDBase in
5038     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5039     // update uses of LDBase's output chain to use the TokenFactor.
5040     if (LDBase->hasAnyUseOfValue(1)) {
5041       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5042                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5043       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5044       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5045                              SDValue(ResNode.getNode(), 1));
5046     }
5047
5048     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5049   }
5050   return SDValue();
5051 }
5052
5053 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5054 /// to generate a splat value for the following cases:
5055 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5056 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5057 /// a scalar load, or a constant.
5058 /// The VBROADCAST node is returned when a pattern is found,
5059 /// or SDValue() otherwise.
5060 SDValue
5061 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5062   if (!Subtarget->hasAVX())
5063     return SDValue();
5064
5065   EVT VT = Op.getValueType();
5066   DebugLoc dl = Op.getDebugLoc();
5067
5068   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5069          "Unsupported vector type for broadcast.");
5070
5071   SDValue Ld;
5072   bool ConstSplatVal;
5073
5074   switch (Op.getOpcode()) {
5075     default:
5076       // Unknown pattern found.
5077       return SDValue();
5078
5079     case ISD::BUILD_VECTOR: {
5080       // The BUILD_VECTOR node must be a splat.
5081       if (!isSplatVector(Op.getNode()))
5082         return SDValue();
5083
5084       Ld = Op.getOperand(0);
5085       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5086                      Ld.getOpcode() == ISD::ConstantFP);
5087
5088       // The suspected load node has several users. Make sure that all
5089       // of its users are from the BUILD_VECTOR node.
5090       // Constants may have multiple users.
5091       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5092         return SDValue();
5093       break;
5094     }
5095
5096     case ISD::VECTOR_SHUFFLE: {
5097       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5098
5099       // Shuffles must have a splat mask where the first element is
5100       // broadcasted.
5101       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5102         return SDValue();
5103
5104       SDValue Sc = Op.getOperand(0);
5105       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5106           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5107
5108         if (!Subtarget->hasAVX2())
5109           return SDValue();
5110
5111         // Use the register form of the broadcast instruction available on AVX2.
5112         if (VT.is256BitVector())
5113           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5114         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5115       }
5116
5117       Ld = Sc.getOperand(0);
5118       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5119                        Ld.getOpcode() == ISD::ConstantFP);
5120
5121       // The scalar_to_vector node and the suspected
5122       // load node must have exactly one user.
5123       // Constants may have multiple users.
5124       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5125         return SDValue();
5126       break;
5127     }
5128   }
5129
5130   bool Is256 = VT.is256BitVector();
5131
5132   // Handle the broadcasting a single constant scalar from the constant pool
5133   // into a vector. On Sandybridge it is still better to load a constant vector
5134   // from the constant pool and not to broadcast it from a scalar.
5135   if (ConstSplatVal && Subtarget->hasAVX2()) {
5136     EVT CVT = Ld.getValueType();
5137     assert(!CVT.isVector() && "Must not broadcast a vector type");
5138     unsigned ScalarSize = CVT.getSizeInBits();
5139
5140     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5141       const Constant *C = 0;
5142       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5143         C = CI->getConstantIntValue();
5144       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5145         C = CF->getConstantFPValue();
5146
5147       assert(C && "Invalid constant type");
5148
5149       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5150       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5151       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5152                        MachinePointerInfo::getConstantPool(),
5153                        false, false, false, Alignment);
5154
5155       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5156     }
5157   }
5158
5159   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5160   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5161
5162   // Handle AVX2 in-register broadcasts.
5163   if (!IsLoad && Subtarget->hasAVX2() &&
5164       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5165     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5166
5167   // The scalar source must be a normal load.
5168   if (!IsLoad)
5169     return SDValue();
5170
5171   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5172     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5173
5174   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5175   // double since there is no vbroadcastsd xmm
5176   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5177     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5178       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5179   }
5180
5181   // Unsupported broadcast.
5182   return SDValue();
5183 }
5184
5185 SDValue
5186 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5187   EVT VT = Op.getValueType();
5188
5189   // Skip if insert_vec_elt is not supported.
5190   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5191     return SDValue();
5192
5193   DebugLoc DL = Op.getDebugLoc();
5194   unsigned NumElems = Op.getNumOperands();
5195
5196   SDValue VecIn1;
5197   SDValue VecIn2;
5198   SmallVector<unsigned, 4> InsertIndices;
5199   SmallVector<int, 8> Mask(NumElems, -1);
5200
5201   for (unsigned i = 0; i != NumElems; ++i) {
5202     unsigned Opc = Op.getOperand(i).getOpcode();
5203
5204     if (Opc == ISD::UNDEF)
5205       continue;
5206
5207     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5208       // Quit if more than 1 elements need inserting.
5209       if (InsertIndices.size() > 1)
5210         return SDValue();
5211
5212       InsertIndices.push_back(i);
5213       continue;
5214     }
5215
5216     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5217     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5218
5219     // Quit if extracted from vector of different type.
5220     if (ExtractedFromVec.getValueType() != VT)
5221       return SDValue();
5222
5223     // Quit if non-constant index.
5224     if (!isa<ConstantSDNode>(ExtIdx))
5225       return SDValue();
5226
5227     if (VecIn1.getNode() == 0)
5228       VecIn1 = ExtractedFromVec;
5229     else if (VecIn1 != ExtractedFromVec) {
5230       if (VecIn2.getNode() == 0)
5231         VecIn2 = ExtractedFromVec;
5232       else if (VecIn2 != ExtractedFromVec)
5233         // Quit if more than 2 vectors to shuffle
5234         return SDValue();
5235     }
5236
5237     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5238
5239     if (ExtractedFromVec == VecIn1)
5240       Mask[i] = Idx;
5241     else if (ExtractedFromVec == VecIn2)
5242       Mask[i] = Idx + NumElems;
5243   }
5244
5245   if (VecIn1.getNode() == 0)
5246     return SDValue();
5247
5248   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5249   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5250   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5251     unsigned Idx = InsertIndices[i];
5252     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5253                      DAG.getIntPtrConstant(Idx));
5254   }
5255
5256   return NV;
5257 }
5258
5259 SDValue
5260 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5261   DebugLoc dl = Op.getDebugLoc();
5262
5263   EVT VT = Op.getValueType();
5264   EVT ExtVT = VT.getVectorElementType();
5265   unsigned NumElems = Op.getNumOperands();
5266
5267   // Vectors containing all zeros can be matched by pxor and xorps later
5268   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5269     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5270     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5271     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5272       return Op;
5273
5274     return getZeroVector(VT, Subtarget, DAG, dl);
5275   }
5276
5277   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5278   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5279   // vpcmpeqd on 256-bit vectors.
5280   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5281     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5282       return Op;
5283
5284     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5285   }
5286
5287   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5288   if (Broadcast.getNode())
5289     return Broadcast;
5290
5291   unsigned EVTBits = ExtVT.getSizeInBits();
5292
5293   unsigned NumZero  = 0;
5294   unsigned NumNonZero = 0;
5295   unsigned NonZeros = 0;
5296   bool IsAllConstants = true;
5297   SmallSet<SDValue, 8> Values;
5298   for (unsigned i = 0; i < NumElems; ++i) {
5299     SDValue Elt = Op.getOperand(i);
5300     if (Elt.getOpcode() == ISD::UNDEF)
5301       continue;
5302     Values.insert(Elt);
5303     if (Elt.getOpcode() != ISD::Constant &&
5304         Elt.getOpcode() != ISD::ConstantFP)
5305       IsAllConstants = false;
5306     if (X86::isZeroNode(Elt))
5307       NumZero++;
5308     else {
5309       NonZeros |= (1 << i);
5310       NumNonZero++;
5311     }
5312   }
5313
5314   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5315   if (NumNonZero == 0)
5316     return DAG.getUNDEF(VT);
5317
5318   // Special case for single non-zero, non-undef, element.
5319   if (NumNonZero == 1) {
5320     unsigned Idx = CountTrailingZeros_32(NonZeros);
5321     SDValue Item = Op.getOperand(Idx);
5322
5323     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5324     // the value are obviously zero, truncate the value to i32 and do the
5325     // insertion that way.  Only do this if the value is non-constant or if the
5326     // value is a constant being inserted into element 0.  It is cheaper to do
5327     // a constant pool load than it is to do a movd + shuffle.
5328     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5329         (!IsAllConstants || Idx == 0)) {
5330       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5331         // Handle SSE only.
5332         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5333         EVT VecVT = MVT::v4i32;
5334         unsigned VecElts = 4;
5335
5336         // Truncate the value (which may itself be a constant) to i32, and
5337         // convert it to a vector with movd (S2V+shuffle to zero extend).
5338         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5339         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5340         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5341
5342         // Now we have our 32-bit value zero extended in the low element of
5343         // a vector.  If Idx != 0, swizzle it into place.
5344         if (Idx != 0) {
5345           SmallVector<int, 4> Mask;
5346           Mask.push_back(Idx);
5347           for (unsigned i = 1; i != VecElts; ++i)
5348             Mask.push_back(i);
5349           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5350                                       &Mask[0]);
5351         }
5352         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5353       }
5354     }
5355
5356     // If we have a constant or non-constant insertion into the low element of
5357     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5358     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5359     // depending on what the source datatype is.
5360     if (Idx == 0) {
5361       if (NumZero == 0)
5362         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5363
5364       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5365           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5366         if (VT.is256BitVector()) {
5367           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5368           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5369                              Item, DAG.getIntPtrConstant(0));
5370         }
5371         assert(VT.is128BitVector() && "Expected an SSE value type!");
5372         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5373         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5374         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5375       }
5376
5377       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5378         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5379         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5380         if (VT.is256BitVector()) {
5381           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5382           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5383         } else {
5384           assert(VT.is128BitVector() && "Expected an SSE value type!");
5385           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5386         }
5387         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5388       }
5389     }
5390
5391     // Is it a vector logical left shift?
5392     if (NumElems == 2 && Idx == 1 &&
5393         X86::isZeroNode(Op.getOperand(0)) &&
5394         !X86::isZeroNode(Op.getOperand(1))) {
5395       unsigned NumBits = VT.getSizeInBits();
5396       return getVShift(true, VT,
5397                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5398                                    VT, Op.getOperand(1)),
5399                        NumBits/2, DAG, *this, dl);
5400     }
5401
5402     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5403       return SDValue();
5404
5405     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5406     // is a non-constant being inserted into an element other than the low one,
5407     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5408     // movd/movss) to move this into the low element, then shuffle it into
5409     // place.
5410     if (EVTBits == 32) {
5411       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5412
5413       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5414       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5415       SmallVector<int, 8> MaskVec;
5416       for (unsigned i = 0; i != NumElems; ++i)
5417         MaskVec.push_back(i == Idx ? 0 : 1);
5418       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5419     }
5420   }
5421
5422   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5423   if (Values.size() == 1) {
5424     if (EVTBits == 32) {
5425       // Instead of a shuffle like this:
5426       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5427       // Check if it's possible to issue this instead.
5428       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5429       unsigned Idx = CountTrailingZeros_32(NonZeros);
5430       SDValue Item = Op.getOperand(Idx);
5431       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5432         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5433     }
5434     return SDValue();
5435   }
5436
5437   // A vector full of immediates; various special cases are already
5438   // handled, so this is best done with a single constant-pool load.
5439   if (IsAllConstants)
5440     return SDValue();
5441
5442   // For AVX-length vectors, build the individual 128-bit pieces and use
5443   // shuffles to put them in place.
5444   if (VT.is256BitVector()) {
5445     SmallVector<SDValue, 32> V;
5446     for (unsigned i = 0; i != NumElems; ++i)
5447       V.push_back(Op.getOperand(i));
5448
5449     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5450
5451     // Build both the lower and upper subvector.
5452     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5453     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5454                                 NumElems/2);
5455
5456     // Recreate the wider vector with the lower and upper part.
5457     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5458   }
5459
5460   // Let legalizer expand 2-wide build_vectors.
5461   if (EVTBits == 64) {
5462     if (NumNonZero == 1) {
5463       // One half is zero or undef.
5464       unsigned Idx = CountTrailingZeros_32(NonZeros);
5465       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5466                                  Op.getOperand(Idx));
5467       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5468     }
5469     return SDValue();
5470   }
5471
5472   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5473   if (EVTBits == 8 && NumElems == 16) {
5474     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5475                                         Subtarget, *this);
5476     if (V.getNode()) return V;
5477   }
5478
5479   if (EVTBits == 16 && NumElems == 8) {
5480     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5481                                       Subtarget, *this);
5482     if (V.getNode()) return V;
5483   }
5484
5485   // If element VT is == 32 bits, turn it into a number of shuffles.
5486   SmallVector<SDValue, 8> V(NumElems);
5487   if (NumElems == 4 && NumZero > 0) {
5488     for (unsigned i = 0; i < 4; ++i) {
5489       bool isZero = !(NonZeros & (1 << i));
5490       if (isZero)
5491         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5492       else
5493         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5494     }
5495
5496     for (unsigned i = 0; i < 2; ++i) {
5497       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5498         default: break;
5499         case 0:
5500           V[i] = V[i*2];  // Must be a zero vector.
5501           break;
5502         case 1:
5503           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5504           break;
5505         case 2:
5506           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5507           break;
5508         case 3:
5509           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5510           break;
5511       }
5512     }
5513
5514     bool Reverse1 = (NonZeros & 0x3) == 2;
5515     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5516     int MaskVec[] = {
5517       Reverse1 ? 1 : 0,
5518       Reverse1 ? 0 : 1,
5519       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5520       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5521     };
5522     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5523   }
5524
5525   if (Values.size() > 1 && VT.is128BitVector()) {
5526     // Check for a build vector of consecutive loads.
5527     for (unsigned i = 0; i < NumElems; ++i)
5528       V[i] = Op.getOperand(i);
5529
5530     // Check for elements which are consecutive loads.
5531     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5532     if (LD.getNode())
5533       return LD;
5534
5535     // Check for a build vector from mostly shuffle plus few inserting.
5536     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5537     if (Sh.getNode())
5538       return Sh;
5539
5540     // For SSE 4.1, use insertps to put the high elements into the low element.
5541     if (getSubtarget()->hasSSE41()) {
5542       SDValue Result;
5543       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5544         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5545       else
5546         Result = DAG.getUNDEF(VT);
5547
5548       for (unsigned i = 1; i < NumElems; ++i) {
5549         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5550         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5551                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5552       }
5553       return Result;
5554     }
5555
5556     // Otherwise, expand into a number of unpckl*, start by extending each of
5557     // our (non-undef) elements to the full vector width with the element in the
5558     // bottom slot of the vector (which generates no code for SSE).
5559     for (unsigned i = 0; i < NumElems; ++i) {
5560       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5561         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5562       else
5563         V[i] = DAG.getUNDEF(VT);
5564     }
5565
5566     // Next, we iteratively mix elements, e.g. for v4f32:
5567     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5568     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5569     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5570     unsigned EltStride = NumElems >> 1;
5571     while (EltStride != 0) {
5572       for (unsigned i = 0; i < EltStride; ++i) {
5573         // If V[i+EltStride] is undef and this is the first round of mixing,
5574         // then it is safe to just drop this shuffle: V[i] is already in the
5575         // right place, the one element (since it's the first round) being
5576         // inserted as undef can be dropped.  This isn't safe for successive
5577         // rounds because they will permute elements within both vectors.
5578         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5579             EltStride == NumElems/2)
5580           continue;
5581
5582         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5583       }
5584       EltStride >>= 1;
5585     }
5586     return V[0];
5587   }
5588   return SDValue();
5589 }
5590
5591 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5592 // to create 256-bit vectors from two other 128-bit ones.
5593 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5594   DebugLoc dl = Op.getDebugLoc();
5595   EVT ResVT = Op.getValueType();
5596
5597   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5598
5599   SDValue V1 = Op.getOperand(0);
5600   SDValue V2 = Op.getOperand(1);
5601   unsigned NumElems = ResVT.getVectorNumElements();
5602
5603   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5604 }
5605
5606 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5607   assert(Op.getNumOperands() == 2);
5608
5609   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5610   // from two other 128-bit ones.
5611   return LowerAVXCONCAT_VECTORS(Op, DAG);
5612 }
5613
5614 // Try to lower a shuffle node into a simple blend instruction.
5615 static SDValue
5616 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5617                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5618   SDValue V1 = SVOp->getOperand(0);
5619   SDValue V2 = SVOp->getOperand(1);
5620   DebugLoc dl = SVOp->getDebugLoc();
5621   MVT VT = SVOp->getValueType(0).getSimpleVT();
5622   unsigned NumElems = VT.getVectorNumElements();
5623
5624   if (!Subtarget->hasSSE41())
5625     return SDValue();
5626
5627   unsigned ISDNo = 0;
5628   MVT OpTy;
5629
5630   switch (VT.SimpleTy) {
5631   default: return SDValue();
5632   case MVT::v8i16:
5633     ISDNo = X86ISD::BLENDPW;
5634     OpTy = MVT::v8i16;
5635     break;
5636   case MVT::v4i32:
5637   case MVT::v4f32:
5638     ISDNo = X86ISD::BLENDPS;
5639     OpTy = MVT::v4f32;
5640     break;
5641   case MVT::v2i64:
5642   case MVT::v2f64:
5643     ISDNo = X86ISD::BLENDPD;
5644     OpTy = MVT::v2f64;
5645     break;
5646   case MVT::v8i32:
5647   case MVT::v8f32:
5648     if (!Subtarget->hasAVX())
5649       return SDValue();
5650     ISDNo = X86ISD::BLENDPS;
5651     OpTy = MVT::v8f32;
5652     break;
5653   case MVT::v4i64:
5654   case MVT::v4f64:
5655     if (!Subtarget->hasAVX())
5656       return SDValue();
5657     ISDNo = X86ISD::BLENDPD;
5658     OpTy = MVT::v4f64;
5659     break;
5660   }
5661   assert(ISDNo && "Invalid Op Number");
5662
5663   unsigned MaskVals = 0;
5664
5665   for (unsigned i = 0; i != NumElems; ++i) {
5666     int EltIdx = SVOp->getMaskElt(i);
5667     if (EltIdx == (int)i || EltIdx < 0)
5668       MaskVals |= (1<<i);
5669     else if (EltIdx == (int)(i + NumElems))
5670       continue; // Bit is set to zero;
5671     else
5672       return SDValue();
5673   }
5674
5675   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5676   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5677   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5678                              DAG.getConstant(MaskVals, MVT::i32));
5679   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5680 }
5681
5682 // v8i16 shuffles - Prefer shuffles in the following order:
5683 // 1. [all]   pshuflw, pshufhw, optional move
5684 // 2. [ssse3] 1 x pshufb
5685 // 3. [ssse3] 2 x pshufb + 1 x por
5686 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5687 static SDValue
5688 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5689                          SelectionDAG &DAG) {
5690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5691   SDValue V1 = SVOp->getOperand(0);
5692   SDValue V2 = SVOp->getOperand(1);
5693   DebugLoc dl = SVOp->getDebugLoc();
5694   SmallVector<int, 8> MaskVals;
5695
5696   // Determine if more than 1 of the words in each of the low and high quadwords
5697   // of the result come from the same quadword of one of the two inputs.  Undef
5698   // mask values count as coming from any quadword, for better codegen.
5699   unsigned LoQuad[] = { 0, 0, 0, 0 };
5700   unsigned HiQuad[] = { 0, 0, 0, 0 };
5701   std::bitset<4> InputQuads;
5702   for (unsigned i = 0; i < 8; ++i) {
5703     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5704     int EltIdx = SVOp->getMaskElt(i);
5705     MaskVals.push_back(EltIdx);
5706     if (EltIdx < 0) {
5707       ++Quad[0];
5708       ++Quad[1];
5709       ++Quad[2];
5710       ++Quad[3];
5711       continue;
5712     }
5713     ++Quad[EltIdx / 4];
5714     InputQuads.set(EltIdx / 4);
5715   }
5716
5717   int BestLoQuad = -1;
5718   unsigned MaxQuad = 1;
5719   for (unsigned i = 0; i < 4; ++i) {
5720     if (LoQuad[i] > MaxQuad) {
5721       BestLoQuad = i;
5722       MaxQuad = LoQuad[i];
5723     }
5724   }
5725
5726   int BestHiQuad = -1;
5727   MaxQuad = 1;
5728   for (unsigned i = 0; i < 4; ++i) {
5729     if (HiQuad[i] > MaxQuad) {
5730       BestHiQuad = i;
5731       MaxQuad = HiQuad[i];
5732     }
5733   }
5734
5735   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5736   // of the two input vectors, shuffle them into one input vector so only a
5737   // single pshufb instruction is necessary. If There are more than 2 input
5738   // quads, disable the next transformation since it does not help SSSE3.
5739   bool V1Used = InputQuads[0] || InputQuads[1];
5740   bool V2Used = InputQuads[2] || InputQuads[3];
5741   if (Subtarget->hasSSSE3()) {
5742     if (InputQuads.count() == 2 && V1Used && V2Used) {
5743       BestLoQuad = InputQuads[0] ? 0 : 1;
5744       BestHiQuad = InputQuads[2] ? 2 : 3;
5745     }
5746     if (InputQuads.count() > 2) {
5747       BestLoQuad = -1;
5748       BestHiQuad = -1;
5749     }
5750   }
5751
5752   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5753   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5754   // words from all 4 input quadwords.
5755   SDValue NewV;
5756   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5757     int MaskV[] = {
5758       BestLoQuad < 0 ? 0 : BestLoQuad,
5759       BestHiQuad < 0 ? 1 : BestHiQuad
5760     };
5761     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5762                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5763                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5764     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5765
5766     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5767     // source words for the shuffle, to aid later transformations.
5768     bool AllWordsInNewV = true;
5769     bool InOrder[2] = { true, true };
5770     for (unsigned i = 0; i != 8; ++i) {
5771       int idx = MaskVals[i];
5772       if (idx != (int)i)
5773         InOrder[i/4] = false;
5774       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5775         continue;
5776       AllWordsInNewV = false;
5777       break;
5778     }
5779
5780     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5781     if (AllWordsInNewV) {
5782       for (int i = 0; i != 8; ++i) {
5783         int idx = MaskVals[i];
5784         if (idx < 0)
5785           continue;
5786         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5787         if ((idx != i) && idx < 4)
5788           pshufhw = false;
5789         if ((idx != i) && idx > 3)
5790           pshuflw = false;
5791       }
5792       V1 = NewV;
5793       V2Used = false;
5794       BestLoQuad = 0;
5795       BestHiQuad = 1;
5796     }
5797
5798     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5799     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5800     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5801       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5802       unsigned TargetMask = 0;
5803       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5804                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5805       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5806       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5807                              getShufflePSHUFLWImmediate(SVOp);
5808       V1 = NewV.getOperand(0);
5809       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5810     }
5811   }
5812
5813   // If we have SSSE3, and all words of the result are from 1 input vector,
5814   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5815   // is present, fall back to case 4.
5816   if (Subtarget->hasSSSE3()) {
5817     SmallVector<SDValue,16> pshufbMask;
5818
5819     // If we have elements from both input vectors, set the high bit of the
5820     // shuffle mask element to zero out elements that come from V2 in the V1
5821     // mask, and elements that come from V1 in the V2 mask, so that the two
5822     // results can be OR'd together.
5823     bool TwoInputs = V1Used && V2Used;
5824     for (unsigned i = 0; i != 8; ++i) {
5825       int EltIdx = MaskVals[i] * 2;
5826       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5827       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5828       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5829       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5830     }
5831     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5832     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5833                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5834                                  MVT::v16i8, &pshufbMask[0], 16));
5835     if (!TwoInputs)
5836       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5837
5838     // Calculate the shuffle mask for the second input, shuffle it, and
5839     // OR it with the first shuffled input.
5840     pshufbMask.clear();
5841     for (unsigned i = 0; i != 8; ++i) {
5842       int EltIdx = MaskVals[i] * 2;
5843       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5844       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5845       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5846       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5847     }
5848     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5849     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5850                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5851                                  MVT::v16i8, &pshufbMask[0], 16));
5852     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5853     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5854   }
5855
5856   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5857   // and update MaskVals with new element order.
5858   std::bitset<8> InOrder;
5859   if (BestLoQuad >= 0) {
5860     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5861     for (int i = 0; i != 4; ++i) {
5862       int idx = MaskVals[i];
5863       if (idx < 0) {
5864         InOrder.set(i);
5865       } else if ((idx / 4) == BestLoQuad) {
5866         MaskV[i] = idx & 3;
5867         InOrder.set(i);
5868       }
5869     }
5870     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5871                                 &MaskV[0]);
5872
5873     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5874       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5875       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5876                                   NewV.getOperand(0),
5877                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5878     }
5879   }
5880
5881   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5882   // and update MaskVals with the new element order.
5883   if (BestHiQuad >= 0) {
5884     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5885     for (unsigned i = 4; i != 8; ++i) {
5886       int idx = MaskVals[i];
5887       if (idx < 0) {
5888         InOrder.set(i);
5889       } else if ((idx / 4) == BestHiQuad) {
5890         MaskV[i] = (idx & 3) + 4;
5891         InOrder.set(i);
5892       }
5893     }
5894     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5895                                 &MaskV[0]);
5896
5897     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5898       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5899       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5900                                   NewV.getOperand(0),
5901                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5902     }
5903   }
5904
5905   // In case BestHi & BestLo were both -1, which means each quadword has a word
5906   // from each of the four input quadwords, calculate the InOrder bitvector now
5907   // before falling through to the insert/extract cleanup.
5908   if (BestLoQuad == -1 && BestHiQuad == -1) {
5909     NewV = V1;
5910     for (int i = 0; i != 8; ++i)
5911       if (MaskVals[i] < 0 || MaskVals[i] == i)
5912         InOrder.set(i);
5913   }
5914
5915   // The other elements are put in the right place using pextrw and pinsrw.
5916   for (unsigned i = 0; i != 8; ++i) {
5917     if (InOrder[i])
5918       continue;
5919     int EltIdx = MaskVals[i];
5920     if (EltIdx < 0)
5921       continue;
5922     SDValue ExtOp = (EltIdx < 8) ?
5923       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5924                   DAG.getIntPtrConstant(EltIdx)) :
5925       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5926                   DAG.getIntPtrConstant(EltIdx - 8));
5927     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5928                        DAG.getIntPtrConstant(i));
5929   }
5930   return NewV;
5931 }
5932
5933 // v16i8 shuffles - Prefer shuffles in the following order:
5934 // 1. [ssse3] 1 x pshufb
5935 // 2. [ssse3] 2 x pshufb + 1 x por
5936 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5937 static
5938 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5939                                  SelectionDAG &DAG,
5940                                  const X86TargetLowering &TLI) {
5941   SDValue V1 = SVOp->getOperand(0);
5942   SDValue V2 = SVOp->getOperand(1);
5943   DebugLoc dl = SVOp->getDebugLoc();
5944   ArrayRef<int> MaskVals = SVOp->getMask();
5945
5946   // If we have SSSE3, case 1 is generated when all result bytes come from
5947   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5948   // present, fall back to case 3.
5949
5950   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5951   if (TLI.getSubtarget()->hasSSSE3()) {
5952     SmallVector<SDValue,16> pshufbMask;
5953
5954     // If all result elements are from one input vector, then only translate
5955     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5956     //
5957     // Otherwise, we have elements from both input vectors, and must zero out
5958     // elements that come from V2 in the first mask, and V1 in the second mask
5959     // so that we can OR them together.
5960     for (unsigned i = 0; i != 16; ++i) {
5961       int EltIdx = MaskVals[i];
5962       if (EltIdx < 0 || EltIdx >= 16)
5963         EltIdx = 0x80;
5964       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5965     }
5966     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5967                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5968                                  MVT::v16i8, &pshufbMask[0], 16));
5969
5970     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5971     // the 2nd operand if it's undefined or zero.
5972     if (V2.getOpcode() == ISD::UNDEF ||
5973         ISD::isBuildVectorAllZeros(V2.getNode()))
5974       return V1;
5975
5976     // Calculate the shuffle mask for the second input, shuffle it, and
5977     // OR it with the first shuffled input.
5978     pshufbMask.clear();
5979     for (unsigned i = 0; i != 16; ++i) {
5980       int EltIdx = MaskVals[i];
5981       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5982       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5983     }
5984     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5985                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5986                                  MVT::v16i8, &pshufbMask[0], 16));
5987     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5988   }
5989
5990   // No SSSE3 - Calculate in place words and then fix all out of place words
5991   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5992   // the 16 different words that comprise the two doublequadword input vectors.
5993   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5994   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5995   SDValue NewV = V1;
5996   for (int i = 0; i != 8; ++i) {
5997     int Elt0 = MaskVals[i*2];
5998     int Elt1 = MaskVals[i*2+1];
5999
6000     // This word of the result is all undef, skip it.
6001     if (Elt0 < 0 && Elt1 < 0)
6002       continue;
6003
6004     // This word of the result is already in the correct place, skip it.
6005     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6006       continue;
6007
6008     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6009     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6010     SDValue InsElt;
6011
6012     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6013     // using a single extract together, load it and store it.
6014     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6015       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6016                            DAG.getIntPtrConstant(Elt1 / 2));
6017       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6018                         DAG.getIntPtrConstant(i));
6019       continue;
6020     }
6021
6022     // If Elt1 is defined, extract it from the appropriate source.  If the
6023     // source byte is not also odd, shift the extracted word left 8 bits
6024     // otherwise clear the bottom 8 bits if we need to do an or.
6025     if (Elt1 >= 0) {
6026       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6027                            DAG.getIntPtrConstant(Elt1 / 2));
6028       if ((Elt1 & 1) == 0)
6029         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6030                              DAG.getConstant(8,
6031                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6032       else if (Elt0 >= 0)
6033         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6034                              DAG.getConstant(0xFF00, MVT::i16));
6035     }
6036     // If Elt0 is defined, extract it from the appropriate source.  If the
6037     // source byte is not also even, shift the extracted word right 8 bits. If
6038     // Elt1 was also defined, OR the extracted values together before
6039     // inserting them in the result.
6040     if (Elt0 >= 0) {
6041       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6042                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6043       if ((Elt0 & 1) != 0)
6044         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6045                               DAG.getConstant(8,
6046                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6047       else if (Elt1 >= 0)
6048         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6049                              DAG.getConstant(0x00FF, MVT::i16));
6050       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6051                          : InsElt0;
6052     }
6053     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6054                        DAG.getIntPtrConstant(i));
6055   }
6056   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6057 }
6058
6059 // v32i8 shuffles - Translate to VPSHUFB if possible.
6060 static
6061 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6062                                  const X86Subtarget *Subtarget,
6063                                  SelectionDAG &DAG) {
6064   EVT VT = SVOp->getValueType(0);
6065   SDValue V1 = SVOp->getOperand(0);
6066   SDValue V2 = SVOp->getOperand(1);
6067   DebugLoc dl = SVOp->getDebugLoc();
6068   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6069
6070   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6071   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6072   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6073
6074   // VPSHUFB may be generated if
6075   // (1) one of input vector is undefined or zeroinitializer.
6076   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6077   // And (2) the mask indexes don't cross the 128-bit lane.
6078   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6079       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6080     return SDValue();
6081
6082   if (V1IsAllZero && !V2IsAllZero) {
6083     CommuteVectorShuffleMask(MaskVals, 32);
6084     V1 = V2;
6085   }
6086   SmallVector<SDValue, 32> pshufbMask;
6087   for (unsigned i = 0; i != 32; i++) {
6088     int EltIdx = MaskVals[i];
6089     if (EltIdx < 0 || EltIdx >= 32)
6090       EltIdx = 0x80;
6091     else {
6092       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6093         // Cross lane is not allowed.
6094         return SDValue();
6095       EltIdx &= 0xf;
6096     }
6097     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6098   }
6099   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6100                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6101                                   MVT::v32i8, &pshufbMask[0], 32));
6102 }
6103
6104 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6105 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6106 /// done when every pair / quad of shuffle mask elements point to elements in
6107 /// the right sequence. e.g.
6108 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6109 static
6110 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6111                                  SelectionDAG &DAG, DebugLoc dl) {
6112   MVT VT = SVOp->getValueType(0).getSimpleVT();
6113   unsigned NumElems = VT.getVectorNumElements();
6114   MVT NewVT;
6115   unsigned Scale;
6116   switch (VT.SimpleTy) {
6117   default: llvm_unreachable("Unexpected!");
6118   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6119   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6120   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6121   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6122   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6123   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6124   }
6125
6126   SmallVector<int, 8> MaskVec;
6127   for (unsigned i = 0; i != NumElems; i += Scale) {
6128     int StartIdx = -1;
6129     for (unsigned j = 0; j != Scale; ++j) {
6130       int EltIdx = SVOp->getMaskElt(i+j);
6131       if (EltIdx < 0)
6132         continue;
6133       if (StartIdx < 0)
6134         StartIdx = (EltIdx / Scale);
6135       if (EltIdx != (int)(StartIdx*Scale + j))
6136         return SDValue();
6137     }
6138     MaskVec.push_back(StartIdx);
6139   }
6140
6141   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6142   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6143   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6144 }
6145
6146 /// getVZextMovL - Return a zero-extending vector move low node.
6147 ///
6148 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6149                             SDValue SrcOp, SelectionDAG &DAG,
6150                             const X86Subtarget *Subtarget, DebugLoc dl) {
6151   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6152     LoadSDNode *LD = NULL;
6153     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6154       LD = dyn_cast<LoadSDNode>(SrcOp);
6155     if (!LD) {
6156       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6157       // instead.
6158       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6159       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6160           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6161           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6162           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6163         // PR2108
6164         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6165         return DAG.getNode(ISD::BITCAST, dl, VT,
6166                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6167                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6168                                                    OpVT,
6169                                                    SrcOp.getOperand(0)
6170                                                           .getOperand(0))));
6171       }
6172     }
6173   }
6174
6175   return DAG.getNode(ISD::BITCAST, dl, VT,
6176                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6177                                  DAG.getNode(ISD::BITCAST, dl,
6178                                              OpVT, SrcOp)));
6179 }
6180
6181 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6182 /// which could not be matched by any known target speficic shuffle
6183 static SDValue
6184 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6185
6186   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6187   if (NewOp.getNode())
6188     return NewOp;
6189
6190   EVT VT = SVOp->getValueType(0);
6191
6192   unsigned NumElems = VT.getVectorNumElements();
6193   unsigned NumLaneElems = NumElems / 2;
6194
6195   DebugLoc dl = SVOp->getDebugLoc();
6196   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6197   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6198   SDValue Output[2];
6199
6200   SmallVector<int, 16> Mask;
6201   for (unsigned l = 0; l < 2; ++l) {
6202     // Build a shuffle mask for the output, discovering on the fly which
6203     // input vectors to use as shuffle operands (recorded in InputUsed).
6204     // If building a suitable shuffle vector proves too hard, then bail
6205     // out with UseBuildVector set.
6206     bool UseBuildVector = false;
6207     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6208     unsigned LaneStart = l * NumLaneElems;
6209     for (unsigned i = 0; i != NumLaneElems; ++i) {
6210       // The mask element.  This indexes into the input.
6211       int Idx = SVOp->getMaskElt(i+LaneStart);
6212       if (Idx < 0) {
6213         // the mask element does not index into any input vector.
6214         Mask.push_back(-1);
6215         continue;
6216       }
6217
6218       // The input vector this mask element indexes into.
6219       int Input = Idx / NumLaneElems;
6220
6221       // Turn the index into an offset from the start of the input vector.
6222       Idx -= Input * NumLaneElems;
6223
6224       // Find or create a shuffle vector operand to hold this input.
6225       unsigned OpNo;
6226       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6227         if (InputUsed[OpNo] == Input)
6228           // This input vector is already an operand.
6229           break;
6230         if (InputUsed[OpNo] < 0) {
6231           // Create a new operand for this input vector.
6232           InputUsed[OpNo] = Input;
6233           break;
6234         }
6235       }
6236
6237       if (OpNo >= array_lengthof(InputUsed)) {
6238         // More than two input vectors used!  Give up on trying to create a
6239         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6240         UseBuildVector = true;
6241         break;
6242       }
6243
6244       // Add the mask index for the new shuffle vector.
6245       Mask.push_back(Idx + OpNo * NumLaneElems);
6246     }
6247
6248     if (UseBuildVector) {
6249       SmallVector<SDValue, 16> SVOps;
6250       for (unsigned i = 0; i != NumLaneElems; ++i) {
6251         // The mask element.  This indexes into the input.
6252         int Idx = SVOp->getMaskElt(i+LaneStart);
6253         if (Idx < 0) {
6254           SVOps.push_back(DAG.getUNDEF(EltVT));
6255           continue;
6256         }
6257
6258         // The input vector this mask element indexes into.
6259         int Input = Idx / NumElems;
6260
6261         // Turn the index into an offset from the start of the input vector.
6262         Idx -= Input * NumElems;
6263
6264         // Extract the vector element by hand.
6265         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6266                                     SVOp->getOperand(Input),
6267                                     DAG.getIntPtrConstant(Idx)));
6268       }
6269
6270       // Construct the output using a BUILD_VECTOR.
6271       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6272                               SVOps.size());
6273     } else if (InputUsed[0] < 0) {
6274       // No input vectors were used! The result is undefined.
6275       Output[l] = DAG.getUNDEF(NVT);
6276     } else {
6277       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6278                                         (InputUsed[0] % 2) * NumLaneElems,
6279                                         DAG, dl);
6280       // If only one input was used, use an undefined vector for the other.
6281       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6282         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6283                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6284       // At least one input vector was used. Create a new shuffle vector.
6285       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6286     }
6287
6288     Mask.clear();
6289   }
6290
6291   // Concatenate the result back
6292   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6293 }
6294
6295 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6296 /// 4 elements, and match them with several different shuffle types.
6297 static SDValue
6298 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6299   SDValue V1 = SVOp->getOperand(0);
6300   SDValue V2 = SVOp->getOperand(1);
6301   DebugLoc dl = SVOp->getDebugLoc();
6302   EVT VT = SVOp->getValueType(0);
6303
6304   assert(VT.is128BitVector() && "Unsupported vector size");
6305
6306   std::pair<int, int> Locs[4];
6307   int Mask1[] = { -1, -1, -1, -1 };
6308   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6309
6310   unsigned NumHi = 0;
6311   unsigned NumLo = 0;
6312   for (unsigned i = 0; i != 4; ++i) {
6313     int Idx = PermMask[i];
6314     if (Idx < 0) {
6315       Locs[i] = std::make_pair(-1, -1);
6316     } else {
6317       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6318       if (Idx < 4) {
6319         Locs[i] = std::make_pair(0, NumLo);
6320         Mask1[NumLo] = Idx;
6321         NumLo++;
6322       } else {
6323         Locs[i] = std::make_pair(1, NumHi);
6324         if (2+NumHi < 4)
6325           Mask1[2+NumHi] = Idx;
6326         NumHi++;
6327       }
6328     }
6329   }
6330
6331   if (NumLo <= 2 && NumHi <= 2) {
6332     // If no more than two elements come from either vector. This can be
6333     // implemented with two shuffles. First shuffle gather the elements.
6334     // The second shuffle, which takes the first shuffle as both of its
6335     // vector operands, put the elements into the right order.
6336     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6337
6338     int Mask2[] = { -1, -1, -1, -1 };
6339
6340     for (unsigned i = 0; i != 4; ++i)
6341       if (Locs[i].first != -1) {
6342         unsigned Idx = (i < 2) ? 0 : 4;
6343         Idx += Locs[i].first * 2 + Locs[i].second;
6344         Mask2[i] = Idx;
6345       }
6346
6347     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6348   }
6349
6350   if (NumLo == 3 || NumHi == 3) {
6351     // Otherwise, we must have three elements from one vector, call it X, and
6352     // one element from the other, call it Y.  First, use a shufps to build an
6353     // intermediate vector with the one element from Y and the element from X
6354     // that will be in the same half in the final destination (the indexes don't
6355     // matter). Then, use a shufps to build the final vector, taking the half
6356     // containing the element from Y from the intermediate, and the other half
6357     // from X.
6358     if (NumHi == 3) {
6359       // Normalize it so the 3 elements come from V1.
6360       CommuteVectorShuffleMask(PermMask, 4);
6361       std::swap(V1, V2);
6362     }
6363
6364     // Find the element from V2.
6365     unsigned HiIndex;
6366     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6367       int Val = PermMask[HiIndex];
6368       if (Val < 0)
6369         continue;
6370       if (Val >= 4)
6371         break;
6372     }
6373
6374     Mask1[0] = PermMask[HiIndex];
6375     Mask1[1] = -1;
6376     Mask1[2] = PermMask[HiIndex^1];
6377     Mask1[3] = -1;
6378     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6379
6380     if (HiIndex >= 2) {
6381       Mask1[0] = PermMask[0];
6382       Mask1[1] = PermMask[1];
6383       Mask1[2] = HiIndex & 1 ? 6 : 4;
6384       Mask1[3] = HiIndex & 1 ? 4 : 6;
6385       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6386     }
6387
6388     Mask1[0] = HiIndex & 1 ? 2 : 0;
6389     Mask1[1] = HiIndex & 1 ? 0 : 2;
6390     Mask1[2] = PermMask[2];
6391     Mask1[3] = PermMask[3];
6392     if (Mask1[2] >= 0)
6393       Mask1[2] += 4;
6394     if (Mask1[3] >= 0)
6395       Mask1[3] += 4;
6396     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6397   }
6398
6399   // Break it into (shuffle shuffle_hi, shuffle_lo).
6400   int LoMask[] = { -1, -1, -1, -1 };
6401   int HiMask[] = { -1, -1, -1, -1 };
6402
6403   int *MaskPtr = LoMask;
6404   unsigned MaskIdx = 0;
6405   unsigned LoIdx = 0;
6406   unsigned HiIdx = 2;
6407   for (unsigned i = 0; i != 4; ++i) {
6408     if (i == 2) {
6409       MaskPtr = HiMask;
6410       MaskIdx = 1;
6411       LoIdx = 0;
6412       HiIdx = 2;
6413     }
6414     int Idx = PermMask[i];
6415     if (Idx < 0) {
6416       Locs[i] = std::make_pair(-1, -1);
6417     } else if (Idx < 4) {
6418       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6419       MaskPtr[LoIdx] = Idx;
6420       LoIdx++;
6421     } else {
6422       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6423       MaskPtr[HiIdx] = Idx;
6424       HiIdx++;
6425     }
6426   }
6427
6428   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6429   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6430   int MaskOps[] = { -1, -1, -1, -1 };
6431   for (unsigned i = 0; i != 4; ++i)
6432     if (Locs[i].first != -1)
6433       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6434   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6435 }
6436
6437 static bool MayFoldVectorLoad(SDValue V) {
6438   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6439     V = V.getOperand(0);
6440   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6441     V = V.getOperand(0);
6442   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6443       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6444     // BUILD_VECTOR (load), undef
6445     V = V.getOperand(0);
6446   if (MayFoldLoad(V))
6447     return true;
6448   return false;
6449 }
6450
6451 // FIXME: the version above should always be used. Since there's
6452 // a bug where several vector shuffles can't be folded because the
6453 // DAG is not updated during lowering and a node claims to have two
6454 // uses while it only has one, use this version, and let isel match
6455 // another instruction if the load really happens to have more than
6456 // one use. Remove this version after this bug get fixed.
6457 // rdar://8434668, PR8156
6458 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6459   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6460     V = V.getOperand(0);
6461   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6462     V = V.getOperand(0);
6463   if (ISD::isNormalLoad(V.getNode()))
6464     return true;
6465   return false;
6466 }
6467
6468 static
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470   EVT VT = Op.getValueType();
6471
6472   // Canonizalize to v2f64.
6473   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474   return DAG.getNode(ISD::BITCAST, dl, VT,
6475                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6476                                           V1, DAG));
6477 }
6478
6479 static
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6481                         bool HasSSE2) {
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484   EVT VT = Op.getValueType();
6485
6486   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6487
6488   if (HasSSE2 && VT == MVT::v2f64)
6489     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6490
6491   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492   return DAG.getNode(ISD::BITCAST, dl, VT,
6493                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6496 }
6497
6498 static
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500   SDValue V1 = Op.getOperand(0);
6501   SDValue V2 = Op.getOperand(1);
6502   EVT VT = Op.getValueType();
6503
6504   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505          "unsupported shuffle type");
6506
6507   if (V2.getOpcode() == ISD::UNDEF)
6508     V2 = V1;
6509
6510   // v4i32 or v4f32
6511   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6512 }
6513
6514 static
6515 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6516   SDValue V1 = Op.getOperand(0);
6517   SDValue V2 = Op.getOperand(1);
6518   EVT VT = Op.getValueType();
6519   unsigned NumElems = VT.getVectorNumElements();
6520
6521   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6522   // operand of these instructions is only memory, so check if there's a
6523   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6524   // same masks.
6525   bool CanFoldLoad = false;
6526
6527   // Trivial case, when V2 comes from a load.
6528   if (MayFoldVectorLoad(V2))
6529     CanFoldLoad = true;
6530
6531   // When V1 is a load, it can be folded later into a store in isel, example:
6532   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6533   //    turns into:
6534   //  (MOVLPSmr addr:$src1, VR128:$src2)
6535   // So, recognize this potential and also use MOVLPS or MOVLPD
6536   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6537     CanFoldLoad = true;
6538
6539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6540   if (CanFoldLoad) {
6541     if (HasSSE2 && NumElems == 2)
6542       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6543
6544     if (NumElems == 4)
6545       // If we don't care about the second element, proceed to use movss.
6546       if (SVOp->getMaskElt(1) != -1)
6547         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6548   }
6549
6550   // movl and movlp will both match v2i64, but v2i64 is never matched by
6551   // movl earlier because we make it strict to avoid messing with the movlp load
6552   // folding logic (see the code above getMOVLP call). Match it here then,
6553   // this is horrible, but will stay like this until we move all shuffle
6554   // matching to x86 specific nodes. Note that for the 1st condition all
6555   // types are matched with movsd.
6556   if (HasSSE2) {
6557     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6558     // as to remove this logic from here, as much as possible
6559     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6560       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6561     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6562   }
6563
6564   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6565
6566   // Invert the operand order and use SHUFPS to match it.
6567   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6568                               getShuffleSHUFImmediate(SVOp), DAG);
6569 }
6570
6571 // Reduce a vector shuffle to zext.
6572 SDValue
6573 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6574   // PMOVZX is only available from SSE41.
6575   if (!Subtarget->hasSSE41())
6576     return SDValue();
6577
6578   EVT VT = Op.getValueType();
6579
6580   // Only AVX2 support 256-bit vector integer extending.
6581   if (!Subtarget->hasAVX2() && VT.is256BitVector())
6582     return SDValue();
6583
6584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6585   DebugLoc DL = Op.getDebugLoc();
6586   SDValue V1 = Op.getOperand(0);
6587   SDValue V2 = Op.getOperand(1);
6588   unsigned NumElems = VT.getVectorNumElements();
6589
6590   // Extending is an unary operation and the element type of the source vector
6591   // won't be equal to or larger than i64.
6592   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6593       VT.getVectorElementType() == MVT::i64)
6594     return SDValue();
6595
6596   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6597   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6598   while ((1 << Shift) < NumElems) {
6599     if (SVOp->getMaskElt(1 << Shift) == 1)
6600       break;
6601     Shift += 1;
6602     // The maximal ratio is 8, i.e. from i8 to i64.
6603     if (Shift > 3)
6604       return SDValue();
6605   }
6606
6607   // Check the shuffle mask.
6608   unsigned Mask = (1U << Shift) - 1;
6609   for (unsigned i = 0; i != NumElems; ++i) {
6610     int EltIdx = SVOp->getMaskElt(i);
6611     if ((i & Mask) != 0 && EltIdx != -1)
6612       return SDValue();
6613     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6614       return SDValue();
6615   }
6616
6617   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6618   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6619   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6620
6621   if (!isTypeLegal(NVT))
6622     return SDValue();
6623
6624   // Simplify the operand as it's prepared to be fed into shuffle.
6625   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6626   if (V1.getOpcode() == ISD::BITCAST &&
6627       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6628       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6629       V1.getOperand(0)
6630         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6631     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6632     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6633     // If it's foldable, i.e. normal load with single use, we will let code
6634     // selection to fold it. Otherwise, we will short the conversion sequence.
6635     if (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())
6636       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6637   }
6638
6639   return DAG.getNode(ISD::BITCAST, DL, VT,
6640                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6641 }
6642
6643 SDValue
6644 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6645   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6646   EVT VT = Op.getValueType();
6647   DebugLoc dl = Op.getDebugLoc();
6648   SDValue V1 = Op.getOperand(0);
6649   SDValue V2 = Op.getOperand(1);
6650
6651   if (isZeroShuffle(SVOp))
6652     return getZeroVector(VT, Subtarget, DAG, dl);
6653
6654   // Handle splat operations
6655   if (SVOp->isSplat()) {
6656     unsigned NumElem = VT.getVectorNumElements();
6657     int Size = VT.getSizeInBits();
6658
6659     // Use vbroadcast whenever the splat comes from a foldable load
6660     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6661     if (Broadcast.getNode())
6662       return Broadcast;
6663
6664     // Handle splats by matching through known shuffle masks
6665     if ((Size == 128 && NumElem <= 4) ||
6666         (Size == 256 && NumElem < 8))
6667       return SDValue();
6668
6669     // All remaning splats are promoted to target supported vector shuffles.
6670     return PromoteSplat(SVOp, DAG);
6671   }
6672
6673   // Check integer expanding shuffles.
6674   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6675   if (NewOp.getNode())
6676     return NewOp;
6677
6678   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6679   // do it!
6680   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6681       VT == MVT::v16i16 || VT == MVT::v32i8) {
6682     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6683     if (NewOp.getNode())
6684       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6685   } else if ((VT == MVT::v4i32 ||
6686              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6687     // FIXME: Figure out a cleaner way to do this.
6688     // Try to make use of movq to zero out the top part.
6689     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6690       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6691       if (NewOp.getNode()) {
6692         EVT NewVT = NewOp.getValueType();
6693         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6694                                NewVT, true, false))
6695           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6696                               DAG, Subtarget, dl);
6697       }
6698     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6699       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6700       if (NewOp.getNode()) {
6701         EVT NewVT = NewOp.getValueType();
6702         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6703           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6704                               DAG, Subtarget, dl);
6705       }
6706     }
6707   }
6708   return SDValue();
6709 }
6710
6711 SDValue
6712 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6713   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6714   SDValue V1 = Op.getOperand(0);
6715   SDValue V2 = Op.getOperand(1);
6716   EVT VT = Op.getValueType();
6717   DebugLoc dl = Op.getDebugLoc();
6718   unsigned NumElems = VT.getVectorNumElements();
6719   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6720   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6721   bool V1IsSplat = false;
6722   bool V2IsSplat = false;
6723   bool HasSSE2 = Subtarget->hasSSE2();
6724   bool HasAVX    = Subtarget->hasAVX();
6725   bool HasAVX2   = Subtarget->hasAVX2();
6726   MachineFunction &MF = DAG.getMachineFunction();
6727   bool OptForSize = MF.getFunction()->getFnAttributes().
6728     hasAttribute(Attributes::OptimizeForSize);
6729
6730   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6731
6732   if (V1IsUndef && V2IsUndef)
6733     return DAG.getUNDEF(VT);
6734
6735   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6736
6737   // Vector shuffle lowering takes 3 steps:
6738   //
6739   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6740   //    narrowing and commutation of operands should be handled.
6741   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6742   //    shuffle nodes.
6743   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6744   //    so the shuffle can be broken into other shuffles and the legalizer can
6745   //    try the lowering again.
6746   //
6747   // The general idea is that no vector_shuffle operation should be left to
6748   // be matched during isel, all of them must be converted to a target specific
6749   // node here.
6750
6751   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6752   // narrowing and commutation of operands should be handled. The actual code
6753   // doesn't include all of those, work in progress...
6754   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6755   if (NewOp.getNode())
6756     return NewOp;
6757
6758   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6759
6760   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6761   // unpckh_undef). Only use pshufd if speed is more important than size.
6762   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6763     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6764   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6765     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6766
6767   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6768       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6769     return getMOVDDup(Op, dl, V1, DAG);
6770
6771   if (isMOVHLPS_v_undef_Mask(M, VT))
6772     return getMOVHighToLow(Op, dl, DAG);
6773
6774   // Use to match splats
6775   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6776       (VT == MVT::v2f64 || VT == MVT::v2i64))
6777     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6778
6779   if (isPSHUFDMask(M, VT)) {
6780     // The actual implementation will match the mask in the if above and then
6781     // during isel it can match several different instructions, not only pshufd
6782     // as its name says, sad but true, emulate the behavior for now...
6783     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6784       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6785
6786     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6787
6788     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6789       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6790
6791     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6792       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6793
6794     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6795                                 TargetMask, DAG);
6796   }
6797
6798   // Check if this can be converted into a logical shift.
6799   bool isLeft = false;
6800   unsigned ShAmt = 0;
6801   SDValue ShVal;
6802   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6803   if (isShift && ShVal.hasOneUse()) {
6804     // If the shifted value has multiple uses, it may be cheaper to use
6805     // v_set0 + movlhps or movhlps, etc.
6806     EVT EltVT = VT.getVectorElementType();
6807     ShAmt *= EltVT.getSizeInBits();
6808     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6809   }
6810
6811   if (isMOVLMask(M, VT)) {
6812     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6813       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6814     if (!isMOVLPMask(M, VT)) {
6815       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6816         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6817
6818       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6819         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6820     }
6821   }
6822
6823   // FIXME: fold these into legal mask.
6824   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6825     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6826
6827   if (isMOVHLPSMask(M, VT))
6828     return getMOVHighToLow(Op, dl, DAG);
6829
6830   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6831     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6832
6833   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6834     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6835
6836   if (isMOVLPMask(M, VT))
6837     return getMOVLP(Op, dl, DAG, HasSSE2);
6838
6839   if (ShouldXformToMOVHLPS(M, VT) ||
6840       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6841     return CommuteVectorShuffle(SVOp, DAG);
6842
6843   if (isShift) {
6844     // No better options. Use a vshldq / vsrldq.
6845     EVT EltVT = VT.getVectorElementType();
6846     ShAmt *= EltVT.getSizeInBits();
6847     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6848   }
6849
6850   bool Commuted = false;
6851   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6852   // 1,1,1,1 -> v8i16 though.
6853   V1IsSplat = isSplatVector(V1.getNode());
6854   V2IsSplat = isSplatVector(V2.getNode());
6855
6856   // Canonicalize the splat or undef, if present, to be on the RHS.
6857   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6858     CommuteVectorShuffleMask(M, NumElems);
6859     std::swap(V1, V2);
6860     std::swap(V1IsSplat, V2IsSplat);
6861     Commuted = true;
6862   }
6863
6864   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6865     // Shuffling low element of v1 into undef, just return v1.
6866     if (V2IsUndef)
6867       return V1;
6868     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6869     // the instruction selector will not match, so get a canonical MOVL with
6870     // swapped operands to undo the commute.
6871     return getMOVL(DAG, dl, VT, V2, V1);
6872   }
6873
6874   if (isUNPCKLMask(M, VT, HasAVX2))
6875     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6876
6877   if (isUNPCKHMask(M, VT, HasAVX2))
6878     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6879
6880   if (V2IsSplat) {
6881     // Normalize mask so all entries that point to V2 points to its first
6882     // element then try to match unpck{h|l} again. If match, return a
6883     // new vector_shuffle with the corrected mask.p
6884     SmallVector<int, 8> NewMask(M.begin(), M.end());
6885     NormalizeMask(NewMask, NumElems);
6886     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6887       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6888     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6889       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6890   }
6891
6892   if (Commuted) {
6893     // Commute is back and try unpck* again.
6894     // FIXME: this seems wrong.
6895     CommuteVectorShuffleMask(M, NumElems);
6896     std::swap(V1, V2);
6897     std::swap(V1IsSplat, V2IsSplat);
6898     Commuted = false;
6899
6900     if (isUNPCKLMask(M, VT, HasAVX2))
6901       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6902
6903     if (isUNPCKHMask(M, VT, HasAVX2))
6904       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6905   }
6906
6907   // Normalize the node to match x86 shuffle ops if needed
6908   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6909     return CommuteVectorShuffle(SVOp, DAG);
6910
6911   // The checks below are all present in isShuffleMaskLegal, but they are
6912   // inlined here right now to enable us to directly emit target specific
6913   // nodes, and remove one by one until they don't return Op anymore.
6914
6915   if (isPALIGNRMask(M, VT, Subtarget))
6916     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6917                                 getShufflePALIGNRImmediate(SVOp),
6918                                 DAG);
6919
6920   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6921       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6922     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6923       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6924   }
6925
6926   if (isPSHUFHWMask(M, VT, HasAVX2))
6927     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6928                                 getShufflePSHUFHWImmediate(SVOp),
6929                                 DAG);
6930
6931   if (isPSHUFLWMask(M, VT, HasAVX2))
6932     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6933                                 getShufflePSHUFLWImmediate(SVOp),
6934                                 DAG);
6935
6936   if (isSHUFPMask(M, VT, HasAVX))
6937     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6938                                 getShuffleSHUFImmediate(SVOp), DAG);
6939
6940   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6941     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6942   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6943     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6944
6945   //===--------------------------------------------------------------------===//
6946   // Generate target specific nodes for 128 or 256-bit shuffles only
6947   // supported in the AVX instruction set.
6948   //
6949
6950   // Handle VMOVDDUPY permutations
6951   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6952     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6953
6954   // Handle VPERMILPS/D* permutations
6955   if (isVPERMILPMask(M, VT, HasAVX)) {
6956     if (HasAVX2 && VT == MVT::v8i32)
6957       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6958                                   getShuffleSHUFImmediate(SVOp), DAG);
6959     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6960                                 getShuffleSHUFImmediate(SVOp), DAG);
6961   }
6962
6963   // Handle VPERM2F128/VPERM2I128 permutations
6964   if (isVPERM2X128Mask(M, VT, HasAVX))
6965     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6966                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6967
6968   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6969   if (BlendOp.getNode())
6970     return BlendOp;
6971
6972   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6973     SmallVector<SDValue, 8> permclMask;
6974     for (unsigned i = 0; i != 8; ++i) {
6975       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6976     }
6977     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6978                                &permclMask[0], 8);
6979     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6980     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6981                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6982   }
6983
6984   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6985     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6986                                 getShuffleCLImmediate(SVOp), DAG);
6987
6988
6989   //===--------------------------------------------------------------------===//
6990   // Since no target specific shuffle was selected for this generic one,
6991   // lower it into other known shuffles. FIXME: this isn't true yet, but
6992   // this is the plan.
6993   //
6994
6995   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6996   if (VT == MVT::v8i16) {
6997     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6998     if (NewOp.getNode())
6999       return NewOp;
7000   }
7001
7002   if (VT == MVT::v16i8) {
7003     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7004     if (NewOp.getNode())
7005       return NewOp;
7006   }
7007
7008   if (VT == MVT::v32i8) {
7009     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7010     if (NewOp.getNode())
7011       return NewOp;
7012   }
7013
7014   // Handle all 128-bit wide vectors with 4 elements, and match them with
7015   // several different shuffle types.
7016   if (NumElems == 4 && VT.is128BitVector())
7017     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7018
7019   // Handle general 256-bit shuffles
7020   if (VT.is256BitVector())
7021     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7022
7023   return SDValue();
7024 }
7025
7026 SDValue
7027 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7028                                                 SelectionDAG &DAG) const {
7029   EVT VT = Op.getValueType();
7030   DebugLoc dl = Op.getDebugLoc();
7031
7032   if (!Op.getOperand(0).getValueType().is128BitVector())
7033     return SDValue();
7034
7035   if (VT.getSizeInBits() == 8) {
7036     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7037                                   Op.getOperand(0), Op.getOperand(1));
7038     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7039                                   DAG.getValueType(VT));
7040     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7041   }
7042
7043   if (VT.getSizeInBits() == 16) {
7044     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7045     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7046     if (Idx == 0)
7047       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7048                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7049                                      DAG.getNode(ISD::BITCAST, dl,
7050                                                  MVT::v4i32,
7051                                                  Op.getOperand(0)),
7052                                      Op.getOperand(1)));
7053     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7054                                   Op.getOperand(0), Op.getOperand(1));
7055     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7056                                   DAG.getValueType(VT));
7057     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7058   }
7059
7060   if (VT == MVT::f32) {
7061     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7062     // the result back to FR32 register. It's only worth matching if the
7063     // result has a single use which is a store or a bitcast to i32.  And in
7064     // the case of a store, it's not worth it if the index is a constant 0,
7065     // because a MOVSSmr can be used instead, which is smaller and faster.
7066     if (!Op.hasOneUse())
7067       return SDValue();
7068     SDNode *User = *Op.getNode()->use_begin();
7069     if ((User->getOpcode() != ISD::STORE ||
7070          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7071           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7072         (User->getOpcode() != ISD::BITCAST ||
7073          User->getValueType(0) != MVT::i32))
7074       return SDValue();
7075     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7076                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7077                                               Op.getOperand(0)),
7078                                               Op.getOperand(1));
7079     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7080   }
7081
7082   if (VT == MVT::i32 || VT == MVT::i64) {
7083     // ExtractPS/pextrq works with constant index.
7084     if (isa<ConstantSDNode>(Op.getOperand(1)))
7085       return Op;
7086   }
7087   return SDValue();
7088 }
7089
7090
7091 SDValue
7092 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7093                                            SelectionDAG &DAG) const {
7094   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7095     return SDValue();
7096
7097   SDValue Vec = Op.getOperand(0);
7098   EVT VecVT = Vec.getValueType();
7099
7100   // If this is a 256-bit vector result, first extract the 128-bit vector and
7101   // then extract the element from the 128-bit vector.
7102   if (VecVT.is256BitVector()) {
7103     DebugLoc dl = Op.getNode()->getDebugLoc();
7104     unsigned NumElems = VecVT.getVectorNumElements();
7105     SDValue Idx = Op.getOperand(1);
7106     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7107
7108     // Get the 128-bit vector.
7109     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7110
7111     if (IdxVal >= NumElems/2)
7112       IdxVal -= NumElems/2;
7113     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7114                        DAG.getConstant(IdxVal, MVT::i32));
7115   }
7116
7117   assert(VecVT.is128BitVector() && "Unexpected vector length");
7118
7119   if (Subtarget->hasSSE41()) {
7120     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7121     if (Res.getNode())
7122       return Res;
7123   }
7124
7125   EVT VT = Op.getValueType();
7126   DebugLoc dl = Op.getDebugLoc();
7127   // TODO: handle v16i8.
7128   if (VT.getSizeInBits() == 16) {
7129     SDValue Vec = Op.getOperand(0);
7130     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7131     if (Idx == 0)
7132       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7133                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7134                                      DAG.getNode(ISD::BITCAST, dl,
7135                                                  MVT::v4i32, Vec),
7136                                      Op.getOperand(1)));
7137     // Transform it so it match pextrw which produces a 32-bit result.
7138     EVT EltVT = MVT::i32;
7139     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7140                                   Op.getOperand(0), Op.getOperand(1));
7141     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7142                                   DAG.getValueType(VT));
7143     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7144   }
7145
7146   if (VT.getSizeInBits() == 32) {
7147     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7148     if (Idx == 0)
7149       return Op;
7150
7151     // SHUFPS the element to the lowest double word, then movss.
7152     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7153     EVT VVT = Op.getOperand(0).getValueType();
7154     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7155                                        DAG.getUNDEF(VVT), Mask);
7156     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7157                        DAG.getIntPtrConstant(0));
7158   }
7159
7160   if (VT.getSizeInBits() == 64) {
7161     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7162     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7163     //        to match extract_elt for f64.
7164     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7165     if (Idx == 0)
7166       return Op;
7167
7168     // UNPCKHPD the element to the lowest double word, then movsd.
7169     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7170     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7171     int Mask[2] = { 1, -1 };
7172     EVT VVT = Op.getOperand(0).getValueType();
7173     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7174                                        DAG.getUNDEF(VVT), Mask);
7175     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7176                        DAG.getIntPtrConstant(0));
7177   }
7178
7179   return SDValue();
7180 }
7181
7182 SDValue
7183 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7184                                                SelectionDAG &DAG) const {
7185   EVT VT = Op.getValueType();
7186   EVT EltVT = VT.getVectorElementType();
7187   DebugLoc dl = Op.getDebugLoc();
7188
7189   SDValue N0 = Op.getOperand(0);
7190   SDValue N1 = Op.getOperand(1);
7191   SDValue N2 = Op.getOperand(2);
7192
7193   if (!VT.is128BitVector())
7194     return SDValue();
7195
7196   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7197       isa<ConstantSDNode>(N2)) {
7198     unsigned Opc;
7199     if (VT == MVT::v8i16)
7200       Opc = X86ISD::PINSRW;
7201     else if (VT == MVT::v16i8)
7202       Opc = X86ISD::PINSRB;
7203     else
7204       Opc = X86ISD::PINSRB;
7205
7206     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7207     // argument.
7208     if (N1.getValueType() != MVT::i32)
7209       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7210     if (N2.getValueType() != MVT::i32)
7211       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7212     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7213   }
7214
7215   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7216     // Bits [7:6] of the constant are the source select.  This will always be
7217     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7218     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7219     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7220     // Bits [5:4] of the constant are the destination select.  This is the
7221     //  value of the incoming immediate.
7222     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7223     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7224     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7225     // Create this as a scalar to vector..
7226     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7227     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7228   }
7229
7230   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7231     // PINSR* works with constant index.
7232     return Op;
7233   }
7234   return SDValue();
7235 }
7236
7237 SDValue
7238 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7239   EVT VT = Op.getValueType();
7240   EVT EltVT = VT.getVectorElementType();
7241
7242   DebugLoc dl = Op.getDebugLoc();
7243   SDValue N0 = Op.getOperand(0);
7244   SDValue N1 = Op.getOperand(1);
7245   SDValue N2 = Op.getOperand(2);
7246
7247   // If this is a 256-bit vector result, first extract the 128-bit vector,
7248   // insert the element into the extracted half and then place it back.
7249   if (VT.is256BitVector()) {
7250     if (!isa<ConstantSDNode>(N2))
7251       return SDValue();
7252
7253     // Get the desired 128-bit vector half.
7254     unsigned NumElems = VT.getVectorNumElements();
7255     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7256     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7257
7258     // Insert the element into the desired half.
7259     bool Upper = IdxVal >= NumElems/2;
7260     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7261                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7262
7263     // Insert the changed part back to the 256-bit vector
7264     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7265   }
7266
7267   if (Subtarget->hasSSE41())
7268     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7269
7270   if (EltVT == MVT::i8)
7271     return SDValue();
7272
7273   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7274     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7275     // as its second argument.
7276     if (N1.getValueType() != MVT::i32)
7277       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7278     if (N2.getValueType() != MVT::i32)
7279       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7280     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7281   }
7282   return SDValue();
7283 }
7284
7285 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7286   LLVMContext *Context = DAG.getContext();
7287   DebugLoc dl = Op.getDebugLoc();
7288   EVT OpVT = Op.getValueType();
7289
7290   // If this is a 256-bit vector result, first insert into a 128-bit
7291   // vector and then insert into the 256-bit vector.
7292   if (!OpVT.is128BitVector()) {
7293     // Insert into a 128-bit vector.
7294     EVT VT128 = EVT::getVectorVT(*Context,
7295                                  OpVT.getVectorElementType(),
7296                                  OpVT.getVectorNumElements() / 2);
7297
7298     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7299
7300     // Insert the 128-bit vector.
7301     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7302   }
7303
7304   if (OpVT == MVT::v1i64 &&
7305       Op.getOperand(0).getValueType() == MVT::i64)
7306     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7307
7308   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7309   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7310   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7311                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7312 }
7313
7314 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7315 // a simple subregister reference or explicit instructions to grab
7316 // upper bits of a vector.
7317 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7318                                       SelectionDAG &DAG) {
7319   if (Subtarget->hasAVX()) {
7320     DebugLoc dl = Op.getNode()->getDebugLoc();
7321     SDValue Vec = Op.getNode()->getOperand(0);
7322     SDValue Idx = Op.getNode()->getOperand(1);
7323
7324     if (Op.getNode()->getValueType(0).is128BitVector() &&
7325         Vec.getNode()->getValueType(0).is256BitVector() &&
7326         isa<ConstantSDNode>(Idx)) {
7327       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7328       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7329     }
7330   }
7331   return SDValue();
7332 }
7333
7334 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7335 // simple superregister reference or explicit instructions to insert
7336 // the upper bits of a vector.
7337 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7338                                      SelectionDAG &DAG) {
7339   if (Subtarget->hasAVX()) {
7340     DebugLoc dl = Op.getNode()->getDebugLoc();
7341     SDValue Vec = Op.getNode()->getOperand(0);
7342     SDValue SubVec = Op.getNode()->getOperand(1);
7343     SDValue Idx = Op.getNode()->getOperand(2);
7344
7345     if (Op.getNode()->getValueType(0).is256BitVector() &&
7346         SubVec.getNode()->getValueType(0).is128BitVector() &&
7347         isa<ConstantSDNode>(Idx)) {
7348       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7349       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7350     }
7351   }
7352   return SDValue();
7353 }
7354
7355 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7356 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7357 // one of the above mentioned nodes. It has to be wrapped because otherwise
7358 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7359 // be used to form addressing mode. These wrapped nodes will be selected
7360 // into MOV32ri.
7361 SDValue
7362 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7363   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7364
7365   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7366   // global base reg.
7367   unsigned char OpFlag = 0;
7368   unsigned WrapperKind = X86ISD::Wrapper;
7369   CodeModel::Model M = getTargetMachine().getCodeModel();
7370
7371   if (Subtarget->isPICStyleRIPRel() &&
7372       (M == CodeModel::Small || M == CodeModel::Kernel))
7373     WrapperKind = X86ISD::WrapperRIP;
7374   else if (Subtarget->isPICStyleGOT())
7375     OpFlag = X86II::MO_GOTOFF;
7376   else if (Subtarget->isPICStyleStubPIC())
7377     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7378
7379   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7380                                              CP->getAlignment(),
7381                                              CP->getOffset(), OpFlag);
7382   DebugLoc DL = CP->getDebugLoc();
7383   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7384   // With PIC, the address is actually $g + Offset.
7385   if (OpFlag) {
7386     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7387                          DAG.getNode(X86ISD::GlobalBaseReg,
7388                                      DebugLoc(), getPointerTy()),
7389                          Result);
7390   }
7391
7392   return Result;
7393 }
7394
7395 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7396   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7397
7398   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7399   // global base reg.
7400   unsigned char OpFlag = 0;
7401   unsigned WrapperKind = X86ISD::Wrapper;
7402   CodeModel::Model M = getTargetMachine().getCodeModel();
7403
7404   if (Subtarget->isPICStyleRIPRel() &&
7405       (M == CodeModel::Small || M == CodeModel::Kernel))
7406     WrapperKind = X86ISD::WrapperRIP;
7407   else if (Subtarget->isPICStyleGOT())
7408     OpFlag = X86II::MO_GOTOFF;
7409   else if (Subtarget->isPICStyleStubPIC())
7410     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7411
7412   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7413                                           OpFlag);
7414   DebugLoc DL = JT->getDebugLoc();
7415   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7416
7417   // With PIC, the address is actually $g + Offset.
7418   if (OpFlag)
7419     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7420                          DAG.getNode(X86ISD::GlobalBaseReg,
7421                                      DebugLoc(), getPointerTy()),
7422                          Result);
7423
7424   return Result;
7425 }
7426
7427 SDValue
7428 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7429   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7430
7431   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7432   // global base reg.
7433   unsigned char OpFlag = 0;
7434   unsigned WrapperKind = X86ISD::Wrapper;
7435   CodeModel::Model M = getTargetMachine().getCodeModel();
7436
7437   if (Subtarget->isPICStyleRIPRel() &&
7438       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7439     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7440       OpFlag = X86II::MO_GOTPCREL;
7441     WrapperKind = X86ISD::WrapperRIP;
7442   } else if (Subtarget->isPICStyleGOT()) {
7443     OpFlag = X86II::MO_GOT;
7444   } else if (Subtarget->isPICStyleStubPIC()) {
7445     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7446   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7447     OpFlag = X86II::MO_DARWIN_NONLAZY;
7448   }
7449
7450   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7451
7452   DebugLoc DL = Op.getDebugLoc();
7453   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7454
7455
7456   // With PIC, the address is actually $g + Offset.
7457   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7458       !Subtarget->is64Bit()) {
7459     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7460                          DAG.getNode(X86ISD::GlobalBaseReg,
7461                                      DebugLoc(), getPointerTy()),
7462                          Result);
7463   }
7464
7465   // For symbols that require a load from a stub to get the address, emit the
7466   // load.
7467   if (isGlobalStubReference(OpFlag))
7468     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7469                          MachinePointerInfo::getGOT(), false, false, false, 0);
7470
7471   return Result;
7472 }
7473
7474 SDValue
7475 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7476   // Create the TargetBlockAddressAddress node.
7477   unsigned char OpFlags =
7478     Subtarget->ClassifyBlockAddressReference();
7479   CodeModel::Model M = getTargetMachine().getCodeModel();
7480   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7481   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7482   DebugLoc dl = Op.getDebugLoc();
7483   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7484                                              OpFlags);
7485
7486   if (Subtarget->isPICStyleRIPRel() &&
7487       (M == CodeModel::Small || M == CodeModel::Kernel))
7488     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7489   else
7490     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7491
7492   // With PIC, the address is actually $g + Offset.
7493   if (isGlobalRelativeToPICBase(OpFlags)) {
7494     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7495                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7496                          Result);
7497   }
7498
7499   return Result;
7500 }
7501
7502 SDValue
7503 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7504                                       int64_t Offset,
7505                                       SelectionDAG &DAG) const {
7506   // Create the TargetGlobalAddress node, folding in the constant
7507   // offset if it is legal.
7508   unsigned char OpFlags =
7509     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7510   CodeModel::Model M = getTargetMachine().getCodeModel();
7511   SDValue Result;
7512   if (OpFlags == X86II::MO_NO_FLAG &&
7513       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7514     // A direct static reference to a global.
7515     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7516     Offset = 0;
7517   } else {
7518     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7519   }
7520
7521   if (Subtarget->isPICStyleRIPRel() &&
7522       (M == CodeModel::Small || M == CodeModel::Kernel))
7523     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7524   else
7525     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7526
7527   // With PIC, the address is actually $g + Offset.
7528   if (isGlobalRelativeToPICBase(OpFlags)) {
7529     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7530                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7531                          Result);
7532   }
7533
7534   // For globals that require a load from a stub to get the address, emit the
7535   // load.
7536   if (isGlobalStubReference(OpFlags))
7537     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7538                          MachinePointerInfo::getGOT(), false, false, false, 0);
7539
7540   // If there was a non-zero offset that we didn't fold, create an explicit
7541   // addition for it.
7542   if (Offset != 0)
7543     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7544                          DAG.getConstant(Offset, getPointerTy()));
7545
7546   return Result;
7547 }
7548
7549 SDValue
7550 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7551   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7552   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7553   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7554 }
7555
7556 static SDValue
7557 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7558            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7559            unsigned char OperandFlags, bool LocalDynamic = false) {
7560   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7561   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7562   DebugLoc dl = GA->getDebugLoc();
7563   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7564                                            GA->getValueType(0),
7565                                            GA->getOffset(),
7566                                            OperandFlags);
7567
7568   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7569                                            : X86ISD::TLSADDR;
7570
7571   if (InFlag) {
7572     SDValue Ops[] = { Chain,  TGA, *InFlag };
7573     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7574   } else {
7575     SDValue Ops[]  = { Chain, TGA };
7576     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7577   }
7578
7579   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7580   MFI->setAdjustsStack(true);
7581
7582   SDValue Flag = Chain.getValue(1);
7583   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7584 }
7585
7586 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7587 static SDValue
7588 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7589                                 const EVT PtrVT) {
7590   SDValue InFlag;
7591   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7592   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7593                                    DAG.getNode(X86ISD::GlobalBaseReg,
7594                                                DebugLoc(), PtrVT), InFlag);
7595   InFlag = Chain.getValue(1);
7596
7597   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7598 }
7599
7600 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7601 static SDValue
7602 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7603                                 const EVT PtrVT) {
7604   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7605                     X86::RAX, X86II::MO_TLSGD);
7606 }
7607
7608 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7609                                            SelectionDAG &DAG,
7610                                            const EVT PtrVT,
7611                                            bool is64Bit) {
7612   DebugLoc dl = GA->getDebugLoc();
7613
7614   // Get the start address of the TLS block for this module.
7615   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7616       .getInfo<X86MachineFunctionInfo>();
7617   MFI->incNumLocalDynamicTLSAccesses();
7618
7619   SDValue Base;
7620   if (is64Bit) {
7621     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7622                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7623   } else {
7624     SDValue InFlag;
7625     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7626         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7627     InFlag = Chain.getValue(1);
7628     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7629                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7630   }
7631
7632   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7633   // of Base.
7634
7635   // Build x@dtpoff.
7636   unsigned char OperandFlags = X86II::MO_DTPOFF;
7637   unsigned WrapperKind = X86ISD::Wrapper;
7638   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7639                                            GA->getValueType(0),
7640                                            GA->getOffset(), OperandFlags);
7641   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7642
7643   // Add x@dtpoff with the base.
7644   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7645 }
7646
7647 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7648 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7649                                    const EVT PtrVT, TLSModel::Model model,
7650                                    bool is64Bit, bool isPIC) {
7651   DebugLoc dl = GA->getDebugLoc();
7652
7653   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7654   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7655                                                          is64Bit ? 257 : 256));
7656
7657   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7658                                       DAG.getIntPtrConstant(0),
7659                                       MachinePointerInfo(Ptr),
7660                                       false, false, false, 0);
7661
7662   unsigned char OperandFlags = 0;
7663   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7664   // initialexec.
7665   unsigned WrapperKind = X86ISD::Wrapper;
7666   if (model == TLSModel::LocalExec) {
7667     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7668   } else if (model == TLSModel::InitialExec) {
7669     if (is64Bit) {
7670       OperandFlags = X86II::MO_GOTTPOFF;
7671       WrapperKind = X86ISD::WrapperRIP;
7672     } else {
7673       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7674     }
7675   } else {
7676     llvm_unreachable("Unexpected model");
7677   }
7678
7679   // emit "addl x@ntpoff,%eax" (local exec)
7680   // or "addl x@indntpoff,%eax" (initial exec)
7681   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7682   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7683                                            GA->getValueType(0),
7684                                            GA->getOffset(), OperandFlags);
7685   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7686
7687   if (model == TLSModel::InitialExec) {
7688     if (isPIC && !is64Bit) {
7689       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7690                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7691                            Offset);
7692     }
7693
7694     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7695                          MachinePointerInfo::getGOT(), false, false, false,
7696                          0);
7697   }
7698
7699   // The address of the thread local variable is the add of the thread
7700   // pointer with the offset of the variable.
7701   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7702 }
7703
7704 SDValue
7705 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7706
7707   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7708   const GlobalValue *GV = GA->getGlobal();
7709
7710   if (Subtarget->isTargetELF()) {
7711     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7712
7713     switch (model) {
7714       case TLSModel::GeneralDynamic:
7715         if (Subtarget->is64Bit())
7716           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7717         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7718       case TLSModel::LocalDynamic:
7719         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7720                                            Subtarget->is64Bit());
7721       case TLSModel::InitialExec:
7722       case TLSModel::LocalExec:
7723         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7724                                    Subtarget->is64Bit(),
7725                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7726     }
7727     llvm_unreachable("Unknown TLS model.");
7728   }
7729
7730   if (Subtarget->isTargetDarwin()) {
7731     // Darwin only has one model of TLS.  Lower to that.
7732     unsigned char OpFlag = 0;
7733     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7734                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7735
7736     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7737     // global base reg.
7738     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7739                   !Subtarget->is64Bit();
7740     if (PIC32)
7741       OpFlag = X86II::MO_TLVP_PIC_BASE;
7742     else
7743       OpFlag = X86II::MO_TLVP;
7744     DebugLoc DL = Op.getDebugLoc();
7745     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7746                                                 GA->getValueType(0),
7747                                                 GA->getOffset(), OpFlag);
7748     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7749
7750     // With PIC32, the address is actually $g + Offset.
7751     if (PIC32)
7752       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7753                            DAG.getNode(X86ISD::GlobalBaseReg,
7754                                        DebugLoc(), getPointerTy()),
7755                            Offset);
7756
7757     // Lowering the machine isd will make sure everything is in the right
7758     // location.
7759     SDValue Chain = DAG.getEntryNode();
7760     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7761     SDValue Args[] = { Chain, Offset };
7762     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7763
7764     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7765     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7766     MFI->setAdjustsStack(true);
7767
7768     // And our return value (tls address) is in the standard call return value
7769     // location.
7770     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7771     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7772                               Chain.getValue(1));
7773   }
7774
7775   if (Subtarget->isTargetWindows()) {
7776     // Just use the implicit TLS architecture
7777     // Need to generate someting similar to:
7778     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7779     //                                  ; from TEB
7780     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7781     //   mov     rcx, qword [rdx+rcx*8]
7782     //   mov     eax, .tls$:tlsvar
7783     //   [rax+rcx] contains the address
7784     // Windows 64bit: gs:0x58
7785     // Windows 32bit: fs:__tls_array
7786
7787     // If GV is an alias then use the aliasee for determining
7788     // thread-localness.
7789     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7790       GV = GA->resolveAliasedGlobal(false);
7791     DebugLoc dl = GA->getDebugLoc();
7792     SDValue Chain = DAG.getEntryNode();
7793
7794     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7795     // %gs:0x58 (64-bit).
7796     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7797                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7798                                                              256)
7799                                         : Type::getInt32PtrTy(*DAG.getContext(),
7800                                                               257));
7801
7802     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7803                                         Subtarget->is64Bit()
7804                                         ? DAG.getIntPtrConstant(0x58)
7805                                         : DAG.getExternalSymbol("_tls_array",
7806                                                                 getPointerTy()),
7807                                         MachinePointerInfo(Ptr),
7808                                         false, false, false, 0);
7809
7810     // Load the _tls_index variable
7811     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7812     if (Subtarget->is64Bit())
7813       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7814                            IDX, MachinePointerInfo(), MVT::i32,
7815                            false, false, 0);
7816     else
7817       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7818                         false, false, false, 0);
7819
7820     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7821                                     getPointerTy());
7822     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7823
7824     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7825     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7826                       false, false, false, 0);
7827
7828     // Get the offset of start of .tls section
7829     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7830                                              GA->getValueType(0),
7831                                              GA->getOffset(), X86II::MO_SECREL);
7832     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7833
7834     // The address of the thread local variable is the add of the thread
7835     // pointer with the offset of the variable.
7836     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7837   }
7838
7839   llvm_unreachable("TLS not implemented for this target.");
7840 }
7841
7842
7843 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7844 /// and take a 2 x i32 value to shift plus a shift amount.
7845 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7846   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7847   EVT VT = Op.getValueType();
7848   unsigned VTBits = VT.getSizeInBits();
7849   DebugLoc dl = Op.getDebugLoc();
7850   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7851   SDValue ShOpLo = Op.getOperand(0);
7852   SDValue ShOpHi = Op.getOperand(1);
7853   SDValue ShAmt  = Op.getOperand(2);
7854   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7855                                      DAG.getConstant(VTBits - 1, MVT::i8))
7856                        : DAG.getConstant(0, VT);
7857
7858   SDValue Tmp2, Tmp3;
7859   if (Op.getOpcode() == ISD::SHL_PARTS) {
7860     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7861     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7862   } else {
7863     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7864     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7865   }
7866
7867   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7868                                 DAG.getConstant(VTBits, MVT::i8));
7869   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7870                              AndNode, DAG.getConstant(0, MVT::i8));
7871
7872   SDValue Hi, Lo;
7873   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7874   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7875   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7876
7877   if (Op.getOpcode() == ISD::SHL_PARTS) {
7878     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7879     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7880   } else {
7881     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7882     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7883   }
7884
7885   SDValue Ops[2] = { Lo, Hi };
7886   return DAG.getMergeValues(Ops, 2, dl);
7887 }
7888
7889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7890                                            SelectionDAG &DAG) const {
7891   EVT SrcVT = Op.getOperand(0).getValueType();
7892
7893   if (SrcVT.isVector())
7894     return SDValue();
7895
7896   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7897          "Unknown SINT_TO_FP to lower!");
7898
7899   // These are really Legal; return the operand so the caller accepts it as
7900   // Legal.
7901   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7902     return Op;
7903   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7904       Subtarget->is64Bit()) {
7905     return Op;
7906   }
7907
7908   DebugLoc dl = Op.getDebugLoc();
7909   unsigned Size = SrcVT.getSizeInBits()/8;
7910   MachineFunction &MF = DAG.getMachineFunction();
7911   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7912   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7913   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7914                                StackSlot,
7915                                MachinePointerInfo::getFixedStack(SSFI),
7916                                false, false, 0);
7917   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7918 }
7919
7920 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7921                                      SDValue StackSlot,
7922                                      SelectionDAG &DAG) const {
7923   // Build the FILD
7924   DebugLoc DL = Op.getDebugLoc();
7925   SDVTList Tys;
7926   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7927   if (useSSE)
7928     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7929   else
7930     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7931
7932   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7933
7934   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7935   MachineMemOperand *MMO;
7936   if (FI) {
7937     int SSFI = FI->getIndex();
7938     MMO =
7939       DAG.getMachineFunction()
7940       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7941                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7942   } else {
7943     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7944     StackSlot = StackSlot.getOperand(1);
7945   }
7946   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7947   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7948                                            X86ISD::FILD, DL,
7949                                            Tys, Ops, array_lengthof(Ops),
7950                                            SrcVT, MMO);
7951
7952   if (useSSE) {
7953     Chain = Result.getValue(1);
7954     SDValue InFlag = Result.getValue(2);
7955
7956     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7957     // shouldn't be necessary except that RFP cannot be live across
7958     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7959     MachineFunction &MF = DAG.getMachineFunction();
7960     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7961     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7962     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963     Tys = DAG.getVTList(MVT::Other);
7964     SDValue Ops[] = {
7965       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7966     };
7967     MachineMemOperand *MMO =
7968       DAG.getMachineFunction()
7969       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7971
7972     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7973                                     Ops, array_lengthof(Ops),
7974                                     Op.getValueType(), MMO);
7975     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7976                          MachinePointerInfo::getFixedStack(SSFI),
7977                          false, false, false, 0);
7978   }
7979
7980   return Result;
7981 }
7982
7983 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7984 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7985                                                SelectionDAG &DAG) const {
7986   // This algorithm is not obvious. Here it is what we're trying to output:
7987   /*
7988      movq       %rax,  %xmm0
7989      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7990      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7991      #ifdef __SSE3__
7992        haddpd   %xmm0, %xmm0
7993      #else
7994        pshufd   $0x4e, %xmm0, %xmm1
7995        addpd    %xmm1, %xmm0
7996      #endif
7997   */
7998
7999   DebugLoc dl = Op.getDebugLoc();
8000   LLVMContext *Context = DAG.getContext();
8001
8002   // Build some magic constants.
8003   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8004   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8005   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8006
8007   SmallVector<Constant*,2> CV1;
8008   CV1.push_back(
8009         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8010   CV1.push_back(
8011         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8012   Constant *C1 = ConstantVector::get(CV1);
8013   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8014
8015   // Load the 64-bit value into an XMM register.
8016   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8017                             Op.getOperand(0));
8018   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8019                               MachinePointerInfo::getConstantPool(),
8020                               false, false, false, 16);
8021   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8022                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8023                               CLod0);
8024
8025   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8026                               MachinePointerInfo::getConstantPool(),
8027                               false, false, false, 16);
8028   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8029   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8030   SDValue Result;
8031
8032   if (Subtarget->hasSSE3()) {
8033     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8034     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8035   } else {
8036     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8037     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8038                                            S2F, 0x4E, DAG);
8039     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8040                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8041                          Sub);
8042   }
8043
8044   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8045                      DAG.getIntPtrConstant(0));
8046 }
8047
8048 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8049 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8050                                                SelectionDAG &DAG) const {
8051   DebugLoc dl = Op.getDebugLoc();
8052   // FP constant to bias correct the final result.
8053   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8054                                    MVT::f64);
8055
8056   // Load the 32-bit value into an XMM register.
8057   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8058                              Op.getOperand(0));
8059
8060   // Zero out the upper parts of the register.
8061   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8062
8063   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8064                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8065                      DAG.getIntPtrConstant(0));
8066
8067   // Or the load with the bias.
8068   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8069                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8070                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8071                                                    MVT::v2f64, Load)),
8072                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8073                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8074                                                    MVT::v2f64, Bias)));
8075   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8077                    DAG.getIntPtrConstant(0));
8078
8079   // Subtract the bias.
8080   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8081
8082   // Handle final rounding.
8083   EVT DestVT = Op.getValueType();
8084
8085   if (DestVT.bitsLT(MVT::f64))
8086     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8087                        DAG.getIntPtrConstant(0));
8088   if (DestVT.bitsGT(MVT::f64))
8089     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8090
8091   // Handle final rounding.
8092   return Sub;
8093 }
8094
8095 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8096                                                SelectionDAG &DAG) const {
8097   SDValue N0 = Op.getOperand(0);
8098   EVT SVT = N0.getValueType();
8099   DebugLoc dl = Op.getDebugLoc();
8100
8101   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8102           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8103          "Custom UINT_TO_FP is not supported!");
8104
8105   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8106   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8107                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8108 }
8109
8110 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8111                                            SelectionDAG &DAG) const {
8112   SDValue N0 = Op.getOperand(0);
8113   DebugLoc dl = Op.getDebugLoc();
8114
8115   if (Op.getValueType().isVector())
8116     return lowerUINT_TO_FP_vec(Op, DAG);
8117
8118   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8119   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8120   // the optimization here.
8121   if (DAG.SignBitIsZero(N0))
8122     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8123
8124   EVT SrcVT = N0.getValueType();
8125   EVT DstVT = Op.getValueType();
8126   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8127     return LowerUINT_TO_FP_i64(Op, DAG);
8128   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8129     return LowerUINT_TO_FP_i32(Op, DAG);
8130   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8131     return SDValue();
8132
8133   // Make a 64-bit buffer, and use it to build an FILD.
8134   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8135   if (SrcVT == MVT::i32) {
8136     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8137     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8138                                      getPointerTy(), StackSlot, WordOff);
8139     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8140                                   StackSlot, MachinePointerInfo(),
8141                                   false, false, 0);
8142     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8143                                   OffsetSlot, MachinePointerInfo(),
8144                                   false, false, 0);
8145     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8146     return Fild;
8147   }
8148
8149   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8150   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8151                                StackSlot, MachinePointerInfo(),
8152                                false, false, 0);
8153   // For i64 source, we need to add the appropriate power of 2 if the input
8154   // was negative.  This is the same as the optimization in
8155   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8156   // we must be careful to do the computation in x87 extended precision, not
8157   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8158   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8159   MachineMemOperand *MMO =
8160     DAG.getMachineFunction()
8161     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8162                           MachineMemOperand::MOLoad, 8, 8);
8163
8164   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8165   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8166   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8167                                          MVT::i64, MMO);
8168
8169   APInt FF(32, 0x5F800000ULL);
8170
8171   // Check whether the sign bit is set.
8172   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8173                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8174                                  ISD::SETLT);
8175
8176   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8177   SDValue FudgePtr = DAG.getConstantPool(
8178                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8179                                          getPointerTy());
8180
8181   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8182   SDValue Zero = DAG.getIntPtrConstant(0);
8183   SDValue Four = DAG.getIntPtrConstant(4);
8184   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8185                                Zero, Four);
8186   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8187
8188   // Load the value out, extending it from f32 to f80.
8189   // FIXME: Avoid the extend by constructing the right constant pool?
8190   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8191                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8192                                  MVT::f32, false, false, 4);
8193   // Extend everything to 80 bits to force it to be done on x87.
8194   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8195   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8196 }
8197
8198 std::pair<SDValue,SDValue> X86TargetLowering::
8199 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8200   DebugLoc DL = Op.getDebugLoc();
8201
8202   EVT DstTy = Op.getValueType();
8203
8204   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8205     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8206     DstTy = MVT::i64;
8207   }
8208
8209   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8210          DstTy.getSimpleVT() >= MVT::i16 &&
8211          "Unknown FP_TO_INT to lower!");
8212
8213   // These are really Legal.
8214   if (DstTy == MVT::i32 &&
8215       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8216     return std::make_pair(SDValue(), SDValue());
8217   if (Subtarget->is64Bit() &&
8218       DstTy == MVT::i64 &&
8219       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8220     return std::make_pair(SDValue(), SDValue());
8221
8222   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8223   // stack slot, or into the FTOL runtime function.
8224   MachineFunction &MF = DAG.getMachineFunction();
8225   unsigned MemSize = DstTy.getSizeInBits()/8;
8226   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8227   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8228
8229   unsigned Opc;
8230   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8231     Opc = X86ISD::WIN_FTOL;
8232   else
8233     switch (DstTy.getSimpleVT().SimpleTy) {
8234     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8235     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8236     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8237     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8238     }
8239
8240   SDValue Chain = DAG.getEntryNode();
8241   SDValue Value = Op.getOperand(0);
8242   EVT TheVT = Op.getOperand(0).getValueType();
8243   // FIXME This causes a redundant load/store if the SSE-class value is already
8244   // in memory, such as if it is on the callstack.
8245   if (isScalarFPTypeInSSEReg(TheVT)) {
8246     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8247     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8248                          MachinePointerInfo::getFixedStack(SSFI),
8249                          false, false, 0);
8250     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8251     SDValue Ops[] = {
8252       Chain, StackSlot, DAG.getValueType(TheVT)
8253     };
8254
8255     MachineMemOperand *MMO =
8256       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8257                               MachineMemOperand::MOLoad, MemSize, MemSize);
8258     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8259                                     DstTy, MMO);
8260     Chain = Value.getValue(1);
8261     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8262     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8263   }
8264
8265   MachineMemOperand *MMO =
8266     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8267                             MachineMemOperand::MOStore, MemSize, MemSize);
8268
8269   if (Opc != X86ISD::WIN_FTOL) {
8270     // Build the FP_TO_INT*_IN_MEM
8271     SDValue Ops[] = { Chain, Value, StackSlot };
8272     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8273                                            Ops, 3, DstTy, MMO);
8274     return std::make_pair(FIST, StackSlot);
8275   } else {
8276     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8277       DAG.getVTList(MVT::Other, MVT::Glue),
8278       Chain, Value);
8279     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8280       MVT::i32, ftol.getValue(1));
8281     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8282       MVT::i32, eax.getValue(2));
8283     SDValue Ops[] = { eax, edx };
8284     SDValue pair = IsReplace
8285       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8286       : DAG.getMergeValues(Ops, 2, DL);
8287     return std::make_pair(pair, SDValue());
8288   }
8289 }
8290
8291 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8292   DebugLoc DL = Op.getDebugLoc();
8293   EVT VT = Op.getValueType();
8294   SDValue In = Op.getOperand(0);
8295   EVT SVT = In.getValueType();
8296
8297   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8298       VT.getVectorNumElements() != SVT.getVectorNumElements())
8299     return SDValue();
8300
8301   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8302
8303   // AVX2 has better support of integer extending.
8304   if (Subtarget->hasAVX2())
8305     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8306
8307   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8308   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8309   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8310                            DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8311
8312   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8313 }
8314
8315 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8316   DebugLoc DL = Op.getDebugLoc();
8317   EVT VT = Op.getValueType();
8318   EVT SVT = Op.getOperand(0).getValueType();
8319
8320   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8321       VT.getVectorNumElements() != SVT.getVectorNumElements())
8322     return SDValue();
8323
8324   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8325
8326   unsigned NumElems = VT.getVectorNumElements();
8327   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8328                              NumElems * 2);
8329
8330   SDValue In = Op.getOperand(0);
8331   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8332   // Prepare truncation shuffle mask
8333   for (unsigned i = 0; i != NumElems; ++i)
8334     MaskVec[i] = i * 2;
8335   SDValue V = DAG.getVectorShuffle(NVT, DL,
8336                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8337                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8338   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8339                      DAG.getIntPtrConstant(0));
8340 }
8341
8342 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8343                                            SelectionDAG &DAG) const {
8344   if (Op.getValueType().isVector()) {
8345     if (Op.getValueType() == MVT::v8i16)
8346       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8347                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8348                                      MVT::v8i32, Op.getOperand(0)));
8349     return SDValue();
8350   }
8351
8352   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8353     /*IsSigned=*/ true, /*IsReplace=*/ false);
8354   SDValue FIST = Vals.first, StackSlot = Vals.second;
8355   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8356   if (FIST.getNode() == 0) return Op;
8357
8358   if (StackSlot.getNode())
8359     // Load the result.
8360     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8361                        FIST, StackSlot, MachinePointerInfo(),
8362                        false, false, false, 0);
8363
8364   // The node is the result.
8365   return FIST;
8366 }
8367
8368 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8369                                            SelectionDAG &DAG) const {
8370   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8371     /*IsSigned=*/ false, /*IsReplace=*/ false);
8372   SDValue FIST = Vals.first, StackSlot = Vals.second;
8373   assert(FIST.getNode() && "Unexpected failure");
8374
8375   if (StackSlot.getNode())
8376     // Load the result.
8377     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8378                        FIST, StackSlot, MachinePointerInfo(),
8379                        false, false, false, 0);
8380
8381   // The node is the result.
8382   return FIST;
8383 }
8384
8385 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8386                                           SelectionDAG &DAG) const {
8387   DebugLoc DL = Op.getDebugLoc();
8388   EVT VT = Op.getValueType();
8389   SDValue In = Op.getOperand(0);
8390   EVT SVT = In.getValueType();
8391
8392   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8393
8394   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8395                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8396                                  In, DAG.getUNDEF(SVT)));
8397 }
8398
8399 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8400   LLVMContext *Context = DAG.getContext();
8401   DebugLoc dl = Op.getDebugLoc();
8402   EVT VT = Op.getValueType();
8403   EVT EltVT = VT;
8404   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8405   if (VT.isVector()) {
8406     EltVT = VT.getVectorElementType();
8407     NumElts = VT.getVectorNumElements();
8408   }
8409   Constant *C;
8410   if (EltVT == MVT::f64)
8411     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8412   else
8413     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8414   C = ConstantVector::getSplat(NumElts, C);
8415   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8416   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8417   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8418                              MachinePointerInfo::getConstantPool(),
8419                              false, false, false, Alignment);
8420   if (VT.isVector()) {
8421     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8422     return DAG.getNode(ISD::BITCAST, dl, VT,
8423                        DAG.getNode(ISD::AND, dl, ANDVT,
8424                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8425                                                Op.getOperand(0)),
8426                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8427   }
8428   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8429 }
8430
8431 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8432   LLVMContext *Context = DAG.getContext();
8433   DebugLoc dl = Op.getDebugLoc();
8434   EVT VT = Op.getValueType();
8435   EVT EltVT = VT;
8436   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8437   if (VT.isVector()) {
8438     EltVT = VT.getVectorElementType();
8439     NumElts = VT.getVectorNumElements();
8440   }
8441   Constant *C;
8442   if (EltVT == MVT::f64)
8443     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8444   else
8445     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8446   C = ConstantVector::getSplat(NumElts, C);
8447   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8448   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8449   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8450                              MachinePointerInfo::getConstantPool(),
8451                              false, false, false, Alignment);
8452   if (VT.isVector()) {
8453     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8454     return DAG.getNode(ISD::BITCAST, dl, VT,
8455                        DAG.getNode(ISD::XOR, dl, XORVT,
8456                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8457                                                Op.getOperand(0)),
8458                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8459   }
8460
8461   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8462 }
8463
8464 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8465   LLVMContext *Context = DAG.getContext();
8466   SDValue Op0 = Op.getOperand(0);
8467   SDValue Op1 = Op.getOperand(1);
8468   DebugLoc dl = Op.getDebugLoc();
8469   EVT VT = Op.getValueType();
8470   EVT SrcVT = Op1.getValueType();
8471
8472   // If second operand is smaller, extend it first.
8473   if (SrcVT.bitsLT(VT)) {
8474     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8475     SrcVT = VT;
8476   }
8477   // And if it is bigger, shrink it first.
8478   if (SrcVT.bitsGT(VT)) {
8479     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8480     SrcVT = VT;
8481   }
8482
8483   // At this point the operands and the result should have the same
8484   // type, and that won't be f80 since that is not custom lowered.
8485
8486   // First get the sign bit of second operand.
8487   SmallVector<Constant*,4> CV;
8488   if (SrcVT == MVT::f64) {
8489     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8490     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8491   } else {
8492     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8493     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8494     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8495     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8496   }
8497   Constant *C = ConstantVector::get(CV);
8498   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8499   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8500                               MachinePointerInfo::getConstantPool(),
8501                               false, false, false, 16);
8502   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8503
8504   // Shift sign bit right or left if the two operands have different types.
8505   if (SrcVT.bitsGT(VT)) {
8506     // Op0 is MVT::f32, Op1 is MVT::f64.
8507     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8508     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8509                           DAG.getConstant(32, MVT::i32));
8510     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8511     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8512                           DAG.getIntPtrConstant(0));
8513   }
8514
8515   // Clear first operand sign bit.
8516   CV.clear();
8517   if (VT == MVT::f64) {
8518     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8519     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8520   } else {
8521     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8522     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8523     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8524     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8525   }
8526   C = ConstantVector::get(CV);
8527   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8528   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8529                               MachinePointerInfo::getConstantPool(),
8530                               false, false, false, 16);
8531   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8532
8533   // Or the value with the sign bit.
8534   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8535 }
8536
8537 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8538   SDValue N0 = Op.getOperand(0);
8539   DebugLoc dl = Op.getDebugLoc();
8540   EVT VT = Op.getValueType();
8541
8542   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8543   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8544                                   DAG.getConstant(1, VT));
8545   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8546 }
8547
8548 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8549 //
8550 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8551   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8552
8553   if (!Subtarget->hasSSE41())
8554     return SDValue();
8555
8556   if (!Op->hasOneUse())
8557     return SDValue();
8558
8559   SDNode *N = Op.getNode();
8560   DebugLoc DL = N->getDebugLoc();
8561
8562   SmallVector<SDValue, 8> Opnds;
8563   DenseMap<SDValue, unsigned> VecInMap;
8564   EVT VT = MVT::Other;
8565
8566   // Recognize a special case where a vector is casted into wide integer to
8567   // test all 0s.
8568   Opnds.push_back(N->getOperand(0));
8569   Opnds.push_back(N->getOperand(1));
8570
8571   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8572     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8573     // BFS traverse all OR'd operands.
8574     if (I->getOpcode() == ISD::OR) {
8575       Opnds.push_back(I->getOperand(0));
8576       Opnds.push_back(I->getOperand(1));
8577       // Re-evaluate the number of nodes to be traversed.
8578       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8579       continue;
8580     }
8581
8582     // Quit if a non-EXTRACT_VECTOR_ELT
8583     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8584       return SDValue();
8585
8586     // Quit if without a constant index.
8587     SDValue Idx = I->getOperand(1);
8588     if (!isa<ConstantSDNode>(Idx))
8589       return SDValue();
8590
8591     SDValue ExtractedFromVec = I->getOperand(0);
8592     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8593     if (M == VecInMap.end()) {
8594       VT = ExtractedFromVec.getValueType();
8595       // Quit if not 128/256-bit vector.
8596       if (!VT.is128BitVector() && !VT.is256BitVector())
8597         return SDValue();
8598       // Quit if not the same type.
8599       if (VecInMap.begin() != VecInMap.end() &&
8600           VT != VecInMap.begin()->first.getValueType())
8601         return SDValue();
8602       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8603     }
8604     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8605   }
8606
8607   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8608          "Not extracted from 128-/256-bit vector.");
8609
8610   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8611   SmallVector<SDValue, 8> VecIns;
8612
8613   for (DenseMap<SDValue, unsigned>::const_iterator
8614         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8615     // Quit if not all elements are used.
8616     if (I->second != FullMask)
8617       return SDValue();
8618     VecIns.push_back(I->first);
8619   }
8620
8621   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8622
8623   // Cast all vectors into TestVT for PTEST.
8624   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8625     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8626
8627   // If more than one full vectors are evaluated, OR them first before PTEST.
8628   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8629     // Each iteration will OR 2 nodes and append the result until there is only
8630     // 1 node left, i.e. the final OR'd value of all vectors.
8631     SDValue LHS = VecIns[Slot];
8632     SDValue RHS = VecIns[Slot + 1];
8633     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8634   }
8635
8636   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8637                      VecIns.back(), VecIns.back());
8638 }
8639
8640 /// Emit nodes that will be selected as "test Op0,Op0", or something
8641 /// equivalent.
8642 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8643                                     SelectionDAG &DAG) const {
8644   DebugLoc dl = Op.getDebugLoc();
8645
8646   // CF and OF aren't always set the way we want. Determine which
8647   // of these we need.
8648   bool NeedCF = false;
8649   bool NeedOF = false;
8650   switch (X86CC) {
8651   default: break;
8652   case X86::COND_A: case X86::COND_AE:
8653   case X86::COND_B: case X86::COND_BE:
8654     NeedCF = true;
8655     break;
8656   case X86::COND_G: case X86::COND_GE:
8657   case X86::COND_L: case X86::COND_LE:
8658   case X86::COND_O: case X86::COND_NO:
8659     NeedOF = true;
8660     break;
8661   }
8662
8663   // See if we can use the EFLAGS value from the operand instead of
8664   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8665   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8666   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8667     // Emit a CMP with 0, which is the TEST pattern.
8668     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8669                        DAG.getConstant(0, Op.getValueType()));
8670
8671   unsigned Opcode = 0;
8672   unsigned NumOperands = 0;
8673
8674   // Truncate operations may prevent the merge of the SETCC instruction
8675   // and the arithmetic intruction before it. Attempt to truncate the operands
8676   // of the arithmetic instruction and use a reduced bit-width instruction.
8677   bool NeedTruncation = false;
8678   SDValue ArithOp = Op;
8679   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8680     SDValue Arith = Op->getOperand(0);
8681     // Both the trunc and the arithmetic op need to have one user each.
8682     if (Arith->hasOneUse())
8683       switch (Arith.getOpcode()) {
8684         default: break;
8685         case ISD::ADD:
8686         case ISD::SUB:
8687         case ISD::AND:
8688         case ISD::OR:
8689         case ISD::XOR: {
8690           NeedTruncation = true;
8691           ArithOp = Arith;
8692         }
8693       }
8694   }
8695
8696   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8697   // which may be the result of a CAST.  We use the variable 'Op', which is the
8698   // non-casted variable when we check for possible users.
8699   switch (ArithOp.getOpcode()) {
8700   case ISD::ADD:
8701     // Due to an isel shortcoming, be conservative if this add is likely to be
8702     // selected as part of a load-modify-store instruction. When the root node
8703     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8704     // uses of other nodes in the match, such as the ADD in this case. This
8705     // leads to the ADD being left around and reselected, with the result being
8706     // two adds in the output.  Alas, even if none our users are stores, that
8707     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8708     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8709     // climbing the DAG back to the root, and it doesn't seem to be worth the
8710     // effort.
8711     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8712          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8713       if (UI->getOpcode() != ISD::CopyToReg &&
8714           UI->getOpcode() != ISD::SETCC &&
8715           UI->getOpcode() != ISD::STORE)
8716         goto default_case;
8717
8718     if (ConstantSDNode *C =
8719         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8720       // An add of one will be selected as an INC.
8721       if (C->getAPIntValue() == 1) {
8722         Opcode = X86ISD::INC;
8723         NumOperands = 1;
8724         break;
8725       }
8726
8727       // An add of negative one (subtract of one) will be selected as a DEC.
8728       if (C->getAPIntValue().isAllOnesValue()) {
8729         Opcode = X86ISD::DEC;
8730         NumOperands = 1;
8731         break;
8732       }
8733     }
8734
8735     // Otherwise use a regular EFLAGS-setting add.
8736     Opcode = X86ISD::ADD;
8737     NumOperands = 2;
8738     break;
8739   case ISD::AND: {
8740     // If the primary and result isn't used, don't bother using X86ISD::AND,
8741     // because a TEST instruction will be better.
8742     bool NonFlagUse = false;
8743     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8744            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8745       SDNode *User = *UI;
8746       unsigned UOpNo = UI.getOperandNo();
8747       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8748         // Look pass truncate.
8749         UOpNo = User->use_begin().getOperandNo();
8750         User = *User->use_begin();
8751       }
8752
8753       if (User->getOpcode() != ISD::BRCOND &&
8754           User->getOpcode() != ISD::SETCC &&
8755           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8756         NonFlagUse = true;
8757         break;
8758       }
8759     }
8760
8761     if (!NonFlagUse)
8762       break;
8763   }
8764     // FALL THROUGH
8765   case ISD::SUB:
8766   case ISD::OR:
8767   case ISD::XOR:
8768     // Due to the ISEL shortcoming noted above, be conservative if this op is
8769     // likely to be selected as part of a load-modify-store instruction.
8770     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8771            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8772       if (UI->getOpcode() == ISD::STORE)
8773         goto default_case;
8774
8775     // Otherwise use a regular EFLAGS-setting instruction.
8776     switch (ArithOp.getOpcode()) {
8777     default: llvm_unreachable("unexpected operator!");
8778     case ISD::SUB: Opcode = X86ISD::SUB; break;
8779     case ISD::XOR: Opcode = X86ISD::XOR; break;
8780     case ISD::AND: Opcode = X86ISD::AND; break;
8781     case ISD::OR: {
8782       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8783         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8784         if (EFLAGS.getNode())
8785           return EFLAGS;
8786       }
8787       Opcode = X86ISD::OR;
8788       break;
8789     }
8790     }
8791
8792     NumOperands = 2;
8793     break;
8794   case X86ISD::ADD:
8795   case X86ISD::SUB:
8796   case X86ISD::INC:
8797   case X86ISD::DEC:
8798   case X86ISD::OR:
8799   case X86ISD::XOR:
8800   case X86ISD::AND:
8801     return SDValue(Op.getNode(), 1);
8802   default:
8803   default_case:
8804     break;
8805   }
8806
8807   // If we found that truncation is beneficial, perform the truncation and
8808   // update 'Op'.
8809   if (NeedTruncation) {
8810     EVT VT = Op.getValueType();
8811     SDValue WideVal = Op->getOperand(0);
8812     EVT WideVT = WideVal.getValueType();
8813     unsigned ConvertedOp = 0;
8814     // Use a target machine opcode to prevent further DAGCombine
8815     // optimizations that may separate the arithmetic operations
8816     // from the setcc node.
8817     switch (WideVal.getOpcode()) {
8818       default: break;
8819       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8820       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8821       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8822       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8823       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8824     }
8825
8826     if (ConvertedOp) {
8827       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8828       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8829         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8830         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8831         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8832       }
8833     }
8834   }
8835
8836   if (Opcode == 0)
8837     // Emit a CMP with 0, which is the TEST pattern.
8838     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8839                        DAG.getConstant(0, Op.getValueType()));
8840
8841   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8842   SmallVector<SDValue, 4> Ops;
8843   for (unsigned i = 0; i != NumOperands; ++i)
8844     Ops.push_back(Op.getOperand(i));
8845
8846   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8847   DAG.ReplaceAllUsesWith(Op, New);
8848   return SDValue(New.getNode(), 1);
8849 }
8850
8851 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8852 /// equivalent.
8853 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8854                                    SelectionDAG &DAG) const {
8855   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8856     if (C->getAPIntValue() == 0)
8857       return EmitTest(Op0, X86CC, DAG);
8858
8859   DebugLoc dl = Op0.getDebugLoc();
8860   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8861        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8862     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8863     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8864     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8865                               Op0, Op1);
8866     return SDValue(Sub.getNode(), 1);
8867   }
8868   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8869 }
8870
8871 /// Convert a comparison if required by the subtarget.
8872 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8873                                                  SelectionDAG &DAG) const {
8874   // If the subtarget does not support the FUCOMI instruction, floating-point
8875   // comparisons have to be converted.
8876   if (Subtarget->hasCMov() ||
8877       Cmp.getOpcode() != X86ISD::CMP ||
8878       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8879       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8880     return Cmp;
8881
8882   // The instruction selector will select an FUCOM instruction instead of
8883   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8884   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8885   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8886   DebugLoc dl = Cmp.getDebugLoc();
8887   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8888   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8889   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8890                             DAG.getConstant(8, MVT::i8));
8891   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8892   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8893 }
8894
8895 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8896 /// if it's possible.
8897 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8898                                      DebugLoc dl, SelectionDAG &DAG) const {
8899   SDValue Op0 = And.getOperand(0);
8900   SDValue Op1 = And.getOperand(1);
8901   if (Op0.getOpcode() == ISD::TRUNCATE)
8902     Op0 = Op0.getOperand(0);
8903   if (Op1.getOpcode() == ISD::TRUNCATE)
8904     Op1 = Op1.getOperand(0);
8905
8906   SDValue LHS, RHS;
8907   if (Op1.getOpcode() == ISD::SHL)
8908     std::swap(Op0, Op1);
8909   if (Op0.getOpcode() == ISD::SHL) {
8910     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8911       if (And00C->getZExtValue() == 1) {
8912         // If we looked past a truncate, check that it's only truncating away
8913         // known zeros.
8914         unsigned BitWidth = Op0.getValueSizeInBits();
8915         unsigned AndBitWidth = And.getValueSizeInBits();
8916         if (BitWidth > AndBitWidth) {
8917           APInt Zeros, Ones;
8918           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8919           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8920             return SDValue();
8921         }
8922         LHS = Op1;
8923         RHS = Op0.getOperand(1);
8924       }
8925   } else if (Op1.getOpcode() == ISD::Constant) {
8926     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8927     uint64_t AndRHSVal = AndRHS->getZExtValue();
8928     SDValue AndLHS = Op0;
8929
8930     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8931       LHS = AndLHS.getOperand(0);
8932       RHS = AndLHS.getOperand(1);
8933     }
8934
8935     // Use BT if the immediate can't be encoded in a TEST instruction.
8936     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8937       LHS = AndLHS;
8938       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8939     }
8940   }
8941
8942   if (LHS.getNode()) {
8943     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8944     // instruction.  Since the shift amount is in-range-or-undefined, we know
8945     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8946     // the encoding for the i16 version is larger than the i32 version.
8947     // Also promote i16 to i32 for performance / code size reason.
8948     if (LHS.getValueType() == MVT::i8 ||
8949         LHS.getValueType() == MVT::i16)
8950       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8951
8952     // If the operand types disagree, extend the shift amount to match.  Since
8953     // BT ignores high bits (like shifts) we can use anyextend.
8954     if (LHS.getValueType() != RHS.getValueType())
8955       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8956
8957     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8958     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8959     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8960                        DAG.getConstant(Cond, MVT::i8), BT);
8961   }
8962
8963   return SDValue();
8964 }
8965
8966 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8967
8968   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8969
8970   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8971   SDValue Op0 = Op.getOperand(0);
8972   SDValue Op1 = Op.getOperand(1);
8973   DebugLoc dl = Op.getDebugLoc();
8974   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8975
8976   // Optimize to BT if possible.
8977   // Lower (X & (1 << N)) == 0 to BT(X, N).
8978   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8979   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8980   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8981       Op1.getOpcode() == ISD::Constant &&
8982       cast<ConstantSDNode>(Op1)->isNullValue() &&
8983       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8984     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8985     if (NewSetCC.getNode())
8986       return NewSetCC;
8987   }
8988
8989   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8990   // these.
8991   if (Op1.getOpcode() == ISD::Constant &&
8992       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8993        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8994       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8995
8996     // If the input is a setcc, then reuse the input setcc or use a new one with
8997     // the inverted condition.
8998     if (Op0.getOpcode() == X86ISD::SETCC) {
8999       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9000       bool Invert = (CC == ISD::SETNE) ^
9001         cast<ConstantSDNode>(Op1)->isNullValue();
9002       if (!Invert) return Op0;
9003
9004       CCode = X86::GetOppositeBranchCondition(CCode);
9005       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9006                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9007     }
9008   }
9009
9010   bool isFP = Op1.getValueType().isFloatingPoint();
9011   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9012   if (X86CC == X86::COND_INVALID)
9013     return SDValue();
9014
9015   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9016   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9017   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9018                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9019 }
9020
9021 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9022 // ones, and then concatenate the result back.
9023 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9024   EVT VT = Op.getValueType();
9025
9026   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9027          "Unsupported value type for operation");
9028
9029   unsigned NumElems = VT.getVectorNumElements();
9030   DebugLoc dl = Op.getDebugLoc();
9031   SDValue CC = Op.getOperand(2);
9032
9033   // Extract the LHS vectors
9034   SDValue LHS = Op.getOperand(0);
9035   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9036   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9037
9038   // Extract the RHS vectors
9039   SDValue RHS = Op.getOperand(1);
9040   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9041   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9042
9043   // Issue the operation on the smaller types and concatenate the result back
9044   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9045   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9046   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9047                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9048                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9049 }
9050
9051
9052 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9053   SDValue Cond;
9054   SDValue Op0 = Op.getOperand(0);
9055   SDValue Op1 = Op.getOperand(1);
9056   SDValue CC = Op.getOperand(2);
9057   EVT VT = Op.getValueType();
9058   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9059   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9060   DebugLoc dl = Op.getDebugLoc();
9061
9062   if (isFP) {
9063 #ifndef NDEBUG
9064     EVT EltVT = Op0.getValueType().getVectorElementType();
9065     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9066 #endif
9067
9068     unsigned SSECC;
9069     bool Swap = false;
9070
9071     // SSE Condition code mapping:
9072     //  0 - EQ
9073     //  1 - LT
9074     //  2 - LE
9075     //  3 - UNORD
9076     //  4 - NEQ
9077     //  5 - NLT
9078     //  6 - NLE
9079     //  7 - ORD
9080     switch (SetCCOpcode) {
9081     default: llvm_unreachable("Unexpected SETCC condition");
9082     case ISD::SETOEQ:
9083     case ISD::SETEQ:  SSECC = 0; break;
9084     case ISD::SETOGT:
9085     case ISD::SETGT: Swap = true; // Fallthrough
9086     case ISD::SETLT:
9087     case ISD::SETOLT: SSECC = 1; break;
9088     case ISD::SETOGE:
9089     case ISD::SETGE: Swap = true; // Fallthrough
9090     case ISD::SETLE:
9091     case ISD::SETOLE: SSECC = 2; break;
9092     case ISD::SETUO:  SSECC = 3; break;
9093     case ISD::SETUNE:
9094     case ISD::SETNE:  SSECC = 4; break;
9095     case ISD::SETULE: Swap = true; // Fallthrough
9096     case ISD::SETUGE: SSECC = 5; break;
9097     case ISD::SETULT: Swap = true; // Fallthrough
9098     case ISD::SETUGT: SSECC = 6; break;
9099     case ISD::SETO:   SSECC = 7; break;
9100     case ISD::SETUEQ:
9101     case ISD::SETONE: SSECC = 8; break;
9102     }
9103     if (Swap)
9104       std::swap(Op0, Op1);
9105
9106     // In the two special cases we can't handle, emit two comparisons.
9107     if (SSECC == 8) {
9108       unsigned CC0, CC1;
9109       unsigned CombineOpc;
9110       if (SetCCOpcode == ISD::SETUEQ) {
9111         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9112       } else {
9113         assert(SetCCOpcode == ISD::SETONE);
9114         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9115       }
9116
9117       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9118                                  DAG.getConstant(CC0, MVT::i8));
9119       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9120                                  DAG.getConstant(CC1, MVT::i8));
9121       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9122     }
9123     // Handle all other FP comparisons here.
9124     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9125                        DAG.getConstant(SSECC, MVT::i8));
9126   }
9127
9128   // Break 256-bit integer vector compare into smaller ones.
9129   if (VT.is256BitVector() && !Subtarget->hasAVX2())
9130     return Lower256IntVSETCC(Op, DAG);
9131
9132   // We are handling one of the integer comparisons here.  Since SSE only has
9133   // GT and EQ comparisons for integer, swapping operands and multiple
9134   // operations may be required for some comparisons.
9135   unsigned Opc;
9136   bool Swap = false, Invert = false, FlipSigns = false;
9137
9138   switch (SetCCOpcode) {
9139   default: llvm_unreachable("Unexpected SETCC condition");
9140   case ISD::SETNE:  Invert = true;
9141   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9142   case ISD::SETLT:  Swap = true;
9143   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9144   case ISD::SETGE:  Swap = true;
9145   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9146   case ISD::SETULT: Swap = true;
9147   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9148   case ISD::SETUGE: Swap = true;
9149   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9150   }
9151   if (Swap)
9152     std::swap(Op0, Op1);
9153
9154   // Check that the operation in question is available (most are plain SSE2,
9155   // but PCMPGTQ and PCMPEQQ have different requirements).
9156   if (VT == MVT::v2i64) {
9157     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9158       return SDValue();
9159     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9160       return SDValue();
9161   }
9162
9163   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9164   // bits of the inputs before performing those operations.
9165   if (FlipSigns) {
9166     EVT EltVT = VT.getVectorElementType();
9167     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9168                                       EltVT);
9169     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9170     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9171                                     SignBits.size());
9172     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9173     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9174   }
9175
9176   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9177
9178   // If the logical-not of the result is required, perform that now.
9179   if (Invert)
9180     Result = DAG.getNOT(dl, Result, VT);
9181
9182   return Result;
9183 }
9184
9185 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9186 static bool isX86LogicalCmp(SDValue Op) {
9187   unsigned Opc = Op.getNode()->getOpcode();
9188   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9189       Opc == X86ISD::SAHF)
9190     return true;
9191   if (Op.getResNo() == 1 &&
9192       (Opc == X86ISD::ADD ||
9193        Opc == X86ISD::SUB ||
9194        Opc == X86ISD::ADC ||
9195        Opc == X86ISD::SBB ||
9196        Opc == X86ISD::SMUL ||
9197        Opc == X86ISD::UMUL ||
9198        Opc == X86ISD::INC ||
9199        Opc == X86ISD::DEC ||
9200        Opc == X86ISD::OR ||
9201        Opc == X86ISD::XOR ||
9202        Opc == X86ISD::AND))
9203     return true;
9204
9205   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9206     return true;
9207
9208   return false;
9209 }
9210
9211 static bool isZero(SDValue V) {
9212   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9213   return C && C->isNullValue();
9214 }
9215
9216 static bool isAllOnes(SDValue V) {
9217   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9218   return C && C->isAllOnesValue();
9219 }
9220
9221 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9222   if (V.getOpcode() != ISD::TRUNCATE)
9223     return false;
9224
9225   SDValue VOp0 = V.getOperand(0);
9226   unsigned InBits = VOp0.getValueSizeInBits();
9227   unsigned Bits = V.getValueSizeInBits();
9228   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9229 }
9230
9231 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9232   bool addTest = true;
9233   SDValue Cond  = Op.getOperand(0);
9234   SDValue Op1 = Op.getOperand(1);
9235   SDValue Op2 = Op.getOperand(2);
9236   DebugLoc DL = Op.getDebugLoc();
9237   SDValue CC;
9238
9239   if (Cond.getOpcode() == ISD::SETCC) {
9240     SDValue NewCond = LowerSETCC(Cond, DAG);
9241     if (NewCond.getNode())
9242       Cond = NewCond;
9243   }
9244
9245   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9246   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9247   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9248   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9249   if (Cond.getOpcode() == X86ISD::SETCC &&
9250       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9251       isZero(Cond.getOperand(1).getOperand(1))) {
9252     SDValue Cmp = Cond.getOperand(1);
9253
9254     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9255
9256     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9257         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9258       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9259
9260       SDValue CmpOp0 = Cmp.getOperand(0);
9261       // Apply further optimizations for special cases
9262       // (select (x != 0), -1, 0) -> neg & sbb
9263       // (select (x == 0), 0, -1) -> neg & sbb
9264       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9265         if (YC->isNullValue() &&
9266             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9267           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9268           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9269                                     DAG.getConstant(0, CmpOp0.getValueType()),
9270                                     CmpOp0);
9271           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9272                                     DAG.getConstant(X86::COND_B, MVT::i8),
9273                                     SDValue(Neg.getNode(), 1));
9274           return Res;
9275         }
9276
9277       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9278                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9279       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9280
9281       SDValue Res =   // Res = 0 or -1.
9282         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9283                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9284
9285       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9286         Res = DAG.getNOT(DL, Res, Res.getValueType());
9287
9288       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9289       if (N2C == 0 || !N2C->isNullValue())
9290         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9291       return Res;
9292     }
9293   }
9294
9295   // Look past (and (setcc_carry (cmp ...)), 1).
9296   if (Cond.getOpcode() == ISD::AND &&
9297       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9298     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9299     if (C && C->getAPIntValue() == 1)
9300       Cond = Cond.getOperand(0);
9301   }
9302
9303   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9304   // setting operand in place of the X86ISD::SETCC.
9305   unsigned CondOpcode = Cond.getOpcode();
9306   if (CondOpcode == X86ISD::SETCC ||
9307       CondOpcode == X86ISD::SETCC_CARRY) {
9308     CC = Cond.getOperand(0);
9309
9310     SDValue Cmp = Cond.getOperand(1);
9311     unsigned Opc = Cmp.getOpcode();
9312     EVT VT = Op.getValueType();
9313
9314     bool IllegalFPCMov = false;
9315     if (VT.isFloatingPoint() && !VT.isVector() &&
9316         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9317       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9318
9319     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9320         Opc == X86ISD::BT) { // FIXME
9321       Cond = Cmp;
9322       addTest = false;
9323     }
9324   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9325              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9326              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9327               Cond.getOperand(0).getValueType() != MVT::i8)) {
9328     SDValue LHS = Cond.getOperand(0);
9329     SDValue RHS = Cond.getOperand(1);
9330     unsigned X86Opcode;
9331     unsigned X86Cond;
9332     SDVTList VTs;
9333     switch (CondOpcode) {
9334     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9335     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9336     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9337     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9338     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9339     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9340     default: llvm_unreachable("unexpected overflowing operator");
9341     }
9342     if (CondOpcode == ISD::UMULO)
9343       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9344                           MVT::i32);
9345     else
9346       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9347
9348     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9349
9350     if (CondOpcode == ISD::UMULO)
9351       Cond = X86Op.getValue(2);
9352     else
9353       Cond = X86Op.getValue(1);
9354
9355     CC = DAG.getConstant(X86Cond, MVT::i8);
9356     addTest = false;
9357   }
9358
9359   if (addTest) {
9360     // Look pass the truncate if the high bits are known zero.
9361     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9362         Cond = Cond.getOperand(0);
9363
9364     // We know the result of AND is compared against zero. Try to match
9365     // it to BT.
9366     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9367       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9368       if (NewSetCC.getNode()) {
9369         CC = NewSetCC.getOperand(0);
9370         Cond = NewSetCC.getOperand(1);
9371         addTest = false;
9372       }
9373     }
9374   }
9375
9376   if (addTest) {
9377     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9378     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9379   }
9380
9381   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9382   // a <  b ?  0 : -1 -> RES = setcc_carry
9383   // a >= b ? -1 :  0 -> RES = setcc_carry
9384   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9385   if (Cond.getOpcode() == X86ISD::SUB) {
9386     Cond = ConvertCmpIfNecessary(Cond, DAG);
9387     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9388
9389     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9390         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9391       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9392                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9393       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9394         return DAG.getNOT(DL, Res, Res.getValueType());
9395       return Res;
9396     }
9397   }
9398
9399   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9400   // widen the cmov and push the truncate through. This avoids introducing a new
9401   // branch during isel and doesn't add any extensions.
9402   if (Op.getValueType() == MVT::i8 &&
9403       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9404     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9405     if (T1.getValueType() == T2.getValueType() &&
9406         // Blacklist CopyFromReg to avoid partial register stalls.
9407         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9408       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9409       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9410       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9411     }
9412   }
9413
9414   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9415   // condition is true.
9416   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9417   SDValue Ops[] = { Op2, Op1, CC, Cond };
9418   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9419 }
9420
9421 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9422 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9423 // from the AND / OR.
9424 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9425   Opc = Op.getOpcode();
9426   if (Opc != ISD::OR && Opc != ISD::AND)
9427     return false;
9428   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9429           Op.getOperand(0).hasOneUse() &&
9430           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9431           Op.getOperand(1).hasOneUse());
9432 }
9433
9434 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9435 // 1 and that the SETCC node has a single use.
9436 static bool isXor1OfSetCC(SDValue Op) {
9437   if (Op.getOpcode() != ISD::XOR)
9438     return false;
9439   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9440   if (N1C && N1C->getAPIntValue() == 1) {
9441     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9442       Op.getOperand(0).hasOneUse();
9443   }
9444   return false;
9445 }
9446
9447 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9448   bool addTest = true;
9449   SDValue Chain = Op.getOperand(0);
9450   SDValue Cond  = Op.getOperand(1);
9451   SDValue Dest  = Op.getOperand(2);
9452   DebugLoc dl = Op.getDebugLoc();
9453   SDValue CC;
9454   bool Inverted = false;
9455
9456   if (Cond.getOpcode() == ISD::SETCC) {
9457     // Check for setcc([su]{add,sub,mul}o == 0).
9458     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9459         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9460         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9461         Cond.getOperand(0).getResNo() == 1 &&
9462         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9463          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9464          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9465          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9466          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9467          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9468       Inverted = true;
9469       Cond = Cond.getOperand(0);
9470     } else {
9471       SDValue NewCond = LowerSETCC(Cond, DAG);
9472       if (NewCond.getNode())
9473         Cond = NewCond;
9474     }
9475   }
9476 #if 0
9477   // FIXME: LowerXALUO doesn't handle these!!
9478   else if (Cond.getOpcode() == X86ISD::ADD  ||
9479            Cond.getOpcode() == X86ISD::SUB  ||
9480            Cond.getOpcode() == X86ISD::SMUL ||
9481            Cond.getOpcode() == X86ISD::UMUL)
9482     Cond = LowerXALUO(Cond, DAG);
9483 #endif
9484
9485   // Look pass (and (setcc_carry (cmp ...)), 1).
9486   if (Cond.getOpcode() == ISD::AND &&
9487       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9488     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9489     if (C && C->getAPIntValue() == 1)
9490       Cond = Cond.getOperand(0);
9491   }
9492
9493   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9494   // setting operand in place of the X86ISD::SETCC.
9495   unsigned CondOpcode = Cond.getOpcode();
9496   if (CondOpcode == X86ISD::SETCC ||
9497       CondOpcode == X86ISD::SETCC_CARRY) {
9498     CC = Cond.getOperand(0);
9499
9500     SDValue Cmp = Cond.getOperand(1);
9501     unsigned Opc = Cmp.getOpcode();
9502     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9503     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9504       Cond = Cmp;
9505       addTest = false;
9506     } else {
9507       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9508       default: break;
9509       case X86::COND_O:
9510       case X86::COND_B:
9511         // These can only come from an arithmetic instruction with overflow,
9512         // e.g. SADDO, UADDO.
9513         Cond = Cond.getNode()->getOperand(1);
9514         addTest = false;
9515         break;
9516       }
9517     }
9518   }
9519   CondOpcode = Cond.getOpcode();
9520   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9521       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9522       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9523        Cond.getOperand(0).getValueType() != MVT::i8)) {
9524     SDValue LHS = Cond.getOperand(0);
9525     SDValue RHS = Cond.getOperand(1);
9526     unsigned X86Opcode;
9527     unsigned X86Cond;
9528     SDVTList VTs;
9529     switch (CondOpcode) {
9530     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9531     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9532     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9533     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9534     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9535     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9536     default: llvm_unreachable("unexpected overflowing operator");
9537     }
9538     if (Inverted)
9539       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9540     if (CondOpcode == ISD::UMULO)
9541       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9542                           MVT::i32);
9543     else
9544       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9545
9546     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9547
9548     if (CondOpcode == ISD::UMULO)
9549       Cond = X86Op.getValue(2);
9550     else
9551       Cond = X86Op.getValue(1);
9552
9553     CC = DAG.getConstant(X86Cond, MVT::i8);
9554     addTest = false;
9555   } else {
9556     unsigned CondOpc;
9557     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9558       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9559       if (CondOpc == ISD::OR) {
9560         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9561         // two branches instead of an explicit OR instruction with a
9562         // separate test.
9563         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9564             isX86LogicalCmp(Cmp)) {
9565           CC = Cond.getOperand(0).getOperand(0);
9566           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9567                               Chain, Dest, CC, Cmp);
9568           CC = Cond.getOperand(1).getOperand(0);
9569           Cond = Cmp;
9570           addTest = false;
9571         }
9572       } else { // ISD::AND
9573         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9574         // two branches instead of an explicit AND instruction with a
9575         // separate test. However, we only do this if this block doesn't
9576         // have a fall-through edge, because this requires an explicit
9577         // jmp when the condition is false.
9578         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9579             isX86LogicalCmp(Cmp) &&
9580             Op.getNode()->hasOneUse()) {
9581           X86::CondCode CCode =
9582             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9583           CCode = X86::GetOppositeBranchCondition(CCode);
9584           CC = DAG.getConstant(CCode, MVT::i8);
9585           SDNode *User = *Op.getNode()->use_begin();
9586           // Look for an unconditional branch following this conditional branch.
9587           // We need this because we need to reverse the successors in order
9588           // to implement FCMP_OEQ.
9589           if (User->getOpcode() == ISD::BR) {
9590             SDValue FalseBB = User->getOperand(1);
9591             SDNode *NewBR =
9592               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9593             assert(NewBR == User);
9594             (void)NewBR;
9595             Dest = FalseBB;
9596
9597             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9598                                 Chain, Dest, CC, Cmp);
9599             X86::CondCode CCode =
9600               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9601             CCode = X86::GetOppositeBranchCondition(CCode);
9602             CC = DAG.getConstant(CCode, MVT::i8);
9603             Cond = Cmp;
9604             addTest = false;
9605           }
9606         }
9607       }
9608     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9609       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9610       // It should be transformed during dag combiner except when the condition
9611       // is set by a arithmetics with overflow node.
9612       X86::CondCode CCode =
9613         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9614       CCode = X86::GetOppositeBranchCondition(CCode);
9615       CC = DAG.getConstant(CCode, MVT::i8);
9616       Cond = Cond.getOperand(0).getOperand(1);
9617       addTest = false;
9618     } else if (Cond.getOpcode() == ISD::SETCC &&
9619                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9620       // For FCMP_OEQ, we can emit
9621       // two branches instead of an explicit AND instruction with a
9622       // separate test. However, we only do this if this block doesn't
9623       // have a fall-through edge, because this requires an explicit
9624       // jmp when the condition is false.
9625       if (Op.getNode()->hasOneUse()) {
9626         SDNode *User = *Op.getNode()->use_begin();
9627         // Look for an unconditional branch following this conditional branch.
9628         // We need this because we need to reverse the successors in order
9629         // to implement FCMP_OEQ.
9630         if (User->getOpcode() == ISD::BR) {
9631           SDValue FalseBB = User->getOperand(1);
9632           SDNode *NewBR =
9633             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9634           assert(NewBR == User);
9635           (void)NewBR;
9636           Dest = FalseBB;
9637
9638           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9639                                     Cond.getOperand(0), Cond.getOperand(1));
9640           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9641           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9642           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9643                               Chain, Dest, CC, Cmp);
9644           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9645           Cond = Cmp;
9646           addTest = false;
9647         }
9648       }
9649     } else if (Cond.getOpcode() == ISD::SETCC &&
9650                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9651       // For FCMP_UNE, we can emit
9652       // two branches instead of an explicit AND instruction with a
9653       // separate test. However, we only do this if this block doesn't
9654       // have a fall-through edge, because this requires an explicit
9655       // jmp when the condition is false.
9656       if (Op.getNode()->hasOneUse()) {
9657         SDNode *User = *Op.getNode()->use_begin();
9658         // Look for an unconditional branch following this conditional branch.
9659         // We need this because we need to reverse the successors in order
9660         // to implement FCMP_UNE.
9661         if (User->getOpcode() == ISD::BR) {
9662           SDValue FalseBB = User->getOperand(1);
9663           SDNode *NewBR =
9664             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9665           assert(NewBR == User);
9666           (void)NewBR;
9667
9668           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9669                                     Cond.getOperand(0), Cond.getOperand(1));
9670           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9671           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9672           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9673                               Chain, Dest, CC, Cmp);
9674           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9675           Cond = Cmp;
9676           addTest = false;
9677           Dest = FalseBB;
9678         }
9679       }
9680     }
9681   }
9682
9683   if (addTest) {
9684     // Look pass the truncate if the high bits are known zero.
9685     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9686         Cond = Cond.getOperand(0);
9687
9688     // We know the result of AND is compared against zero. Try to match
9689     // it to BT.
9690     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9691       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9692       if (NewSetCC.getNode()) {
9693         CC = NewSetCC.getOperand(0);
9694         Cond = NewSetCC.getOperand(1);
9695         addTest = false;
9696       }
9697     }
9698   }
9699
9700   if (addTest) {
9701     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9702     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9703   }
9704   Cond = ConvertCmpIfNecessary(Cond, DAG);
9705   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9706                      Chain, Dest, CC, Cond);
9707 }
9708
9709
9710 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9711 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9712 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9713 // that the guard pages used by the OS virtual memory manager are allocated in
9714 // correct sequence.
9715 SDValue
9716 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9717                                            SelectionDAG &DAG) const {
9718   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9719           getTargetMachine().Options.EnableSegmentedStacks) &&
9720          "This should be used only on Windows targets or when segmented stacks "
9721          "are being used");
9722   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9723   DebugLoc dl = Op.getDebugLoc();
9724
9725   // Get the inputs.
9726   SDValue Chain = Op.getOperand(0);
9727   SDValue Size  = Op.getOperand(1);
9728   // FIXME: Ensure alignment here
9729
9730   bool Is64Bit = Subtarget->is64Bit();
9731   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9732
9733   if (getTargetMachine().Options.EnableSegmentedStacks) {
9734     MachineFunction &MF = DAG.getMachineFunction();
9735     MachineRegisterInfo &MRI = MF.getRegInfo();
9736
9737     if (Is64Bit) {
9738       // The 64 bit implementation of segmented stacks needs to clobber both r10
9739       // r11. This makes it impossible to use it along with nested parameters.
9740       const Function *F = MF.getFunction();
9741
9742       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9743            I != E; ++I)
9744         if (I->hasNestAttr())
9745           report_fatal_error("Cannot use segmented stacks with functions that "
9746                              "have nested arguments.");
9747     }
9748
9749     const TargetRegisterClass *AddrRegClass =
9750       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9751     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9752     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9753     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9754                                 DAG.getRegister(Vreg, SPTy));
9755     SDValue Ops1[2] = { Value, Chain };
9756     return DAG.getMergeValues(Ops1, 2, dl);
9757   } else {
9758     SDValue Flag;
9759     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9760
9761     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9762     Flag = Chain.getValue(1);
9763     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9764
9765     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9766     Flag = Chain.getValue(1);
9767
9768     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9769
9770     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9771     return DAG.getMergeValues(Ops1, 2, dl);
9772   }
9773 }
9774
9775 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9776   MachineFunction &MF = DAG.getMachineFunction();
9777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9778
9779   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9780   DebugLoc DL = Op.getDebugLoc();
9781
9782   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9783     // vastart just stores the address of the VarArgsFrameIndex slot into the
9784     // memory location argument.
9785     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9786                                    getPointerTy());
9787     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9788                         MachinePointerInfo(SV), false, false, 0);
9789   }
9790
9791   // __va_list_tag:
9792   //   gp_offset         (0 - 6 * 8)
9793   //   fp_offset         (48 - 48 + 8 * 16)
9794   //   overflow_arg_area (point to parameters coming in memory).
9795   //   reg_save_area
9796   SmallVector<SDValue, 8> MemOps;
9797   SDValue FIN = Op.getOperand(1);
9798   // Store gp_offset
9799   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9800                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9801                                                MVT::i32),
9802                                FIN, MachinePointerInfo(SV), false, false, 0);
9803   MemOps.push_back(Store);
9804
9805   // Store fp_offset
9806   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9807                     FIN, DAG.getIntPtrConstant(4));
9808   Store = DAG.getStore(Op.getOperand(0), DL,
9809                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9810                                        MVT::i32),
9811                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9812   MemOps.push_back(Store);
9813
9814   // Store ptr to overflow_arg_area
9815   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9816                     FIN, DAG.getIntPtrConstant(4));
9817   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9818                                     getPointerTy());
9819   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9820                        MachinePointerInfo(SV, 8),
9821                        false, false, 0);
9822   MemOps.push_back(Store);
9823
9824   // Store ptr to reg_save_area.
9825   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9826                     FIN, DAG.getIntPtrConstant(8));
9827   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9828                                     getPointerTy());
9829   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9830                        MachinePointerInfo(SV, 16), false, false, 0);
9831   MemOps.push_back(Store);
9832   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9833                      &MemOps[0], MemOps.size());
9834 }
9835
9836 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9837   assert(Subtarget->is64Bit() &&
9838          "LowerVAARG only handles 64-bit va_arg!");
9839   assert((Subtarget->isTargetLinux() ||
9840           Subtarget->isTargetDarwin()) &&
9841           "Unhandled target in LowerVAARG");
9842   assert(Op.getNode()->getNumOperands() == 4);
9843   SDValue Chain = Op.getOperand(0);
9844   SDValue SrcPtr = Op.getOperand(1);
9845   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9846   unsigned Align = Op.getConstantOperandVal(3);
9847   DebugLoc dl = Op.getDebugLoc();
9848
9849   EVT ArgVT = Op.getNode()->getValueType(0);
9850   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9851   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9852   uint8_t ArgMode;
9853
9854   // Decide which area this value should be read from.
9855   // TODO: Implement the AMD64 ABI in its entirety. This simple
9856   // selection mechanism works only for the basic types.
9857   if (ArgVT == MVT::f80) {
9858     llvm_unreachable("va_arg for f80 not yet implemented");
9859   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9860     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9861   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9862     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9863   } else {
9864     llvm_unreachable("Unhandled argument type in LowerVAARG");
9865   }
9866
9867   if (ArgMode == 2) {
9868     // Sanity Check: Make sure using fp_offset makes sense.
9869     assert(!getTargetMachine().Options.UseSoftFloat &&
9870            !(DAG.getMachineFunction()
9871                 .getFunction()->getFnAttributes()
9872                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9873            Subtarget->hasSSE1());
9874   }
9875
9876   // Insert VAARG_64 node into the DAG
9877   // VAARG_64 returns two values: Variable Argument Address, Chain
9878   SmallVector<SDValue, 11> InstOps;
9879   InstOps.push_back(Chain);
9880   InstOps.push_back(SrcPtr);
9881   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9882   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9883   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9884   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9885   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9886                                           VTs, &InstOps[0], InstOps.size(),
9887                                           MVT::i64,
9888                                           MachinePointerInfo(SV),
9889                                           /*Align=*/0,
9890                                           /*Volatile=*/false,
9891                                           /*ReadMem=*/true,
9892                                           /*WriteMem=*/true);
9893   Chain = VAARG.getValue(1);
9894
9895   // Load the next argument and return it
9896   return DAG.getLoad(ArgVT, dl,
9897                      Chain,
9898                      VAARG,
9899                      MachinePointerInfo(),
9900                      false, false, false, 0);
9901 }
9902
9903 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9904                            SelectionDAG &DAG) {
9905   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9906   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9907   SDValue Chain = Op.getOperand(0);
9908   SDValue DstPtr = Op.getOperand(1);
9909   SDValue SrcPtr = Op.getOperand(2);
9910   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9911   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9912   DebugLoc DL = Op.getDebugLoc();
9913
9914   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9915                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9916                        false,
9917                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9918 }
9919
9920 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9921 // may or may not be a constant. Takes immediate version of shift as input.
9922 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9923                                    SDValue SrcOp, SDValue ShAmt,
9924                                    SelectionDAG &DAG) {
9925   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9926
9927   if (isa<ConstantSDNode>(ShAmt)) {
9928     // Constant may be a TargetConstant. Use a regular constant.
9929     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9930     switch (Opc) {
9931       default: llvm_unreachable("Unknown target vector shift node");
9932       case X86ISD::VSHLI:
9933       case X86ISD::VSRLI:
9934       case X86ISD::VSRAI:
9935         return DAG.getNode(Opc, dl, VT, SrcOp,
9936                            DAG.getConstant(ShiftAmt, MVT::i32));
9937     }
9938   }
9939
9940   // Change opcode to non-immediate version
9941   switch (Opc) {
9942     default: llvm_unreachable("Unknown target vector shift node");
9943     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9944     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9945     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9946   }
9947
9948   // Need to build a vector containing shift amount
9949   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9950   SDValue ShOps[4];
9951   ShOps[0] = ShAmt;
9952   ShOps[1] = DAG.getConstant(0, MVT::i32);
9953   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9954   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9955
9956   // The return type has to be a 128-bit type with the same element
9957   // type as the input type.
9958   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9959   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9960
9961   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9962   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9963 }
9964
9965 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9966   DebugLoc dl = Op.getDebugLoc();
9967   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9968   switch (IntNo) {
9969   default: return SDValue();    // Don't custom lower most intrinsics.
9970   // Comparison intrinsics.
9971   case Intrinsic::x86_sse_comieq_ss:
9972   case Intrinsic::x86_sse_comilt_ss:
9973   case Intrinsic::x86_sse_comile_ss:
9974   case Intrinsic::x86_sse_comigt_ss:
9975   case Intrinsic::x86_sse_comige_ss:
9976   case Intrinsic::x86_sse_comineq_ss:
9977   case Intrinsic::x86_sse_ucomieq_ss:
9978   case Intrinsic::x86_sse_ucomilt_ss:
9979   case Intrinsic::x86_sse_ucomile_ss:
9980   case Intrinsic::x86_sse_ucomigt_ss:
9981   case Intrinsic::x86_sse_ucomige_ss:
9982   case Intrinsic::x86_sse_ucomineq_ss:
9983   case Intrinsic::x86_sse2_comieq_sd:
9984   case Intrinsic::x86_sse2_comilt_sd:
9985   case Intrinsic::x86_sse2_comile_sd:
9986   case Intrinsic::x86_sse2_comigt_sd:
9987   case Intrinsic::x86_sse2_comige_sd:
9988   case Intrinsic::x86_sse2_comineq_sd:
9989   case Intrinsic::x86_sse2_ucomieq_sd:
9990   case Intrinsic::x86_sse2_ucomilt_sd:
9991   case Intrinsic::x86_sse2_ucomile_sd:
9992   case Intrinsic::x86_sse2_ucomigt_sd:
9993   case Intrinsic::x86_sse2_ucomige_sd:
9994   case Intrinsic::x86_sse2_ucomineq_sd: {
9995     unsigned Opc;
9996     ISD::CondCode CC;
9997     switch (IntNo) {
9998     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9999     case Intrinsic::x86_sse_comieq_ss:
10000     case Intrinsic::x86_sse2_comieq_sd:
10001       Opc = X86ISD::COMI;
10002       CC = ISD::SETEQ;
10003       break;
10004     case Intrinsic::x86_sse_comilt_ss:
10005     case Intrinsic::x86_sse2_comilt_sd:
10006       Opc = X86ISD::COMI;
10007       CC = ISD::SETLT;
10008       break;
10009     case Intrinsic::x86_sse_comile_ss:
10010     case Intrinsic::x86_sse2_comile_sd:
10011       Opc = X86ISD::COMI;
10012       CC = ISD::SETLE;
10013       break;
10014     case Intrinsic::x86_sse_comigt_ss:
10015     case Intrinsic::x86_sse2_comigt_sd:
10016       Opc = X86ISD::COMI;
10017       CC = ISD::SETGT;
10018       break;
10019     case Intrinsic::x86_sse_comige_ss:
10020     case Intrinsic::x86_sse2_comige_sd:
10021       Opc = X86ISD::COMI;
10022       CC = ISD::SETGE;
10023       break;
10024     case Intrinsic::x86_sse_comineq_ss:
10025     case Intrinsic::x86_sse2_comineq_sd:
10026       Opc = X86ISD::COMI;
10027       CC = ISD::SETNE;
10028       break;
10029     case Intrinsic::x86_sse_ucomieq_ss:
10030     case Intrinsic::x86_sse2_ucomieq_sd:
10031       Opc = X86ISD::UCOMI;
10032       CC = ISD::SETEQ;
10033       break;
10034     case Intrinsic::x86_sse_ucomilt_ss:
10035     case Intrinsic::x86_sse2_ucomilt_sd:
10036       Opc = X86ISD::UCOMI;
10037       CC = ISD::SETLT;
10038       break;
10039     case Intrinsic::x86_sse_ucomile_ss:
10040     case Intrinsic::x86_sse2_ucomile_sd:
10041       Opc = X86ISD::UCOMI;
10042       CC = ISD::SETLE;
10043       break;
10044     case Intrinsic::x86_sse_ucomigt_ss:
10045     case Intrinsic::x86_sse2_ucomigt_sd:
10046       Opc = X86ISD::UCOMI;
10047       CC = ISD::SETGT;
10048       break;
10049     case Intrinsic::x86_sse_ucomige_ss:
10050     case Intrinsic::x86_sse2_ucomige_sd:
10051       Opc = X86ISD::UCOMI;
10052       CC = ISD::SETGE;
10053       break;
10054     case Intrinsic::x86_sse_ucomineq_ss:
10055     case Intrinsic::x86_sse2_ucomineq_sd:
10056       Opc = X86ISD::UCOMI;
10057       CC = ISD::SETNE;
10058       break;
10059     }
10060
10061     SDValue LHS = Op.getOperand(1);
10062     SDValue RHS = Op.getOperand(2);
10063     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10064     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10065     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10066     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10067                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10068     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10069   }
10070
10071   // Arithmetic intrinsics.
10072   case Intrinsic::x86_sse2_pmulu_dq:
10073   case Intrinsic::x86_avx2_pmulu_dq:
10074     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10075                        Op.getOperand(1), Op.getOperand(2));
10076
10077   // SSE3/AVX horizontal add/sub intrinsics
10078   case Intrinsic::x86_sse3_hadd_ps:
10079   case Intrinsic::x86_sse3_hadd_pd:
10080   case Intrinsic::x86_avx_hadd_ps_256:
10081   case Intrinsic::x86_avx_hadd_pd_256:
10082   case Intrinsic::x86_sse3_hsub_ps:
10083   case Intrinsic::x86_sse3_hsub_pd:
10084   case Intrinsic::x86_avx_hsub_ps_256:
10085   case Intrinsic::x86_avx_hsub_pd_256:
10086   case Intrinsic::x86_ssse3_phadd_w_128:
10087   case Intrinsic::x86_ssse3_phadd_d_128:
10088   case Intrinsic::x86_avx2_phadd_w:
10089   case Intrinsic::x86_avx2_phadd_d:
10090   case Intrinsic::x86_ssse3_phsub_w_128:
10091   case Intrinsic::x86_ssse3_phsub_d_128:
10092   case Intrinsic::x86_avx2_phsub_w:
10093   case Intrinsic::x86_avx2_phsub_d: {
10094     unsigned Opcode;
10095     switch (IntNo) {
10096     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10097     case Intrinsic::x86_sse3_hadd_ps:
10098     case Intrinsic::x86_sse3_hadd_pd:
10099     case Intrinsic::x86_avx_hadd_ps_256:
10100     case Intrinsic::x86_avx_hadd_pd_256:
10101       Opcode = X86ISD::FHADD;
10102       break;
10103     case Intrinsic::x86_sse3_hsub_ps:
10104     case Intrinsic::x86_sse3_hsub_pd:
10105     case Intrinsic::x86_avx_hsub_ps_256:
10106     case Intrinsic::x86_avx_hsub_pd_256:
10107       Opcode = X86ISD::FHSUB;
10108       break;
10109     case Intrinsic::x86_ssse3_phadd_w_128:
10110     case Intrinsic::x86_ssse3_phadd_d_128:
10111     case Intrinsic::x86_avx2_phadd_w:
10112     case Intrinsic::x86_avx2_phadd_d:
10113       Opcode = X86ISD::HADD;
10114       break;
10115     case Intrinsic::x86_ssse3_phsub_w_128:
10116     case Intrinsic::x86_ssse3_phsub_d_128:
10117     case Intrinsic::x86_avx2_phsub_w:
10118     case Intrinsic::x86_avx2_phsub_d:
10119       Opcode = X86ISD::HSUB;
10120       break;
10121     }
10122     return DAG.getNode(Opcode, dl, Op.getValueType(),
10123                        Op.getOperand(1), Op.getOperand(2));
10124   }
10125
10126   // AVX2 variable shift intrinsics
10127   case Intrinsic::x86_avx2_psllv_d:
10128   case Intrinsic::x86_avx2_psllv_q:
10129   case Intrinsic::x86_avx2_psllv_d_256:
10130   case Intrinsic::x86_avx2_psllv_q_256:
10131   case Intrinsic::x86_avx2_psrlv_d:
10132   case Intrinsic::x86_avx2_psrlv_q:
10133   case Intrinsic::x86_avx2_psrlv_d_256:
10134   case Intrinsic::x86_avx2_psrlv_q_256:
10135   case Intrinsic::x86_avx2_psrav_d:
10136   case Intrinsic::x86_avx2_psrav_d_256: {
10137     unsigned Opcode;
10138     switch (IntNo) {
10139     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10140     case Intrinsic::x86_avx2_psllv_d:
10141     case Intrinsic::x86_avx2_psllv_q:
10142     case Intrinsic::x86_avx2_psllv_d_256:
10143     case Intrinsic::x86_avx2_psllv_q_256:
10144       Opcode = ISD::SHL;
10145       break;
10146     case Intrinsic::x86_avx2_psrlv_d:
10147     case Intrinsic::x86_avx2_psrlv_q:
10148     case Intrinsic::x86_avx2_psrlv_d_256:
10149     case Intrinsic::x86_avx2_psrlv_q_256:
10150       Opcode = ISD::SRL;
10151       break;
10152     case Intrinsic::x86_avx2_psrav_d:
10153     case Intrinsic::x86_avx2_psrav_d_256:
10154       Opcode = ISD::SRA;
10155       break;
10156     }
10157     return DAG.getNode(Opcode, dl, Op.getValueType(),
10158                        Op.getOperand(1), Op.getOperand(2));
10159   }
10160
10161   case Intrinsic::x86_ssse3_pshuf_b_128:
10162   case Intrinsic::x86_avx2_pshuf_b:
10163     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10164                        Op.getOperand(1), Op.getOperand(2));
10165
10166   case Intrinsic::x86_ssse3_psign_b_128:
10167   case Intrinsic::x86_ssse3_psign_w_128:
10168   case Intrinsic::x86_ssse3_psign_d_128:
10169   case Intrinsic::x86_avx2_psign_b:
10170   case Intrinsic::x86_avx2_psign_w:
10171   case Intrinsic::x86_avx2_psign_d:
10172     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10173                        Op.getOperand(1), Op.getOperand(2));
10174
10175   case Intrinsic::x86_sse41_insertps:
10176     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10177                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10178
10179   case Intrinsic::x86_avx_vperm2f128_ps_256:
10180   case Intrinsic::x86_avx_vperm2f128_pd_256:
10181   case Intrinsic::x86_avx_vperm2f128_si_256:
10182   case Intrinsic::x86_avx2_vperm2i128:
10183     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10184                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10185
10186   case Intrinsic::x86_avx2_permd:
10187   case Intrinsic::x86_avx2_permps:
10188     // Operands intentionally swapped. Mask is last operand to intrinsic,
10189     // but second operand for node/intruction.
10190     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10191                        Op.getOperand(2), Op.getOperand(1));
10192
10193   // ptest and testp intrinsics. The intrinsic these come from are designed to
10194   // return an integer value, not just an instruction so lower it to the ptest
10195   // or testp pattern and a setcc for the result.
10196   case Intrinsic::x86_sse41_ptestz:
10197   case Intrinsic::x86_sse41_ptestc:
10198   case Intrinsic::x86_sse41_ptestnzc:
10199   case Intrinsic::x86_avx_ptestz_256:
10200   case Intrinsic::x86_avx_ptestc_256:
10201   case Intrinsic::x86_avx_ptestnzc_256:
10202   case Intrinsic::x86_avx_vtestz_ps:
10203   case Intrinsic::x86_avx_vtestc_ps:
10204   case Intrinsic::x86_avx_vtestnzc_ps:
10205   case Intrinsic::x86_avx_vtestz_pd:
10206   case Intrinsic::x86_avx_vtestc_pd:
10207   case Intrinsic::x86_avx_vtestnzc_pd:
10208   case Intrinsic::x86_avx_vtestz_ps_256:
10209   case Intrinsic::x86_avx_vtestc_ps_256:
10210   case Intrinsic::x86_avx_vtestnzc_ps_256:
10211   case Intrinsic::x86_avx_vtestz_pd_256:
10212   case Intrinsic::x86_avx_vtestc_pd_256:
10213   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10214     bool IsTestPacked = false;
10215     unsigned X86CC;
10216     switch (IntNo) {
10217     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10218     case Intrinsic::x86_avx_vtestz_ps:
10219     case Intrinsic::x86_avx_vtestz_pd:
10220     case Intrinsic::x86_avx_vtestz_ps_256:
10221     case Intrinsic::x86_avx_vtestz_pd_256:
10222       IsTestPacked = true; // Fallthrough
10223     case Intrinsic::x86_sse41_ptestz:
10224     case Intrinsic::x86_avx_ptestz_256:
10225       // ZF = 1
10226       X86CC = X86::COND_E;
10227       break;
10228     case Intrinsic::x86_avx_vtestc_ps:
10229     case Intrinsic::x86_avx_vtestc_pd:
10230     case Intrinsic::x86_avx_vtestc_ps_256:
10231     case Intrinsic::x86_avx_vtestc_pd_256:
10232       IsTestPacked = true; // Fallthrough
10233     case Intrinsic::x86_sse41_ptestc:
10234     case Intrinsic::x86_avx_ptestc_256:
10235       // CF = 1
10236       X86CC = X86::COND_B;
10237       break;
10238     case Intrinsic::x86_avx_vtestnzc_ps:
10239     case Intrinsic::x86_avx_vtestnzc_pd:
10240     case Intrinsic::x86_avx_vtestnzc_ps_256:
10241     case Intrinsic::x86_avx_vtestnzc_pd_256:
10242       IsTestPacked = true; // Fallthrough
10243     case Intrinsic::x86_sse41_ptestnzc:
10244     case Intrinsic::x86_avx_ptestnzc_256:
10245       // ZF and CF = 0
10246       X86CC = X86::COND_A;
10247       break;
10248     }
10249
10250     SDValue LHS = Op.getOperand(1);
10251     SDValue RHS = Op.getOperand(2);
10252     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10253     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10254     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10255     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10256     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10257   }
10258
10259   // SSE/AVX shift intrinsics
10260   case Intrinsic::x86_sse2_psll_w:
10261   case Intrinsic::x86_sse2_psll_d:
10262   case Intrinsic::x86_sse2_psll_q:
10263   case Intrinsic::x86_avx2_psll_w:
10264   case Intrinsic::x86_avx2_psll_d:
10265   case Intrinsic::x86_avx2_psll_q:
10266   case Intrinsic::x86_sse2_psrl_w:
10267   case Intrinsic::x86_sse2_psrl_d:
10268   case Intrinsic::x86_sse2_psrl_q:
10269   case Intrinsic::x86_avx2_psrl_w:
10270   case Intrinsic::x86_avx2_psrl_d:
10271   case Intrinsic::x86_avx2_psrl_q:
10272   case Intrinsic::x86_sse2_psra_w:
10273   case Intrinsic::x86_sse2_psra_d:
10274   case Intrinsic::x86_avx2_psra_w:
10275   case Intrinsic::x86_avx2_psra_d: {
10276     unsigned Opcode;
10277     switch (IntNo) {
10278     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10279     case Intrinsic::x86_sse2_psll_w:
10280     case Intrinsic::x86_sse2_psll_d:
10281     case Intrinsic::x86_sse2_psll_q:
10282     case Intrinsic::x86_avx2_psll_w:
10283     case Intrinsic::x86_avx2_psll_d:
10284     case Intrinsic::x86_avx2_psll_q:
10285       Opcode = X86ISD::VSHL;
10286       break;
10287     case Intrinsic::x86_sse2_psrl_w:
10288     case Intrinsic::x86_sse2_psrl_d:
10289     case Intrinsic::x86_sse2_psrl_q:
10290     case Intrinsic::x86_avx2_psrl_w:
10291     case Intrinsic::x86_avx2_psrl_d:
10292     case Intrinsic::x86_avx2_psrl_q:
10293       Opcode = X86ISD::VSRL;
10294       break;
10295     case Intrinsic::x86_sse2_psra_w:
10296     case Intrinsic::x86_sse2_psra_d:
10297     case Intrinsic::x86_avx2_psra_w:
10298     case Intrinsic::x86_avx2_psra_d:
10299       Opcode = X86ISD::VSRA;
10300       break;
10301     }
10302     return DAG.getNode(Opcode, dl, Op.getValueType(),
10303                        Op.getOperand(1), Op.getOperand(2));
10304   }
10305
10306   // SSE/AVX immediate shift intrinsics
10307   case Intrinsic::x86_sse2_pslli_w:
10308   case Intrinsic::x86_sse2_pslli_d:
10309   case Intrinsic::x86_sse2_pslli_q:
10310   case Intrinsic::x86_avx2_pslli_w:
10311   case Intrinsic::x86_avx2_pslli_d:
10312   case Intrinsic::x86_avx2_pslli_q:
10313   case Intrinsic::x86_sse2_psrli_w:
10314   case Intrinsic::x86_sse2_psrli_d:
10315   case Intrinsic::x86_sse2_psrli_q:
10316   case Intrinsic::x86_avx2_psrli_w:
10317   case Intrinsic::x86_avx2_psrli_d:
10318   case Intrinsic::x86_avx2_psrli_q:
10319   case Intrinsic::x86_sse2_psrai_w:
10320   case Intrinsic::x86_sse2_psrai_d:
10321   case Intrinsic::x86_avx2_psrai_w:
10322   case Intrinsic::x86_avx2_psrai_d: {
10323     unsigned Opcode;
10324     switch (IntNo) {
10325     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10326     case Intrinsic::x86_sse2_pslli_w:
10327     case Intrinsic::x86_sse2_pslli_d:
10328     case Intrinsic::x86_sse2_pslli_q:
10329     case Intrinsic::x86_avx2_pslli_w:
10330     case Intrinsic::x86_avx2_pslli_d:
10331     case Intrinsic::x86_avx2_pslli_q:
10332       Opcode = X86ISD::VSHLI;
10333       break;
10334     case Intrinsic::x86_sse2_psrli_w:
10335     case Intrinsic::x86_sse2_psrli_d:
10336     case Intrinsic::x86_sse2_psrli_q:
10337     case Intrinsic::x86_avx2_psrli_w:
10338     case Intrinsic::x86_avx2_psrli_d:
10339     case Intrinsic::x86_avx2_psrli_q:
10340       Opcode = X86ISD::VSRLI;
10341       break;
10342     case Intrinsic::x86_sse2_psrai_w:
10343     case Intrinsic::x86_sse2_psrai_d:
10344     case Intrinsic::x86_avx2_psrai_w:
10345     case Intrinsic::x86_avx2_psrai_d:
10346       Opcode = X86ISD::VSRAI;
10347       break;
10348     }
10349     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10350                                Op.getOperand(1), Op.getOperand(2), DAG);
10351   }
10352
10353   case Intrinsic::x86_sse42_pcmpistria128:
10354   case Intrinsic::x86_sse42_pcmpestria128:
10355   case Intrinsic::x86_sse42_pcmpistric128:
10356   case Intrinsic::x86_sse42_pcmpestric128:
10357   case Intrinsic::x86_sse42_pcmpistrio128:
10358   case Intrinsic::x86_sse42_pcmpestrio128:
10359   case Intrinsic::x86_sse42_pcmpistris128:
10360   case Intrinsic::x86_sse42_pcmpestris128:
10361   case Intrinsic::x86_sse42_pcmpistriz128:
10362   case Intrinsic::x86_sse42_pcmpestriz128: {
10363     unsigned Opcode;
10364     unsigned X86CC;
10365     switch (IntNo) {
10366     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10367     case Intrinsic::x86_sse42_pcmpistria128:
10368       Opcode = X86ISD::PCMPISTRI;
10369       X86CC = X86::COND_A;
10370       break;
10371     case Intrinsic::x86_sse42_pcmpestria128:
10372       Opcode = X86ISD::PCMPESTRI;
10373       X86CC = X86::COND_A;
10374       break;
10375     case Intrinsic::x86_sse42_pcmpistric128:
10376       Opcode = X86ISD::PCMPISTRI;
10377       X86CC = X86::COND_B;
10378       break;
10379     case Intrinsic::x86_sse42_pcmpestric128:
10380       Opcode = X86ISD::PCMPESTRI;
10381       X86CC = X86::COND_B;
10382       break;
10383     case Intrinsic::x86_sse42_pcmpistrio128:
10384       Opcode = X86ISD::PCMPISTRI;
10385       X86CC = X86::COND_O;
10386       break;
10387     case Intrinsic::x86_sse42_pcmpestrio128:
10388       Opcode = X86ISD::PCMPESTRI;
10389       X86CC = X86::COND_O;
10390       break;
10391     case Intrinsic::x86_sse42_pcmpistris128:
10392       Opcode = X86ISD::PCMPISTRI;
10393       X86CC = X86::COND_S;
10394       break;
10395     case Intrinsic::x86_sse42_pcmpestris128:
10396       Opcode = X86ISD::PCMPESTRI;
10397       X86CC = X86::COND_S;
10398       break;
10399     case Intrinsic::x86_sse42_pcmpistriz128:
10400       Opcode = X86ISD::PCMPISTRI;
10401       X86CC = X86::COND_E;
10402       break;
10403     case Intrinsic::x86_sse42_pcmpestriz128:
10404       Opcode = X86ISD::PCMPESTRI;
10405       X86CC = X86::COND_E;
10406       break;
10407     }
10408     SmallVector<SDValue, 5> NewOps;
10409     NewOps.append(Op->op_begin()+1, Op->op_end());
10410     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10411     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10412     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10413                                 DAG.getConstant(X86CC, MVT::i8),
10414                                 SDValue(PCMP.getNode(), 1));
10415     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10416   }
10417
10418   case Intrinsic::x86_sse42_pcmpistri128:
10419   case Intrinsic::x86_sse42_pcmpestri128: {
10420     unsigned Opcode;
10421     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10422       Opcode = X86ISD::PCMPISTRI;
10423     else
10424       Opcode = X86ISD::PCMPESTRI;
10425
10426     SmallVector<SDValue, 5> NewOps;
10427     NewOps.append(Op->op_begin()+1, Op->op_end());
10428     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10429     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10430   }
10431   case Intrinsic::x86_fma_vfmadd_ps:
10432   case Intrinsic::x86_fma_vfmadd_pd:
10433   case Intrinsic::x86_fma_vfmsub_ps:
10434   case Intrinsic::x86_fma_vfmsub_pd:
10435   case Intrinsic::x86_fma_vfnmadd_ps:
10436   case Intrinsic::x86_fma_vfnmadd_pd:
10437   case Intrinsic::x86_fma_vfnmsub_ps:
10438   case Intrinsic::x86_fma_vfnmsub_pd:
10439   case Intrinsic::x86_fma_vfmaddsub_ps:
10440   case Intrinsic::x86_fma_vfmaddsub_pd:
10441   case Intrinsic::x86_fma_vfmsubadd_ps:
10442   case Intrinsic::x86_fma_vfmsubadd_pd:
10443   case Intrinsic::x86_fma_vfmadd_ps_256:
10444   case Intrinsic::x86_fma_vfmadd_pd_256:
10445   case Intrinsic::x86_fma_vfmsub_ps_256:
10446   case Intrinsic::x86_fma_vfmsub_pd_256:
10447   case Intrinsic::x86_fma_vfnmadd_ps_256:
10448   case Intrinsic::x86_fma_vfnmadd_pd_256:
10449   case Intrinsic::x86_fma_vfnmsub_ps_256:
10450   case Intrinsic::x86_fma_vfnmsub_pd_256:
10451   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10452   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10453   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10454   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10455     unsigned Opc;
10456     switch (IntNo) {
10457     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10458     case Intrinsic::x86_fma_vfmadd_ps:
10459     case Intrinsic::x86_fma_vfmadd_pd:
10460     case Intrinsic::x86_fma_vfmadd_ps_256:
10461     case Intrinsic::x86_fma_vfmadd_pd_256:
10462       Opc = X86ISD::FMADD;
10463       break;
10464     case Intrinsic::x86_fma_vfmsub_ps:
10465     case Intrinsic::x86_fma_vfmsub_pd:
10466     case Intrinsic::x86_fma_vfmsub_ps_256:
10467     case Intrinsic::x86_fma_vfmsub_pd_256:
10468       Opc = X86ISD::FMSUB;
10469       break;
10470     case Intrinsic::x86_fma_vfnmadd_ps:
10471     case Intrinsic::x86_fma_vfnmadd_pd:
10472     case Intrinsic::x86_fma_vfnmadd_ps_256:
10473     case Intrinsic::x86_fma_vfnmadd_pd_256:
10474       Opc = X86ISD::FNMADD;
10475       break;
10476     case Intrinsic::x86_fma_vfnmsub_ps:
10477     case Intrinsic::x86_fma_vfnmsub_pd:
10478     case Intrinsic::x86_fma_vfnmsub_ps_256:
10479     case Intrinsic::x86_fma_vfnmsub_pd_256:
10480       Opc = X86ISD::FNMSUB;
10481       break;
10482     case Intrinsic::x86_fma_vfmaddsub_ps:
10483     case Intrinsic::x86_fma_vfmaddsub_pd:
10484     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10485     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10486       Opc = X86ISD::FMADDSUB;
10487       break;
10488     case Intrinsic::x86_fma_vfmsubadd_ps:
10489     case Intrinsic::x86_fma_vfmsubadd_pd:
10490     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10491     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10492       Opc = X86ISD::FMSUBADD;
10493       break;
10494     }
10495
10496     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10497                        Op.getOperand(2), Op.getOperand(3));
10498   }
10499   }
10500 }
10501
10502 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10503   DebugLoc dl = Op.getDebugLoc();
10504   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10505   switch (IntNo) {
10506   default: return SDValue();    // Don't custom lower most intrinsics.
10507
10508   // RDRAND intrinsics.
10509   case Intrinsic::x86_rdrand_16:
10510   case Intrinsic::x86_rdrand_32:
10511   case Intrinsic::x86_rdrand_64: {
10512     // Emit the node with the right value type.
10513     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10514     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10515
10516     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10517     // return the value from Rand, which is always 0, casted to i32.
10518     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10519                       DAG.getConstant(1, Op->getValueType(1)),
10520                       DAG.getConstant(X86::COND_B, MVT::i32),
10521                       SDValue(Result.getNode(), 1) };
10522     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10523                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10524                                   Ops, 4);
10525
10526     // Return { result, isValid, chain }.
10527     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10528                        SDValue(Result.getNode(), 2));
10529   }
10530   }
10531 }
10532
10533 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10534                                            SelectionDAG &DAG) const {
10535   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10536   MFI->setReturnAddressIsTaken(true);
10537
10538   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10539   DebugLoc dl = Op.getDebugLoc();
10540
10541   if (Depth > 0) {
10542     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10543     SDValue Offset =
10544       DAG.getConstant(TD->getPointerSize(0),
10545                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10546     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10547                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10548                                    FrameAddr, Offset),
10549                        MachinePointerInfo(), false, false, false, 0);
10550   }
10551
10552   // Just load the return address.
10553   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10554   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10555                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10556 }
10557
10558 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10559   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10560   MFI->setFrameAddressIsTaken(true);
10561
10562   EVT VT = Op.getValueType();
10563   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10564   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10565   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10566   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10567   while (Depth--)
10568     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10569                             MachinePointerInfo(),
10570                             false, false, false, 0);
10571   return FrameAddr;
10572 }
10573
10574 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10575                                                      SelectionDAG &DAG) const {
10576   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10577 }
10578
10579 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10580   SDValue Chain     = Op.getOperand(0);
10581   SDValue Offset    = Op.getOperand(1);
10582   SDValue Handler   = Op.getOperand(2);
10583   DebugLoc dl       = Op.getDebugLoc();
10584
10585   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10586                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10587                                      getPointerTy());
10588   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10589
10590   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10591                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10592   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10593   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10594                        false, false, 0);
10595   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10596
10597   return DAG.getNode(X86ISD::EH_RETURN, dl,
10598                      MVT::Other,
10599                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10600 }
10601
10602 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10603                                                SelectionDAG &DAG) const {
10604   DebugLoc DL = Op.getDebugLoc();
10605   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10606                      DAG.getVTList(MVT::i32, MVT::Other),
10607                      Op.getOperand(0), Op.getOperand(1));
10608 }
10609
10610 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10611                                                 SelectionDAG &DAG) const {
10612   DebugLoc DL = Op.getDebugLoc();
10613   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10614                      Op.getOperand(0), Op.getOperand(1));
10615 }
10616
10617 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10618   return Op.getOperand(0);
10619 }
10620
10621 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10622                                                 SelectionDAG &DAG) const {
10623   SDValue Root = Op.getOperand(0);
10624   SDValue Trmp = Op.getOperand(1); // trampoline
10625   SDValue FPtr = Op.getOperand(2); // nested function
10626   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10627   DebugLoc dl  = Op.getDebugLoc();
10628
10629   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10630   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10631
10632   if (Subtarget->is64Bit()) {
10633     SDValue OutChains[6];
10634
10635     // Large code-model.
10636     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10637     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10638
10639     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10640     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10641
10642     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10643
10644     // Load the pointer to the nested function into R11.
10645     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10646     SDValue Addr = Trmp;
10647     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10648                                 Addr, MachinePointerInfo(TrmpAddr),
10649                                 false, false, 0);
10650
10651     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10652                        DAG.getConstant(2, MVT::i64));
10653     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10654                                 MachinePointerInfo(TrmpAddr, 2),
10655                                 false, false, 2);
10656
10657     // Load the 'nest' parameter value into R10.
10658     // R10 is specified in X86CallingConv.td
10659     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10661                        DAG.getConstant(10, MVT::i64));
10662     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10663                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10664                                 false, false, 0);
10665
10666     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10667                        DAG.getConstant(12, MVT::i64));
10668     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10669                                 MachinePointerInfo(TrmpAddr, 12),
10670                                 false, false, 2);
10671
10672     // Jump to the nested function.
10673     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10674     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10675                        DAG.getConstant(20, MVT::i64));
10676     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10677                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10678                                 false, false, 0);
10679
10680     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10681     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10682                        DAG.getConstant(22, MVT::i64));
10683     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10684                                 MachinePointerInfo(TrmpAddr, 22),
10685                                 false, false, 0);
10686
10687     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10688   } else {
10689     const Function *Func =
10690       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10691     CallingConv::ID CC = Func->getCallingConv();
10692     unsigned NestReg;
10693
10694     switch (CC) {
10695     default:
10696       llvm_unreachable("Unsupported calling convention");
10697     case CallingConv::C:
10698     case CallingConv::X86_StdCall: {
10699       // Pass 'nest' parameter in ECX.
10700       // Must be kept in sync with X86CallingConv.td
10701       NestReg = X86::ECX;
10702
10703       // Check that ECX wasn't needed by an 'inreg' parameter.
10704       FunctionType *FTy = Func->getFunctionType();
10705       const AttrListPtr &Attrs = Func->getAttributes();
10706
10707       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10708         unsigned InRegCount = 0;
10709         unsigned Idx = 1;
10710
10711         for (FunctionType::param_iterator I = FTy->param_begin(),
10712              E = FTy->param_end(); I != E; ++I, ++Idx)
10713           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10714             // FIXME: should only count parameters that are lowered to integers.
10715             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10716
10717         if (InRegCount > 2) {
10718           report_fatal_error("Nest register in use - reduce number of inreg"
10719                              " parameters!");
10720         }
10721       }
10722       break;
10723     }
10724     case CallingConv::X86_FastCall:
10725     case CallingConv::X86_ThisCall:
10726     case CallingConv::Fast:
10727       // Pass 'nest' parameter in EAX.
10728       // Must be kept in sync with X86CallingConv.td
10729       NestReg = X86::EAX;
10730       break;
10731     }
10732
10733     SDValue OutChains[4];
10734     SDValue Addr, Disp;
10735
10736     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10737                        DAG.getConstant(10, MVT::i32));
10738     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10739
10740     // This is storing the opcode for MOV32ri.
10741     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10742     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10743     OutChains[0] = DAG.getStore(Root, dl,
10744                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10745                                 Trmp, MachinePointerInfo(TrmpAddr),
10746                                 false, false, 0);
10747
10748     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10749                        DAG.getConstant(1, MVT::i32));
10750     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10751                                 MachinePointerInfo(TrmpAddr, 1),
10752                                 false, false, 1);
10753
10754     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10755     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10756                        DAG.getConstant(5, MVT::i32));
10757     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10758                                 MachinePointerInfo(TrmpAddr, 5),
10759                                 false, false, 1);
10760
10761     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10762                        DAG.getConstant(6, MVT::i32));
10763     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10764                                 MachinePointerInfo(TrmpAddr, 6),
10765                                 false, false, 1);
10766
10767     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10768   }
10769 }
10770
10771 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10772                                             SelectionDAG &DAG) const {
10773   /*
10774    The rounding mode is in bits 11:10 of FPSR, and has the following
10775    settings:
10776      00 Round to nearest
10777      01 Round to -inf
10778      10 Round to +inf
10779      11 Round to 0
10780
10781   FLT_ROUNDS, on the other hand, expects the following:
10782     -1 Undefined
10783      0 Round to 0
10784      1 Round to nearest
10785      2 Round to +inf
10786      3 Round to -inf
10787
10788   To perform the conversion, we do:
10789     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10790   */
10791
10792   MachineFunction &MF = DAG.getMachineFunction();
10793   const TargetMachine &TM = MF.getTarget();
10794   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10795   unsigned StackAlignment = TFI.getStackAlignment();
10796   EVT VT = Op.getValueType();
10797   DebugLoc DL = Op.getDebugLoc();
10798
10799   // Save FP Control Word to stack slot
10800   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10801   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10802
10803
10804   MachineMemOperand *MMO =
10805    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10806                            MachineMemOperand::MOStore, 2, 2);
10807
10808   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10809   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10810                                           DAG.getVTList(MVT::Other),
10811                                           Ops, 2, MVT::i16, MMO);
10812
10813   // Load FP Control Word from stack slot
10814   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10815                             MachinePointerInfo(), false, false, false, 0);
10816
10817   // Transform as necessary
10818   SDValue CWD1 =
10819     DAG.getNode(ISD::SRL, DL, MVT::i16,
10820                 DAG.getNode(ISD::AND, DL, MVT::i16,
10821                             CWD, DAG.getConstant(0x800, MVT::i16)),
10822                 DAG.getConstant(11, MVT::i8));
10823   SDValue CWD2 =
10824     DAG.getNode(ISD::SRL, DL, MVT::i16,
10825                 DAG.getNode(ISD::AND, DL, MVT::i16,
10826                             CWD, DAG.getConstant(0x400, MVT::i16)),
10827                 DAG.getConstant(9, MVT::i8));
10828
10829   SDValue RetVal =
10830     DAG.getNode(ISD::AND, DL, MVT::i16,
10831                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10832                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10833                             DAG.getConstant(1, MVT::i16)),
10834                 DAG.getConstant(3, MVT::i16));
10835
10836
10837   return DAG.getNode((VT.getSizeInBits() < 16 ?
10838                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10839 }
10840
10841 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10842   EVT VT = Op.getValueType();
10843   EVT OpVT = VT;
10844   unsigned NumBits = VT.getSizeInBits();
10845   DebugLoc dl = Op.getDebugLoc();
10846
10847   Op = Op.getOperand(0);
10848   if (VT == MVT::i8) {
10849     // Zero extend to i32 since there is not an i8 bsr.
10850     OpVT = MVT::i32;
10851     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10852   }
10853
10854   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10855   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10856   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10857
10858   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10859   SDValue Ops[] = {
10860     Op,
10861     DAG.getConstant(NumBits+NumBits-1, OpVT),
10862     DAG.getConstant(X86::COND_E, MVT::i8),
10863     Op.getValue(1)
10864   };
10865   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10866
10867   // Finally xor with NumBits-1.
10868   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10869
10870   if (VT == MVT::i8)
10871     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10872   return Op;
10873 }
10874
10875 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10876   EVT VT = Op.getValueType();
10877   EVT OpVT = VT;
10878   unsigned NumBits = VT.getSizeInBits();
10879   DebugLoc dl = Op.getDebugLoc();
10880
10881   Op = Op.getOperand(0);
10882   if (VT == MVT::i8) {
10883     // Zero extend to i32 since there is not an i8 bsr.
10884     OpVT = MVT::i32;
10885     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10886   }
10887
10888   // Issue a bsr (scan bits in reverse).
10889   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10890   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10891
10892   // And xor with NumBits-1.
10893   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10894
10895   if (VT == MVT::i8)
10896     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10897   return Op;
10898 }
10899
10900 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10901   EVT VT = Op.getValueType();
10902   unsigned NumBits = VT.getSizeInBits();
10903   DebugLoc dl = Op.getDebugLoc();
10904   Op = Op.getOperand(0);
10905
10906   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10907   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10908   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10909
10910   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10911   SDValue Ops[] = {
10912     Op,
10913     DAG.getConstant(NumBits, VT),
10914     DAG.getConstant(X86::COND_E, MVT::i8),
10915     Op.getValue(1)
10916   };
10917   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10918 }
10919
10920 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10921 // ones, and then concatenate the result back.
10922 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10923   EVT VT = Op.getValueType();
10924
10925   assert(VT.is256BitVector() && VT.isInteger() &&
10926          "Unsupported value type for operation");
10927
10928   unsigned NumElems = VT.getVectorNumElements();
10929   DebugLoc dl = Op.getDebugLoc();
10930
10931   // Extract the LHS vectors
10932   SDValue LHS = Op.getOperand(0);
10933   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10934   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10935
10936   // Extract the RHS vectors
10937   SDValue RHS = Op.getOperand(1);
10938   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10939   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10940
10941   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10942   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10943
10944   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10945                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10946                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10947 }
10948
10949 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10950   assert(Op.getValueType().is256BitVector() &&
10951          Op.getValueType().isInteger() &&
10952          "Only handle AVX 256-bit vector integer operation");
10953   return Lower256IntArith(Op, DAG);
10954 }
10955
10956 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10957   assert(Op.getValueType().is256BitVector() &&
10958          Op.getValueType().isInteger() &&
10959          "Only handle AVX 256-bit vector integer operation");
10960   return Lower256IntArith(Op, DAG);
10961 }
10962
10963 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10964                         SelectionDAG &DAG) {
10965   EVT VT = Op.getValueType();
10966
10967   // Decompose 256-bit ops into smaller 128-bit ops.
10968   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10969     return Lower256IntArith(Op, DAG);
10970
10971   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10972          "Only know how to lower V2I64/V4I64 multiply");
10973
10974   DebugLoc dl = Op.getDebugLoc();
10975
10976   //  Ahi = psrlqi(a, 32);
10977   //  Bhi = psrlqi(b, 32);
10978   //
10979   //  AloBlo = pmuludq(a, b);
10980   //  AloBhi = pmuludq(a, Bhi);
10981   //  AhiBlo = pmuludq(Ahi, b);
10982
10983   //  AloBhi = psllqi(AloBhi, 32);
10984   //  AhiBlo = psllqi(AhiBlo, 32);
10985   //  return AloBlo + AloBhi + AhiBlo;
10986
10987   SDValue A = Op.getOperand(0);
10988   SDValue B = Op.getOperand(1);
10989
10990   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10991
10992   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10993   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10994
10995   // Bit cast to 32-bit vectors for MULUDQ
10996   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10997   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10998   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10999   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11000   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11001
11002   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11003   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11004   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11005
11006   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11007   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11008
11009   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11010   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11011 }
11012
11013 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11014
11015   EVT VT = Op.getValueType();
11016   DebugLoc dl = Op.getDebugLoc();
11017   SDValue R = Op.getOperand(0);
11018   SDValue Amt = Op.getOperand(1);
11019   LLVMContext *Context = DAG.getContext();
11020
11021   if (!Subtarget->hasSSE2())
11022     return SDValue();
11023
11024   // Optimize shl/srl/sra with constant shift amount.
11025   if (isSplatVector(Amt.getNode())) {
11026     SDValue SclrAmt = Amt->getOperand(0);
11027     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11028       uint64_t ShiftAmt = C->getZExtValue();
11029
11030       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11031           (Subtarget->hasAVX2() &&
11032            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11033         if (Op.getOpcode() == ISD::SHL)
11034           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11035                              DAG.getConstant(ShiftAmt, MVT::i32));
11036         if (Op.getOpcode() == ISD::SRL)
11037           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11038                              DAG.getConstant(ShiftAmt, MVT::i32));
11039         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11040           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11041                              DAG.getConstant(ShiftAmt, MVT::i32));
11042       }
11043
11044       if (VT == MVT::v16i8) {
11045         if (Op.getOpcode() == ISD::SHL) {
11046           // Make a large shift.
11047           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11048                                     DAG.getConstant(ShiftAmt, MVT::i32));
11049           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11050           // Zero out the rightmost bits.
11051           SmallVector<SDValue, 16> V(16,
11052                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11053                                                      MVT::i8));
11054           return DAG.getNode(ISD::AND, dl, VT, SHL,
11055                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11056         }
11057         if (Op.getOpcode() == ISD::SRL) {
11058           // Make a large shift.
11059           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11060                                     DAG.getConstant(ShiftAmt, MVT::i32));
11061           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11062           // Zero out the leftmost bits.
11063           SmallVector<SDValue, 16> V(16,
11064                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11065                                                      MVT::i8));
11066           return DAG.getNode(ISD::AND, dl, VT, SRL,
11067                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11068         }
11069         if (Op.getOpcode() == ISD::SRA) {
11070           if (ShiftAmt == 7) {
11071             // R s>> 7  ===  R s< 0
11072             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11073             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11074           }
11075
11076           // R s>> a === ((R u>> a) ^ m) - m
11077           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11078           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11079                                                          MVT::i8));
11080           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11081           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11082           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11083           return Res;
11084         }
11085         llvm_unreachable("Unknown shift opcode.");
11086       }
11087
11088       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11089         if (Op.getOpcode() == ISD::SHL) {
11090           // Make a large shift.
11091           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11092                                     DAG.getConstant(ShiftAmt, MVT::i32));
11093           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11094           // Zero out the rightmost bits.
11095           SmallVector<SDValue, 32> V(32,
11096                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11097                                                      MVT::i8));
11098           return DAG.getNode(ISD::AND, dl, VT, SHL,
11099                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11100         }
11101         if (Op.getOpcode() == ISD::SRL) {
11102           // Make a large shift.
11103           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11104                                     DAG.getConstant(ShiftAmt, MVT::i32));
11105           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11106           // Zero out the leftmost bits.
11107           SmallVector<SDValue, 32> V(32,
11108                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11109                                                      MVT::i8));
11110           return DAG.getNode(ISD::AND, dl, VT, SRL,
11111                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11112         }
11113         if (Op.getOpcode() == ISD::SRA) {
11114           if (ShiftAmt == 7) {
11115             // R s>> 7  ===  R s< 0
11116             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11117             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11118           }
11119
11120           // R s>> a === ((R u>> a) ^ m) - m
11121           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11122           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11123                                                          MVT::i8));
11124           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11125           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11126           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11127           return Res;
11128         }
11129         llvm_unreachable("Unknown shift opcode.");
11130       }
11131     }
11132   }
11133
11134   // Lower SHL with variable shift amount.
11135   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11136     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11137                      DAG.getConstant(23, MVT::i32));
11138
11139     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11140     Constant *C = ConstantDataVector::get(*Context, CV);
11141     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11142     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11143                                  MachinePointerInfo::getConstantPool(),
11144                                  false, false, false, 16);
11145
11146     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11147     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11148     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11149     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11150   }
11151   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11152     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11153
11154     // a = a << 5;
11155     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11156                      DAG.getConstant(5, MVT::i32));
11157     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11158
11159     // Turn 'a' into a mask suitable for VSELECT
11160     SDValue VSelM = DAG.getConstant(0x80, VT);
11161     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11162     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11163
11164     SDValue CM1 = DAG.getConstant(0x0f, VT);
11165     SDValue CM2 = DAG.getConstant(0x3f, VT);
11166
11167     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11168     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11169     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11170                             DAG.getConstant(4, MVT::i32), DAG);
11171     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11172     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11173
11174     // a += a
11175     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11176     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11177     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11178
11179     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11180     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11181     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11182                             DAG.getConstant(2, MVT::i32), DAG);
11183     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11184     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11185
11186     // a += a
11187     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11188     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11189     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11190
11191     // return VSELECT(r, r+r, a);
11192     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11193                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11194     return R;
11195   }
11196
11197   // Decompose 256-bit shifts into smaller 128-bit shifts.
11198   if (VT.is256BitVector()) {
11199     unsigned NumElems = VT.getVectorNumElements();
11200     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11201     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11202
11203     // Extract the two vectors
11204     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11205     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11206
11207     // Recreate the shift amount vectors
11208     SDValue Amt1, Amt2;
11209     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11210       // Constant shift amount
11211       SmallVector<SDValue, 4> Amt1Csts;
11212       SmallVector<SDValue, 4> Amt2Csts;
11213       for (unsigned i = 0; i != NumElems/2; ++i)
11214         Amt1Csts.push_back(Amt->getOperand(i));
11215       for (unsigned i = NumElems/2; i != NumElems; ++i)
11216         Amt2Csts.push_back(Amt->getOperand(i));
11217
11218       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11219                                  &Amt1Csts[0], NumElems/2);
11220       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11221                                  &Amt2Csts[0], NumElems/2);
11222     } else {
11223       // Variable shift amount
11224       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11225       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11226     }
11227
11228     // Issue new vector shifts for the smaller types
11229     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11230     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11231
11232     // Concatenate the result back
11233     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11234   }
11235
11236   return SDValue();
11237 }
11238
11239 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11240   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11241   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11242   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11243   // has only one use.
11244   SDNode *N = Op.getNode();
11245   SDValue LHS = N->getOperand(0);
11246   SDValue RHS = N->getOperand(1);
11247   unsigned BaseOp = 0;
11248   unsigned Cond = 0;
11249   DebugLoc DL = Op.getDebugLoc();
11250   switch (Op.getOpcode()) {
11251   default: llvm_unreachable("Unknown ovf instruction!");
11252   case ISD::SADDO:
11253     // A subtract of one will be selected as a INC. Note that INC doesn't
11254     // set CF, so we can't do this for UADDO.
11255     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11256       if (C->isOne()) {
11257         BaseOp = X86ISD::INC;
11258         Cond = X86::COND_O;
11259         break;
11260       }
11261     BaseOp = X86ISD::ADD;
11262     Cond = X86::COND_O;
11263     break;
11264   case ISD::UADDO:
11265     BaseOp = X86ISD::ADD;
11266     Cond = X86::COND_B;
11267     break;
11268   case ISD::SSUBO:
11269     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11270     // set CF, so we can't do this for USUBO.
11271     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11272       if (C->isOne()) {
11273         BaseOp = X86ISD::DEC;
11274         Cond = X86::COND_O;
11275         break;
11276       }
11277     BaseOp = X86ISD::SUB;
11278     Cond = X86::COND_O;
11279     break;
11280   case ISD::USUBO:
11281     BaseOp = X86ISD::SUB;
11282     Cond = X86::COND_B;
11283     break;
11284   case ISD::SMULO:
11285     BaseOp = X86ISD::SMUL;
11286     Cond = X86::COND_O;
11287     break;
11288   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11289     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11290                                  MVT::i32);
11291     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11292
11293     SDValue SetCC =
11294       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11295                   DAG.getConstant(X86::COND_O, MVT::i32),
11296                   SDValue(Sum.getNode(), 2));
11297
11298     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11299   }
11300   }
11301
11302   // Also sets EFLAGS.
11303   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11304   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11305
11306   SDValue SetCC =
11307     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11308                 DAG.getConstant(Cond, MVT::i32),
11309                 SDValue(Sum.getNode(), 1));
11310
11311   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11312 }
11313
11314 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11315                                                   SelectionDAG &DAG) const {
11316   DebugLoc dl = Op.getDebugLoc();
11317   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11318   EVT VT = Op.getValueType();
11319
11320   if (!Subtarget->hasSSE2() || !VT.isVector())
11321     return SDValue();
11322
11323   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11324                       ExtraVT.getScalarType().getSizeInBits();
11325   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11326
11327   switch (VT.getSimpleVT().SimpleTy) {
11328     default: return SDValue();
11329     case MVT::v8i32:
11330     case MVT::v16i16:
11331       if (!Subtarget->hasAVX())
11332         return SDValue();
11333       if (!Subtarget->hasAVX2()) {
11334         // needs to be split
11335         unsigned NumElems = VT.getVectorNumElements();
11336
11337         // Extract the LHS vectors
11338         SDValue LHS = Op.getOperand(0);
11339         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11340         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11341
11342         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11343         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11344
11345         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11346         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11347         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11348                                    ExtraNumElems/2);
11349         SDValue Extra = DAG.getValueType(ExtraVT);
11350
11351         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11352         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11353
11354         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11355       }
11356       // fall through
11357     case MVT::v4i32:
11358     case MVT::v8i16: {
11359       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11360                                          Op.getOperand(0), ShAmt, DAG);
11361       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11362     }
11363   }
11364 }
11365
11366
11367 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11368                               SelectionDAG &DAG) {
11369   DebugLoc dl = Op.getDebugLoc();
11370
11371   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11372   // There isn't any reason to disable it if the target processor supports it.
11373   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11374     SDValue Chain = Op.getOperand(0);
11375     SDValue Zero = DAG.getConstant(0, MVT::i32);
11376     SDValue Ops[] = {
11377       DAG.getRegister(X86::ESP, MVT::i32), // Base
11378       DAG.getTargetConstant(1, MVT::i8),   // Scale
11379       DAG.getRegister(0, MVT::i32),        // Index
11380       DAG.getTargetConstant(0, MVT::i32),  // Disp
11381       DAG.getRegister(0, MVT::i32),        // Segment.
11382       Zero,
11383       Chain
11384     };
11385     SDNode *Res =
11386       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11387                           array_lengthof(Ops));
11388     return SDValue(Res, 0);
11389   }
11390
11391   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11392   if (!isDev)
11393     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11394
11395   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11396   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11397   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11398   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11399
11400   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11401   if (!Op1 && !Op2 && !Op3 && Op4)
11402     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11403
11404   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11405   if (Op1 && !Op2 && !Op3 && !Op4)
11406     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11407
11408   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11409   //           (MFENCE)>;
11410   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11411 }
11412
11413 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11414                                  SelectionDAG &DAG) {
11415   DebugLoc dl = Op.getDebugLoc();
11416   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11417     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11418   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11419     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11420
11421   // The only fence that needs an instruction is a sequentially-consistent
11422   // cross-thread fence.
11423   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11424     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11425     // no-sse2). There isn't any reason to disable it if the target processor
11426     // supports it.
11427     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11428       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11429
11430     SDValue Chain = Op.getOperand(0);
11431     SDValue Zero = DAG.getConstant(0, MVT::i32);
11432     SDValue Ops[] = {
11433       DAG.getRegister(X86::ESP, MVT::i32), // Base
11434       DAG.getTargetConstant(1, MVT::i8),   // Scale
11435       DAG.getRegister(0, MVT::i32),        // Index
11436       DAG.getTargetConstant(0, MVT::i32),  // Disp
11437       DAG.getRegister(0, MVT::i32),        // Segment.
11438       Zero,
11439       Chain
11440     };
11441     SDNode *Res =
11442       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11443                          array_lengthof(Ops));
11444     return SDValue(Res, 0);
11445   }
11446
11447   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11448   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11449 }
11450
11451
11452 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11453                              SelectionDAG &DAG) {
11454   EVT T = Op.getValueType();
11455   DebugLoc DL = Op.getDebugLoc();
11456   unsigned Reg = 0;
11457   unsigned size = 0;
11458   switch(T.getSimpleVT().SimpleTy) {
11459   default: llvm_unreachable("Invalid value type!");
11460   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11461   case MVT::i16: Reg = X86::AX;  size = 2; break;
11462   case MVT::i32: Reg = X86::EAX; size = 4; break;
11463   case MVT::i64:
11464     assert(Subtarget->is64Bit() && "Node not type legal!");
11465     Reg = X86::RAX; size = 8;
11466     break;
11467   }
11468   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11469                                     Op.getOperand(2), SDValue());
11470   SDValue Ops[] = { cpIn.getValue(0),
11471                     Op.getOperand(1),
11472                     Op.getOperand(3),
11473                     DAG.getTargetConstant(size, MVT::i8),
11474                     cpIn.getValue(1) };
11475   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11476   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11477   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11478                                            Ops, 5, T, MMO);
11479   SDValue cpOut =
11480     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11481   return cpOut;
11482 }
11483
11484 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11485                                      SelectionDAG &DAG) {
11486   assert(Subtarget->is64Bit() && "Result not type legalized?");
11487   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11488   SDValue TheChain = Op.getOperand(0);
11489   DebugLoc dl = Op.getDebugLoc();
11490   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11491   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11492   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11493                                    rax.getValue(2));
11494   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11495                             DAG.getConstant(32, MVT::i8));
11496   SDValue Ops[] = {
11497     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11498     rdx.getValue(1)
11499   };
11500   return DAG.getMergeValues(Ops, 2, dl);
11501 }
11502
11503 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11504   EVT SrcVT = Op.getOperand(0).getValueType();
11505   EVT DstVT = Op.getValueType();
11506   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11507          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11508   assert((DstVT == MVT::i64 ||
11509           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11510          "Unexpected custom BITCAST");
11511   // i64 <=> MMX conversions are Legal.
11512   if (SrcVT==MVT::i64 && DstVT.isVector())
11513     return Op;
11514   if (DstVT==MVT::i64 && SrcVT.isVector())
11515     return Op;
11516   // MMX <=> MMX conversions are Legal.
11517   if (SrcVT.isVector() && DstVT.isVector())
11518     return Op;
11519   // All other conversions need to be expanded.
11520   return SDValue();
11521 }
11522
11523 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11524   SDNode *Node = Op.getNode();
11525   DebugLoc dl = Node->getDebugLoc();
11526   EVT T = Node->getValueType(0);
11527   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11528                               DAG.getConstant(0, T), Node->getOperand(2));
11529   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11530                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11531                        Node->getOperand(0),
11532                        Node->getOperand(1), negOp,
11533                        cast<AtomicSDNode>(Node)->getSrcValue(),
11534                        cast<AtomicSDNode>(Node)->getAlignment(),
11535                        cast<AtomicSDNode>(Node)->getOrdering(),
11536                        cast<AtomicSDNode>(Node)->getSynchScope());
11537 }
11538
11539 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11540   SDNode *Node = Op.getNode();
11541   DebugLoc dl = Node->getDebugLoc();
11542   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11543
11544   // Convert seq_cst store -> xchg
11545   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11546   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11547   //        (The only way to get a 16-byte store is cmpxchg16b)
11548   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11549   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11550       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11551     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11552                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11553                                  Node->getOperand(0),
11554                                  Node->getOperand(1), Node->getOperand(2),
11555                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11556                                  cast<AtomicSDNode>(Node)->getOrdering(),
11557                                  cast<AtomicSDNode>(Node)->getSynchScope());
11558     return Swap.getValue(1);
11559   }
11560   // Other atomic stores have a simple pattern.
11561   return Op;
11562 }
11563
11564 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11565   EVT VT = Op.getNode()->getValueType(0);
11566
11567   // Let legalize expand this if it isn't a legal type yet.
11568   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11569     return SDValue();
11570
11571   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11572
11573   unsigned Opc;
11574   bool ExtraOp = false;
11575   switch (Op.getOpcode()) {
11576   default: llvm_unreachable("Invalid code");
11577   case ISD::ADDC: Opc = X86ISD::ADD; break;
11578   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11579   case ISD::SUBC: Opc = X86ISD::SUB; break;
11580   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11581   }
11582
11583   if (!ExtraOp)
11584     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11585                        Op.getOperand(1));
11586   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11587                      Op.getOperand(1), Op.getOperand(2));
11588 }
11589
11590 /// LowerOperation - Provide custom lowering hooks for some operations.
11591 ///
11592 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11593   switch (Op.getOpcode()) {
11594   default: llvm_unreachable("Should not custom lower this!");
11595   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11596   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11597   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11598   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11599   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11600   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11601   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11602   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11603   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11604   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11605   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11606   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11607   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11608   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11609   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11610   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11611   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11612   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11613   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11614   case ISD::SHL_PARTS:
11615   case ISD::SRA_PARTS:
11616   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11617   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11618   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11619   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11620   case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11621   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11622   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11623   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11624   case ISD::FABS:               return LowerFABS(Op, DAG);
11625   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11626   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11627   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11628   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11629   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11630   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11631   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11632   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11633   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11634   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11635   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11636   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11637   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11638   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11639   case ISD::FRAME_TO_ARGS_OFFSET:
11640                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11641   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11642   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11643   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11644   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11645   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11646   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11647   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11648   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11649   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11650   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11651   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11652   case ISD::SRA:
11653   case ISD::SRL:
11654   case ISD::SHL:                return LowerShift(Op, DAG);
11655   case ISD::SADDO:
11656   case ISD::UADDO:
11657   case ISD::SSUBO:
11658   case ISD::USUBO:
11659   case ISD::SMULO:
11660   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11661   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11662   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11663   case ISD::ADDC:
11664   case ISD::ADDE:
11665   case ISD::SUBC:
11666   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11667   case ISD::ADD:                return LowerADD(Op, DAG);
11668   case ISD::SUB:                return LowerSUB(Op, DAG);
11669   }
11670 }
11671
11672 static void ReplaceATOMIC_LOAD(SDNode *Node,
11673                                   SmallVectorImpl<SDValue> &Results,
11674                                   SelectionDAG &DAG) {
11675   DebugLoc dl = Node->getDebugLoc();
11676   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11677
11678   // Convert wide load -> cmpxchg8b/cmpxchg16b
11679   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11680   //        (The only way to get a 16-byte load is cmpxchg16b)
11681   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11682   SDValue Zero = DAG.getConstant(0, VT);
11683   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11684                                Node->getOperand(0),
11685                                Node->getOperand(1), Zero, Zero,
11686                                cast<AtomicSDNode>(Node)->getMemOperand(),
11687                                cast<AtomicSDNode>(Node)->getOrdering(),
11688                                cast<AtomicSDNode>(Node)->getSynchScope());
11689   Results.push_back(Swap.getValue(0));
11690   Results.push_back(Swap.getValue(1));
11691 }
11692
11693 static void
11694 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11695                         SelectionDAG &DAG, unsigned NewOp) {
11696   DebugLoc dl = Node->getDebugLoc();
11697   assert (Node->getValueType(0) == MVT::i64 &&
11698           "Only know how to expand i64 atomics");
11699
11700   SDValue Chain = Node->getOperand(0);
11701   SDValue In1 = Node->getOperand(1);
11702   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11703                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11704   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11705                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11706   SDValue Ops[] = { Chain, In1, In2L, In2H };
11707   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11708   SDValue Result =
11709     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11710                             cast<MemSDNode>(Node)->getMemOperand());
11711   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11712   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11713   Results.push_back(Result.getValue(2));
11714 }
11715
11716 /// ReplaceNodeResults - Replace a node with an illegal result type
11717 /// with a new node built out of custom code.
11718 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11719                                            SmallVectorImpl<SDValue>&Results,
11720                                            SelectionDAG &DAG) const {
11721   DebugLoc dl = N->getDebugLoc();
11722   switch (N->getOpcode()) {
11723   default:
11724     llvm_unreachable("Do not know how to custom type legalize this operation!");
11725   case ISD::SIGN_EXTEND_INREG:
11726   case ISD::ADDC:
11727   case ISD::ADDE:
11728   case ISD::SUBC:
11729   case ISD::SUBE:
11730     // We don't want to expand or promote these.
11731     return;
11732   case ISD::FP_TO_SINT:
11733   case ISD::FP_TO_UINT: {
11734     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11735
11736     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11737       return;
11738
11739     std::pair<SDValue,SDValue> Vals =
11740         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11741     SDValue FIST = Vals.first, StackSlot = Vals.second;
11742     if (FIST.getNode() != 0) {
11743       EVT VT = N->getValueType(0);
11744       // Return a load from the stack slot.
11745       if (StackSlot.getNode() != 0)
11746         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11747                                       MachinePointerInfo(),
11748                                       false, false, false, 0));
11749       else
11750         Results.push_back(FIST);
11751     }
11752     return;
11753   }
11754   case ISD::FP_ROUND: {
11755     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11756     Results.push_back(V);
11757     return;
11758   }
11759   case ISD::READCYCLECOUNTER: {
11760     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11761     SDValue TheChain = N->getOperand(0);
11762     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11763     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11764                                      rd.getValue(1));
11765     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11766                                      eax.getValue(2));
11767     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11768     SDValue Ops[] = { eax, edx };
11769     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11770     Results.push_back(edx.getValue(1));
11771     return;
11772   }
11773   case ISD::ATOMIC_CMP_SWAP: {
11774     EVT T = N->getValueType(0);
11775     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11776     bool Regs64bit = T == MVT::i128;
11777     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11778     SDValue cpInL, cpInH;
11779     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11780                         DAG.getConstant(0, HalfT));
11781     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11782                         DAG.getConstant(1, HalfT));
11783     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11784                              Regs64bit ? X86::RAX : X86::EAX,
11785                              cpInL, SDValue());
11786     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11787                              Regs64bit ? X86::RDX : X86::EDX,
11788                              cpInH, cpInL.getValue(1));
11789     SDValue swapInL, swapInH;
11790     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11791                           DAG.getConstant(0, HalfT));
11792     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11793                           DAG.getConstant(1, HalfT));
11794     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11795                                Regs64bit ? X86::RBX : X86::EBX,
11796                                swapInL, cpInH.getValue(1));
11797     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11798                                Regs64bit ? X86::RCX : X86::ECX,
11799                                swapInH, swapInL.getValue(1));
11800     SDValue Ops[] = { swapInH.getValue(0),
11801                       N->getOperand(1),
11802                       swapInH.getValue(1) };
11803     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11804     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11805     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11806                                   X86ISD::LCMPXCHG8_DAG;
11807     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11808                                              Ops, 3, T, MMO);
11809     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11810                                         Regs64bit ? X86::RAX : X86::EAX,
11811                                         HalfT, Result.getValue(1));
11812     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11813                                         Regs64bit ? X86::RDX : X86::EDX,
11814                                         HalfT, cpOutL.getValue(2));
11815     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11816     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11817     Results.push_back(cpOutH.getValue(1));
11818     return;
11819   }
11820   case ISD::ATOMIC_LOAD_ADD:
11821   case ISD::ATOMIC_LOAD_AND:
11822   case ISD::ATOMIC_LOAD_NAND:
11823   case ISD::ATOMIC_LOAD_OR:
11824   case ISD::ATOMIC_LOAD_SUB:
11825   case ISD::ATOMIC_LOAD_XOR:
11826   case ISD::ATOMIC_LOAD_MAX:
11827   case ISD::ATOMIC_LOAD_MIN:
11828   case ISD::ATOMIC_LOAD_UMAX:
11829   case ISD::ATOMIC_LOAD_UMIN:
11830   case ISD::ATOMIC_SWAP: {
11831     unsigned Opc;
11832     switch (N->getOpcode()) {
11833     default: llvm_unreachable("Unexpected opcode");
11834     case ISD::ATOMIC_LOAD_ADD:
11835       Opc = X86ISD::ATOMADD64_DAG;
11836       break;
11837     case ISD::ATOMIC_LOAD_AND:
11838       Opc = X86ISD::ATOMAND64_DAG;
11839       break;
11840     case ISD::ATOMIC_LOAD_NAND:
11841       Opc = X86ISD::ATOMNAND64_DAG;
11842       break;
11843     case ISD::ATOMIC_LOAD_OR:
11844       Opc = X86ISD::ATOMOR64_DAG;
11845       break;
11846     case ISD::ATOMIC_LOAD_SUB:
11847       Opc = X86ISD::ATOMSUB64_DAG;
11848       break;
11849     case ISD::ATOMIC_LOAD_XOR:
11850       Opc = X86ISD::ATOMXOR64_DAG;
11851       break;
11852     case ISD::ATOMIC_LOAD_MAX:
11853       Opc = X86ISD::ATOMMAX64_DAG;
11854       break;
11855     case ISD::ATOMIC_LOAD_MIN:
11856       Opc = X86ISD::ATOMMIN64_DAG;
11857       break;
11858     case ISD::ATOMIC_LOAD_UMAX:
11859       Opc = X86ISD::ATOMUMAX64_DAG;
11860       break;
11861     case ISD::ATOMIC_LOAD_UMIN:
11862       Opc = X86ISD::ATOMUMIN64_DAG;
11863       break;
11864     case ISD::ATOMIC_SWAP:
11865       Opc = X86ISD::ATOMSWAP64_DAG;
11866       break;
11867     }
11868     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11869     return;
11870   }
11871   case ISD::ATOMIC_LOAD:
11872     ReplaceATOMIC_LOAD(N, Results, DAG);
11873   }
11874 }
11875
11876 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11877   switch (Opcode) {
11878   default: return NULL;
11879   case X86ISD::BSF:                return "X86ISD::BSF";
11880   case X86ISD::BSR:                return "X86ISD::BSR";
11881   case X86ISD::SHLD:               return "X86ISD::SHLD";
11882   case X86ISD::SHRD:               return "X86ISD::SHRD";
11883   case X86ISD::FAND:               return "X86ISD::FAND";
11884   case X86ISD::FOR:                return "X86ISD::FOR";
11885   case X86ISD::FXOR:               return "X86ISD::FXOR";
11886   case X86ISD::FSRL:               return "X86ISD::FSRL";
11887   case X86ISD::FILD:               return "X86ISD::FILD";
11888   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11889   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11890   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11891   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11892   case X86ISD::FLD:                return "X86ISD::FLD";
11893   case X86ISD::FST:                return "X86ISD::FST";
11894   case X86ISD::CALL:               return "X86ISD::CALL";
11895   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11896   case X86ISD::BT:                 return "X86ISD::BT";
11897   case X86ISD::CMP:                return "X86ISD::CMP";
11898   case X86ISD::COMI:               return "X86ISD::COMI";
11899   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11900   case X86ISD::SETCC:              return "X86ISD::SETCC";
11901   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11902   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11903   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11904   case X86ISD::CMOV:               return "X86ISD::CMOV";
11905   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11906   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11907   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11908   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11909   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11910   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11911   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11912   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11913   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11914   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11915   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11916   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11917   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11918   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11919   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11920   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11921   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11922   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11923   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11924   case X86ISD::HADD:               return "X86ISD::HADD";
11925   case X86ISD::HSUB:               return "X86ISD::HSUB";
11926   case X86ISD::FHADD:              return "X86ISD::FHADD";
11927   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11928   case X86ISD::FMAX:               return "X86ISD::FMAX";
11929   case X86ISD::FMIN:               return "X86ISD::FMIN";
11930   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11931   case X86ISD::FMINC:              return "X86ISD::FMINC";
11932   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11933   case X86ISD::FRCP:               return "X86ISD::FRCP";
11934   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11935   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11936   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11937   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11938   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11939   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11940   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11941   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11942   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11943   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11944   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11945   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11946   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11947   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11948   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11949   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11950   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11951   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11952   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11953   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11954   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
11955   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
11956   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11957   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11958   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11959   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11960   case X86ISD::VSHL:               return "X86ISD::VSHL";
11961   case X86ISD::VSRL:               return "X86ISD::VSRL";
11962   case X86ISD::VSRA:               return "X86ISD::VSRA";
11963   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11964   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11965   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11966   case X86ISD::CMPP:               return "X86ISD::CMPP";
11967   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11968   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11969   case X86ISD::ADD:                return "X86ISD::ADD";
11970   case X86ISD::SUB:                return "X86ISD::SUB";
11971   case X86ISD::ADC:                return "X86ISD::ADC";
11972   case X86ISD::SBB:                return "X86ISD::SBB";
11973   case X86ISD::SMUL:               return "X86ISD::SMUL";
11974   case X86ISD::UMUL:               return "X86ISD::UMUL";
11975   case X86ISD::INC:                return "X86ISD::INC";
11976   case X86ISD::DEC:                return "X86ISD::DEC";
11977   case X86ISD::OR:                 return "X86ISD::OR";
11978   case X86ISD::XOR:                return "X86ISD::XOR";
11979   case X86ISD::AND:                return "X86ISD::AND";
11980   case X86ISD::ANDN:               return "X86ISD::ANDN";
11981   case X86ISD::BLSI:               return "X86ISD::BLSI";
11982   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11983   case X86ISD::BLSR:               return "X86ISD::BLSR";
11984   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11985   case X86ISD::PTEST:              return "X86ISD::PTEST";
11986   case X86ISD::TESTP:              return "X86ISD::TESTP";
11987   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11988   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11989   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11990   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11991   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11992   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11993   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11994   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11995   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11996   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11997   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11998   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11999   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12000   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12001   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12002   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12003   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12004   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12005   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12006   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12007   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12008   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12009   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12010   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12011   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12012   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12013   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12014   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12015   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12016   case X86ISD::SAHF:               return "X86ISD::SAHF";
12017   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12018   case X86ISD::FMADD:              return "X86ISD::FMADD";
12019   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12020   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12021   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12022   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12023   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12024   }
12025 }
12026
12027 // isLegalAddressingMode - Return true if the addressing mode represented
12028 // by AM is legal for this target, for a load/store of the specified type.
12029 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12030                                               Type *Ty) const {
12031   // X86 supports extremely general addressing modes.
12032   CodeModel::Model M = getTargetMachine().getCodeModel();
12033   Reloc::Model R = getTargetMachine().getRelocationModel();
12034
12035   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12036   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12037     return false;
12038
12039   if (AM.BaseGV) {
12040     unsigned GVFlags =
12041       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12042
12043     // If a reference to this global requires an extra load, we can't fold it.
12044     if (isGlobalStubReference(GVFlags))
12045       return false;
12046
12047     // If BaseGV requires a register for the PIC base, we cannot also have a
12048     // BaseReg specified.
12049     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12050       return false;
12051
12052     // If lower 4G is not available, then we must use rip-relative addressing.
12053     if ((M != CodeModel::Small || R != Reloc::Static) &&
12054         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12055       return false;
12056   }
12057
12058   switch (AM.Scale) {
12059   case 0:
12060   case 1:
12061   case 2:
12062   case 4:
12063   case 8:
12064     // These scales always work.
12065     break;
12066   case 3:
12067   case 5:
12068   case 9:
12069     // These scales are formed with basereg+scalereg.  Only accept if there is
12070     // no basereg yet.
12071     if (AM.HasBaseReg)
12072       return false;
12073     break;
12074   default:  // Other stuff never works.
12075     return false;
12076   }
12077
12078   return true;
12079 }
12080
12081
12082 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12083   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12084     return false;
12085   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12086   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12087   if (NumBits1 <= NumBits2)
12088     return false;
12089   return true;
12090 }
12091
12092 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12093   return Imm == (int32_t)Imm;
12094 }
12095
12096 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12097   // Can also use sub to handle negated immediates.
12098   return Imm == (int32_t)Imm;
12099 }
12100
12101 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12102   if (!VT1.isInteger() || !VT2.isInteger())
12103     return false;
12104   unsigned NumBits1 = VT1.getSizeInBits();
12105   unsigned NumBits2 = VT2.getSizeInBits();
12106   if (NumBits1 <= NumBits2)
12107     return false;
12108   return true;
12109 }
12110
12111 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12112   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12113   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12114 }
12115
12116 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12117   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12118   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12119 }
12120
12121 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12122   // i16 instructions are longer (0x66 prefix) and potentially slower.
12123   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12124 }
12125
12126 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12127 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12128 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12129 /// are assumed to be legal.
12130 bool
12131 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12132                                       EVT VT) const {
12133   // Very little shuffling can be done for 64-bit vectors right now.
12134   if (VT.getSizeInBits() == 64)
12135     return false;
12136
12137   // FIXME: pshufb, blends, shifts.
12138   return (VT.getVectorNumElements() == 2 ||
12139           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12140           isMOVLMask(M, VT) ||
12141           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12142           isPSHUFDMask(M, VT) ||
12143           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12144           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12145           isPALIGNRMask(M, VT, Subtarget) ||
12146           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12147           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12148           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12149           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12150 }
12151
12152 bool
12153 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12154                                           EVT VT) const {
12155   unsigned NumElts = VT.getVectorNumElements();
12156   // FIXME: This collection of masks seems suspect.
12157   if (NumElts == 2)
12158     return true;
12159   if (NumElts == 4 && VT.is128BitVector()) {
12160     return (isMOVLMask(Mask, VT)  ||
12161             isCommutedMOVLMask(Mask, VT, true) ||
12162             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12163             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12164   }
12165   return false;
12166 }
12167
12168 //===----------------------------------------------------------------------===//
12169 //                           X86 Scheduler Hooks
12170 //===----------------------------------------------------------------------===//
12171
12172 // private utility function
12173
12174 // Get CMPXCHG opcode for the specified data type.
12175 static unsigned getCmpXChgOpcode(EVT VT) {
12176   switch (VT.getSimpleVT().SimpleTy) {
12177   case MVT::i8:  return X86::LCMPXCHG8;
12178   case MVT::i16: return X86::LCMPXCHG16;
12179   case MVT::i32: return X86::LCMPXCHG32;
12180   case MVT::i64: return X86::LCMPXCHG64;
12181   default:
12182     break;
12183   }
12184   llvm_unreachable("Invalid operand size!");
12185 }
12186
12187 // Get LOAD opcode for the specified data type.
12188 static unsigned getLoadOpcode(EVT VT) {
12189   switch (VT.getSimpleVT().SimpleTy) {
12190   case MVT::i8:  return X86::MOV8rm;
12191   case MVT::i16: return X86::MOV16rm;
12192   case MVT::i32: return X86::MOV32rm;
12193   case MVT::i64: return X86::MOV64rm;
12194   default:
12195     break;
12196   }
12197   llvm_unreachable("Invalid operand size!");
12198 }
12199
12200 // Get opcode of the non-atomic one from the specified atomic instruction.
12201 static unsigned getNonAtomicOpcode(unsigned Opc) {
12202   switch (Opc) {
12203   case X86::ATOMAND8:  return X86::AND8rr;
12204   case X86::ATOMAND16: return X86::AND16rr;
12205   case X86::ATOMAND32: return X86::AND32rr;
12206   case X86::ATOMAND64: return X86::AND64rr;
12207   case X86::ATOMOR8:   return X86::OR8rr;
12208   case X86::ATOMOR16:  return X86::OR16rr;
12209   case X86::ATOMOR32:  return X86::OR32rr;
12210   case X86::ATOMOR64:  return X86::OR64rr;
12211   case X86::ATOMXOR8:  return X86::XOR8rr;
12212   case X86::ATOMXOR16: return X86::XOR16rr;
12213   case X86::ATOMXOR32: return X86::XOR32rr;
12214   case X86::ATOMXOR64: return X86::XOR64rr;
12215   }
12216   llvm_unreachable("Unhandled atomic-load-op opcode!");
12217 }
12218
12219 // Get opcode of the non-atomic one from the specified atomic instruction with
12220 // extra opcode.
12221 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12222                                                unsigned &ExtraOpc) {
12223   switch (Opc) {
12224   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12225   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12226   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12227   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12228   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12229   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12230   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12231   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12232   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12233   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12234   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12235   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12236   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12237   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12238   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12239   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12240   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12241   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12242   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12243   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12244   }
12245   llvm_unreachable("Unhandled atomic-load-op opcode!");
12246 }
12247
12248 // Get opcode of the non-atomic one from the specified atomic instruction for
12249 // 64-bit data type on 32-bit target.
12250 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12251   switch (Opc) {
12252   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12253   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12254   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12255   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12256   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12257   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12258   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12259   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12260   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12261   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12262   }
12263   llvm_unreachable("Unhandled atomic-load-op opcode!");
12264 }
12265
12266 // Get opcode of the non-atomic one from the specified atomic instruction for
12267 // 64-bit data type on 32-bit target with extra opcode.
12268 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12269                                                    unsigned &HiOpc,
12270                                                    unsigned &ExtraOpc) {
12271   switch (Opc) {
12272   case X86::ATOMNAND6432:
12273     ExtraOpc = X86::NOT32r;
12274     HiOpc = X86::AND32rr;
12275     return X86::AND32rr;
12276   }
12277   llvm_unreachable("Unhandled atomic-load-op opcode!");
12278 }
12279
12280 // Get pseudo CMOV opcode from the specified data type.
12281 static unsigned getPseudoCMOVOpc(EVT VT) {
12282   switch (VT.getSimpleVT().SimpleTy) {
12283   case MVT::i8:  return X86::CMOV_GR8;
12284   case MVT::i16: return X86::CMOV_GR16;
12285   case MVT::i32: return X86::CMOV_GR32;
12286   default:
12287     break;
12288   }
12289   llvm_unreachable("Unknown CMOV opcode!");
12290 }
12291
12292 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12293 // They will be translated into a spin-loop or compare-exchange loop from
12294 //
12295 //    ...
12296 //    dst = atomic-fetch-op MI.addr, MI.val
12297 //    ...
12298 //
12299 // to
12300 //
12301 //    ...
12302 //    EAX = LOAD MI.addr
12303 // loop:
12304 //    t1 = OP MI.val, EAX
12305 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12306 //    JNE loop
12307 // sink:
12308 //    dst = EAX
12309 //    ...
12310 MachineBasicBlock *
12311 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12312                                        MachineBasicBlock *MBB) const {
12313   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12314   DebugLoc DL = MI->getDebugLoc();
12315
12316   MachineFunction *MF = MBB->getParent();
12317   MachineRegisterInfo &MRI = MF->getRegInfo();
12318
12319   const BasicBlock *BB = MBB->getBasicBlock();
12320   MachineFunction::iterator I = MBB;
12321   ++I;
12322
12323   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12324          "Unexpected number of operands");
12325
12326   assert(MI->hasOneMemOperand() &&
12327          "Expected atomic-load-op to have one memoperand");
12328
12329   // Memory Reference
12330   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12331   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12332
12333   unsigned DstReg, SrcReg;
12334   unsigned MemOpndSlot;
12335
12336   unsigned CurOp = 0;
12337
12338   DstReg = MI->getOperand(CurOp++).getReg();
12339   MemOpndSlot = CurOp;
12340   CurOp += X86::AddrNumOperands;
12341   SrcReg = MI->getOperand(CurOp++).getReg();
12342
12343   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12344   MVT::SimpleValueType VT = *RC->vt_begin();
12345   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12346
12347   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12348   unsigned LOADOpc = getLoadOpcode(VT);
12349
12350   // For the atomic load-arith operator, we generate
12351   //
12352   //  thisMBB:
12353   //    EAX = LOAD [MI.addr]
12354   //  mainMBB:
12355   //    t1 = OP MI.val, EAX
12356   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12357   //    JNE mainMBB
12358   //  sinkMBB:
12359
12360   MachineBasicBlock *thisMBB = MBB;
12361   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12362   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12363   MF->insert(I, mainMBB);
12364   MF->insert(I, sinkMBB);
12365
12366   MachineInstrBuilder MIB;
12367
12368   // Transfer the remainder of BB and its successor edges to sinkMBB.
12369   sinkMBB->splice(sinkMBB->begin(), MBB,
12370                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12371   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12372
12373   // thisMBB:
12374   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12375   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12376     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12377   MIB.setMemRefs(MMOBegin, MMOEnd);
12378
12379   thisMBB->addSuccessor(mainMBB);
12380
12381   // mainMBB:
12382   MachineBasicBlock *origMainMBB = mainMBB;
12383   mainMBB->addLiveIn(AccPhyReg);
12384
12385   // Copy AccPhyReg as it is used more than once.
12386   unsigned AccReg = MRI.createVirtualRegister(RC);
12387   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12388     .addReg(AccPhyReg);
12389
12390   unsigned t1 = MRI.createVirtualRegister(RC);
12391   unsigned Opc = MI->getOpcode();
12392   switch (Opc) {
12393   default:
12394     llvm_unreachable("Unhandled atomic-load-op opcode!");
12395   case X86::ATOMAND8:
12396   case X86::ATOMAND16:
12397   case X86::ATOMAND32:
12398   case X86::ATOMAND64:
12399   case X86::ATOMOR8:
12400   case X86::ATOMOR16:
12401   case X86::ATOMOR32:
12402   case X86::ATOMOR64:
12403   case X86::ATOMXOR8:
12404   case X86::ATOMXOR16:
12405   case X86::ATOMXOR32:
12406   case X86::ATOMXOR64: {
12407     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12408     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12409       .addReg(AccReg);
12410     break;
12411   }
12412   case X86::ATOMNAND8:
12413   case X86::ATOMNAND16:
12414   case X86::ATOMNAND32:
12415   case X86::ATOMNAND64: {
12416     unsigned t2 = MRI.createVirtualRegister(RC);
12417     unsigned NOTOpc;
12418     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12419     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12420       .addReg(AccReg);
12421     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12422     break;
12423   }
12424   case X86::ATOMMAX8:
12425   case X86::ATOMMAX16:
12426   case X86::ATOMMAX32:
12427   case X86::ATOMMAX64:
12428   case X86::ATOMMIN8:
12429   case X86::ATOMMIN16:
12430   case X86::ATOMMIN32:
12431   case X86::ATOMMIN64:
12432   case X86::ATOMUMAX8:
12433   case X86::ATOMUMAX16:
12434   case X86::ATOMUMAX32:
12435   case X86::ATOMUMAX64:
12436   case X86::ATOMUMIN8:
12437   case X86::ATOMUMIN16:
12438   case X86::ATOMUMIN32:
12439   case X86::ATOMUMIN64: {
12440     unsigned CMPOpc;
12441     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12442
12443     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12444       .addReg(SrcReg)
12445       .addReg(AccReg);
12446
12447     if (Subtarget->hasCMov()) {
12448       if (VT != MVT::i8) {
12449         // Native support
12450         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12451           .addReg(SrcReg)
12452           .addReg(AccReg);
12453       } else {
12454         // Promote i8 to i32 to use CMOV32
12455         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12456         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12457         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12458         unsigned t2 = MRI.createVirtualRegister(RC32);
12459
12460         unsigned Undef = MRI.createVirtualRegister(RC32);
12461         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12462
12463         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12464           .addReg(Undef)
12465           .addReg(SrcReg)
12466           .addImm(X86::sub_8bit);
12467         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12468           .addReg(Undef)
12469           .addReg(AccReg)
12470           .addImm(X86::sub_8bit);
12471
12472         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12473           .addReg(SrcReg32)
12474           .addReg(AccReg32);
12475
12476         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12477           .addReg(t2, 0, X86::sub_8bit);
12478       }
12479     } else {
12480       // Use pseudo select and lower them.
12481       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12482              "Invalid atomic-load-op transformation!");
12483       unsigned SelOpc = getPseudoCMOVOpc(VT);
12484       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12485       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12486       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12487               .addReg(SrcReg).addReg(AccReg)
12488               .addImm(CC);
12489       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12490     }
12491     break;
12492   }
12493   }
12494
12495   // Copy AccPhyReg back from virtual register.
12496   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12497     .addReg(AccReg);
12498
12499   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12500   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12501     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12502   MIB.addReg(t1);
12503   MIB.setMemRefs(MMOBegin, MMOEnd);
12504
12505   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12506
12507   mainMBB->addSuccessor(origMainMBB);
12508   mainMBB->addSuccessor(sinkMBB);
12509
12510   // sinkMBB:
12511   sinkMBB->addLiveIn(AccPhyReg);
12512
12513   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12514           TII->get(TargetOpcode::COPY), DstReg)
12515     .addReg(AccPhyReg);
12516
12517   MI->eraseFromParent();
12518   return sinkMBB;
12519 }
12520
12521 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12522 // instructions. They will be translated into a spin-loop or compare-exchange
12523 // loop from
12524 //
12525 //    ...
12526 //    dst = atomic-fetch-op MI.addr, MI.val
12527 //    ...
12528 //
12529 // to
12530 //
12531 //    ...
12532 //    EAX = LOAD [MI.addr + 0]
12533 //    EDX = LOAD [MI.addr + 4]
12534 // loop:
12535 //    EBX = OP MI.val.lo, EAX
12536 //    ECX = OP MI.val.hi, EDX
12537 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12538 //    JNE loop
12539 // sink:
12540 //    dst = EDX:EAX
12541 //    ...
12542 MachineBasicBlock *
12543 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12544                                            MachineBasicBlock *MBB) const {
12545   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12546   DebugLoc DL = MI->getDebugLoc();
12547
12548   MachineFunction *MF = MBB->getParent();
12549   MachineRegisterInfo &MRI = MF->getRegInfo();
12550
12551   const BasicBlock *BB = MBB->getBasicBlock();
12552   MachineFunction::iterator I = MBB;
12553   ++I;
12554
12555   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12556          "Unexpected number of operands");
12557
12558   assert(MI->hasOneMemOperand() &&
12559          "Expected atomic-load-op32 to have one memoperand");
12560
12561   // Memory Reference
12562   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12563   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12564
12565   unsigned DstLoReg, DstHiReg;
12566   unsigned SrcLoReg, SrcHiReg;
12567   unsigned MemOpndSlot;
12568
12569   unsigned CurOp = 0;
12570
12571   DstLoReg = MI->getOperand(CurOp++).getReg();
12572   DstHiReg = MI->getOperand(CurOp++).getReg();
12573   MemOpndSlot = CurOp;
12574   CurOp += X86::AddrNumOperands;
12575   SrcLoReg = MI->getOperand(CurOp++).getReg();
12576   SrcHiReg = MI->getOperand(CurOp++).getReg();
12577
12578   const TargetRegisterClass *RC = &X86::GR32RegClass;
12579   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12580
12581   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12582   unsigned LOADOpc = X86::MOV32rm;
12583
12584   // For the atomic load-arith operator, we generate
12585   //
12586   //  thisMBB:
12587   //    EAX = LOAD [MI.addr + 0]
12588   //    EDX = LOAD [MI.addr + 4]
12589   //  mainMBB:
12590   //    EBX = OP MI.vallo, EAX
12591   //    ECX = OP MI.valhi, EDX
12592   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12593   //    JNE mainMBB
12594   //  sinkMBB:
12595
12596   MachineBasicBlock *thisMBB = MBB;
12597   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12598   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12599   MF->insert(I, mainMBB);
12600   MF->insert(I, sinkMBB);
12601
12602   MachineInstrBuilder MIB;
12603
12604   // Transfer the remainder of BB and its successor edges to sinkMBB.
12605   sinkMBB->splice(sinkMBB->begin(), MBB,
12606                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12607   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12608
12609   // thisMBB:
12610   // Lo
12611   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12612   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12613     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12614   MIB.setMemRefs(MMOBegin, MMOEnd);
12615   // Hi
12616   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12617   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12618     if (i == X86::AddrDisp)
12619       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12620     else
12621       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12622   }
12623   MIB.setMemRefs(MMOBegin, MMOEnd);
12624
12625   thisMBB->addSuccessor(mainMBB);
12626
12627   // mainMBB:
12628   MachineBasicBlock *origMainMBB = mainMBB;
12629   mainMBB->addLiveIn(X86::EAX);
12630   mainMBB->addLiveIn(X86::EDX);
12631
12632   // Copy EDX:EAX as they are used more than once.
12633   unsigned LoReg = MRI.createVirtualRegister(RC);
12634   unsigned HiReg = MRI.createVirtualRegister(RC);
12635   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12636   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12637
12638   unsigned t1L = MRI.createVirtualRegister(RC);
12639   unsigned t1H = MRI.createVirtualRegister(RC);
12640
12641   unsigned Opc = MI->getOpcode();
12642   switch (Opc) {
12643   default:
12644     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12645   case X86::ATOMAND6432:
12646   case X86::ATOMOR6432:
12647   case X86::ATOMXOR6432:
12648   case X86::ATOMADD6432:
12649   case X86::ATOMSUB6432: {
12650     unsigned HiOpc;
12651     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12652     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12653     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12654     break;
12655   }
12656   case X86::ATOMNAND6432: {
12657     unsigned HiOpc, NOTOpc;
12658     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12659     unsigned t2L = MRI.createVirtualRegister(RC);
12660     unsigned t2H = MRI.createVirtualRegister(RC);
12661     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12662     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12663     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12664     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12665     break;
12666   }
12667   case X86::ATOMMAX6432:
12668   case X86::ATOMMIN6432:
12669   case X86::ATOMUMAX6432:
12670   case X86::ATOMUMIN6432: {
12671     unsigned HiOpc;
12672     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12673     unsigned cL = MRI.createVirtualRegister(RC8);
12674     unsigned cH = MRI.createVirtualRegister(RC8);
12675     unsigned cL32 = MRI.createVirtualRegister(RC);
12676     unsigned cH32 = MRI.createVirtualRegister(RC);
12677     unsigned cc = MRI.createVirtualRegister(RC);
12678     // cl := cmp src_lo, lo
12679     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12680       .addReg(SrcLoReg).addReg(LoReg);
12681     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12682     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12683     // ch := cmp src_hi, hi
12684     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12685       .addReg(SrcHiReg).addReg(HiReg);
12686     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12687     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12688     // cc := if (src_hi == hi) ? cl : ch;
12689     if (Subtarget->hasCMov()) {
12690       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12691         .addReg(cH32).addReg(cL32);
12692     } else {
12693       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12694               .addReg(cH32).addReg(cL32)
12695               .addImm(X86::COND_E);
12696       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12697     }
12698     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12699     if (Subtarget->hasCMov()) {
12700       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12701         .addReg(SrcLoReg).addReg(LoReg);
12702       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12703         .addReg(SrcHiReg).addReg(HiReg);
12704     } else {
12705       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12706               .addReg(SrcLoReg).addReg(LoReg)
12707               .addImm(X86::COND_NE);
12708       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12709       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12710               .addReg(SrcHiReg).addReg(HiReg)
12711               .addImm(X86::COND_NE);
12712       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12713     }
12714     break;
12715   }
12716   case X86::ATOMSWAP6432: {
12717     unsigned HiOpc;
12718     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12719     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12720     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12721     break;
12722   }
12723   }
12724
12725   // Copy EDX:EAX back from HiReg:LoReg
12726   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12727   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12728   // Copy ECX:EBX from t1H:t1L
12729   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12730   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12731
12732   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12733   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12734     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12735   MIB.setMemRefs(MMOBegin, MMOEnd);
12736
12737   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12738
12739   mainMBB->addSuccessor(origMainMBB);
12740   mainMBB->addSuccessor(sinkMBB);
12741
12742   // sinkMBB:
12743   sinkMBB->addLiveIn(X86::EAX);
12744   sinkMBB->addLiveIn(X86::EDX);
12745
12746   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12747           TII->get(TargetOpcode::COPY), DstLoReg)
12748     .addReg(X86::EAX);
12749   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12750           TII->get(TargetOpcode::COPY), DstHiReg)
12751     .addReg(X86::EDX);
12752
12753   MI->eraseFromParent();
12754   return sinkMBB;
12755 }
12756
12757 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12758 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12759 // in the .td file.
12760 MachineBasicBlock *
12761 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12762                             unsigned numArgs, bool memArg) const {
12763   assert(Subtarget->hasSSE42() &&
12764          "Target must have SSE4.2 or AVX features enabled");
12765
12766   DebugLoc dl = MI->getDebugLoc();
12767   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12768   unsigned Opc;
12769   if (!Subtarget->hasAVX()) {
12770     if (memArg)
12771       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12772     else
12773       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12774   } else {
12775     if (memArg)
12776       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12777     else
12778       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12779   }
12780
12781   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12782   for (unsigned i = 0; i < numArgs; ++i) {
12783     MachineOperand &Op = MI->getOperand(i+1);
12784     if (!(Op.isReg() && Op.isImplicit()))
12785       MIB.addOperand(Op);
12786   }
12787   BuildMI(*BB, MI, dl,
12788     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12789     .addReg(X86::XMM0);
12790
12791   MI->eraseFromParent();
12792   return BB;
12793 }
12794
12795 MachineBasicBlock *
12796 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12797   DebugLoc dl = MI->getDebugLoc();
12798   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12799
12800   // Address into RAX/EAX, other two args into ECX, EDX.
12801   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12802   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12803   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12804   for (int i = 0; i < X86::AddrNumOperands; ++i)
12805     MIB.addOperand(MI->getOperand(i));
12806
12807   unsigned ValOps = X86::AddrNumOperands;
12808   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12809     .addReg(MI->getOperand(ValOps).getReg());
12810   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12811     .addReg(MI->getOperand(ValOps+1).getReg());
12812
12813   // The instruction doesn't actually take any operands though.
12814   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12815
12816   MI->eraseFromParent(); // The pseudo is gone now.
12817   return BB;
12818 }
12819
12820 MachineBasicBlock *
12821 X86TargetLowering::EmitVAARG64WithCustomInserter(
12822                    MachineInstr *MI,
12823                    MachineBasicBlock *MBB) const {
12824   // Emit va_arg instruction on X86-64.
12825
12826   // Operands to this pseudo-instruction:
12827   // 0  ) Output        : destination address (reg)
12828   // 1-5) Input         : va_list address (addr, i64mem)
12829   // 6  ) ArgSize       : Size (in bytes) of vararg type
12830   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12831   // 8  ) Align         : Alignment of type
12832   // 9  ) EFLAGS (implicit-def)
12833
12834   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12835   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12836
12837   unsigned DestReg = MI->getOperand(0).getReg();
12838   MachineOperand &Base = MI->getOperand(1);
12839   MachineOperand &Scale = MI->getOperand(2);
12840   MachineOperand &Index = MI->getOperand(3);
12841   MachineOperand &Disp = MI->getOperand(4);
12842   MachineOperand &Segment = MI->getOperand(5);
12843   unsigned ArgSize = MI->getOperand(6).getImm();
12844   unsigned ArgMode = MI->getOperand(7).getImm();
12845   unsigned Align = MI->getOperand(8).getImm();
12846
12847   // Memory Reference
12848   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12849   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12850   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12851
12852   // Machine Information
12853   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12854   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12855   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12856   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12857   DebugLoc DL = MI->getDebugLoc();
12858
12859   // struct va_list {
12860   //   i32   gp_offset
12861   //   i32   fp_offset
12862   //   i64   overflow_area (address)
12863   //   i64   reg_save_area (address)
12864   // }
12865   // sizeof(va_list) = 24
12866   // alignment(va_list) = 8
12867
12868   unsigned TotalNumIntRegs = 6;
12869   unsigned TotalNumXMMRegs = 8;
12870   bool UseGPOffset = (ArgMode == 1);
12871   bool UseFPOffset = (ArgMode == 2);
12872   unsigned MaxOffset = TotalNumIntRegs * 8 +
12873                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12874
12875   /* Align ArgSize to a multiple of 8 */
12876   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12877   bool NeedsAlign = (Align > 8);
12878
12879   MachineBasicBlock *thisMBB = MBB;
12880   MachineBasicBlock *overflowMBB;
12881   MachineBasicBlock *offsetMBB;
12882   MachineBasicBlock *endMBB;
12883
12884   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12885   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12886   unsigned OffsetReg = 0;
12887
12888   if (!UseGPOffset && !UseFPOffset) {
12889     // If we only pull from the overflow region, we don't create a branch.
12890     // We don't need to alter control flow.
12891     OffsetDestReg = 0; // unused
12892     OverflowDestReg = DestReg;
12893
12894     offsetMBB = NULL;
12895     overflowMBB = thisMBB;
12896     endMBB = thisMBB;
12897   } else {
12898     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12899     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12900     // If not, pull from overflow_area. (branch to overflowMBB)
12901     //
12902     //       thisMBB
12903     //         |     .
12904     //         |        .
12905     //     offsetMBB   overflowMBB
12906     //         |        .
12907     //         |     .
12908     //        endMBB
12909
12910     // Registers for the PHI in endMBB
12911     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12912     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12913
12914     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12915     MachineFunction *MF = MBB->getParent();
12916     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12917     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12918     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12919
12920     MachineFunction::iterator MBBIter = MBB;
12921     ++MBBIter;
12922
12923     // Insert the new basic blocks
12924     MF->insert(MBBIter, offsetMBB);
12925     MF->insert(MBBIter, overflowMBB);
12926     MF->insert(MBBIter, endMBB);
12927
12928     // Transfer the remainder of MBB and its successor edges to endMBB.
12929     endMBB->splice(endMBB->begin(), thisMBB,
12930                     llvm::next(MachineBasicBlock::iterator(MI)),
12931                     thisMBB->end());
12932     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12933
12934     // Make offsetMBB and overflowMBB successors of thisMBB
12935     thisMBB->addSuccessor(offsetMBB);
12936     thisMBB->addSuccessor(overflowMBB);
12937
12938     // endMBB is a successor of both offsetMBB and overflowMBB
12939     offsetMBB->addSuccessor(endMBB);
12940     overflowMBB->addSuccessor(endMBB);
12941
12942     // Load the offset value into a register
12943     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12944     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12945       .addOperand(Base)
12946       .addOperand(Scale)
12947       .addOperand(Index)
12948       .addDisp(Disp, UseFPOffset ? 4 : 0)
12949       .addOperand(Segment)
12950       .setMemRefs(MMOBegin, MMOEnd);
12951
12952     // Check if there is enough room left to pull this argument.
12953     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12954       .addReg(OffsetReg)
12955       .addImm(MaxOffset + 8 - ArgSizeA8);
12956
12957     // Branch to "overflowMBB" if offset >= max
12958     // Fall through to "offsetMBB" otherwise
12959     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12960       .addMBB(overflowMBB);
12961   }
12962
12963   // In offsetMBB, emit code to use the reg_save_area.
12964   if (offsetMBB) {
12965     assert(OffsetReg != 0);
12966
12967     // Read the reg_save_area address.
12968     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12969     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12970       .addOperand(Base)
12971       .addOperand(Scale)
12972       .addOperand(Index)
12973       .addDisp(Disp, 16)
12974       .addOperand(Segment)
12975       .setMemRefs(MMOBegin, MMOEnd);
12976
12977     // Zero-extend the offset
12978     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12979       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12980         .addImm(0)
12981         .addReg(OffsetReg)
12982         .addImm(X86::sub_32bit);
12983
12984     // Add the offset to the reg_save_area to get the final address.
12985     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12986       .addReg(OffsetReg64)
12987       .addReg(RegSaveReg);
12988
12989     // Compute the offset for the next argument
12990     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12991     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12992       .addReg(OffsetReg)
12993       .addImm(UseFPOffset ? 16 : 8);
12994
12995     // Store it back into the va_list.
12996     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12997       .addOperand(Base)
12998       .addOperand(Scale)
12999       .addOperand(Index)
13000       .addDisp(Disp, UseFPOffset ? 4 : 0)
13001       .addOperand(Segment)
13002       .addReg(NextOffsetReg)
13003       .setMemRefs(MMOBegin, MMOEnd);
13004
13005     // Jump to endMBB
13006     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13007       .addMBB(endMBB);
13008   }
13009
13010   //
13011   // Emit code to use overflow area
13012   //
13013
13014   // Load the overflow_area address into a register.
13015   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13016   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13017     .addOperand(Base)
13018     .addOperand(Scale)
13019     .addOperand(Index)
13020     .addDisp(Disp, 8)
13021     .addOperand(Segment)
13022     .setMemRefs(MMOBegin, MMOEnd);
13023
13024   // If we need to align it, do so. Otherwise, just copy the address
13025   // to OverflowDestReg.
13026   if (NeedsAlign) {
13027     // Align the overflow address
13028     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13029     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13030
13031     // aligned_addr = (addr + (align-1)) & ~(align-1)
13032     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13033       .addReg(OverflowAddrReg)
13034       .addImm(Align-1);
13035
13036     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13037       .addReg(TmpReg)
13038       .addImm(~(uint64_t)(Align-1));
13039   } else {
13040     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13041       .addReg(OverflowAddrReg);
13042   }
13043
13044   // Compute the next overflow address after this argument.
13045   // (the overflow address should be kept 8-byte aligned)
13046   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13047   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13048     .addReg(OverflowDestReg)
13049     .addImm(ArgSizeA8);
13050
13051   // Store the new overflow address.
13052   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13053     .addOperand(Base)
13054     .addOperand(Scale)
13055     .addOperand(Index)
13056     .addDisp(Disp, 8)
13057     .addOperand(Segment)
13058     .addReg(NextAddrReg)
13059     .setMemRefs(MMOBegin, MMOEnd);
13060
13061   // If we branched, emit the PHI to the front of endMBB.
13062   if (offsetMBB) {
13063     BuildMI(*endMBB, endMBB->begin(), DL,
13064             TII->get(X86::PHI), DestReg)
13065       .addReg(OffsetDestReg).addMBB(offsetMBB)
13066       .addReg(OverflowDestReg).addMBB(overflowMBB);
13067   }
13068
13069   // Erase the pseudo instruction
13070   MI->eraseFromParent();
13071
13072   return endMBB;
13073 }
13074
13075 MachineBasicBlock *
13076 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13077                                                  MachineInstr *MI,
13078                                                  MachineBasicBlock *MBB) const {
13079   // Emit code to save XMM registers to the stack. The ABI says that the
13080   // number of registers to save is given in %al, so it's theoretically
13081   // possible to do an indirect jump trick to avoid saving all of them,
13082   // however this code takes a simpler approach and just executes all
13083   // of the stores if %al is non-zero. It's less code, and it's probably
13084   // easier on the hardware branch predictor, and stores aren't all that
13085   // expensive anyway.
13086
13087   // Create the new basic blocks. One block contains all the XMM stores,
13088   // and one block is the final destination regardless of whether any
13089   // stores were performed.
13090   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13091   MachineFunction *F = MBB->getParent();
13092   MachineFunction::iterator MBBIter = MBB;
13093   ++MBBIter;
13094   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13095   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13096   F->insert(MBBIter, XMMSaveMBB);
13097   F->insert(MBBIter, EndMBB);
13098
13099   // Transfer the remainder of MBB and its successor edges to EndMBB.
13100   EndMBB->splice(EndMBB->begin(), MBB,
13101                  llvm::next(MachineBasicBlock::iterator(MI)),
13102                  MBB->end());
13103   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13104
13105   // The original block will now fall through to the XMM save block.
13106   MBB->addSuccessor(XMMSaveMBB);
13107   // The XMMSaveMBB will fall through to the end block.
13108   XMMSaveMBB->addSuccessor(EndMBB);
13109
13110   // Now add the instructions.
13111   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13112   DebugLoc DL = MI->getDebugLoc();
13113
13114   unsigned CountReg = MI->getOperand(0).getReg();
13115   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13116   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13117
13118   if (!Subtarget->isTargetWin64()) {
13119     // If %al is 0, branch around the XMM save block.
13120     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13121     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13122     MBB->addSuccessor(EndMBB);
13123   }
13124
13125   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13126   // In the XMM save block, save all the XMM argument registers.
13127   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13128     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13129     MachineMemOperand *MMO =
13130       F->getMachineMemOperand(
13131           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13132         MachineMemOperand::MOStore,
13133         /*Size=*/16, /*Align=*/16);
13134     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13135       .addFrameIndex(RegSaveFrameIndex)
13136       .addImm(/*Scale=*/1)
13137       .addReg(/*IndexReg=*/0)
13138       .addImm(/*Disp=*/Offset)
13139       .addReg(/*Segment=*/0)
13140       .addReg(MI->getOperand(i).getReg())
13141       .addMemOperand(MMO);
13142   }
13143
13144   MI->eraseFromParent();   // The pseudo instruction is gone now.
13145
13146   return EndMBB;
13147 }
13148
13149 // The EFLAGS operand of SelectItr might be missing a kill marker
13150 // because there were multiple uses of EFLAGS, and ISel didn't know
13151 // which to mark. Figure out whether SelectItr should have had a
13152 // kill marker, and set it if it should. Returns the correct kill
13153 // marker value.
13154 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13155                                      MachineBasicBlock* BB,
13156                                      const TargetRegisterInfo* TRI) {
13157   // Scan forward through BB for a use/def of EFLAGS.
13158   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13159   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13160     const MachineInstr& mi = *miI;
13161     if (mi.readsRegister(X86::EFLAGS))
13162       return false;
13163     if (mi.definesRegister(X86::EFLAGS))
13164       break; // Should have kill-flag - update below.
13165   }
13166
13167   // If we hit the end of the block, check whether EFLAGS is live into a
13168   // successor.
13169   if (miI == BB->end()) {
13170     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13171                                           sEnd = BB->succ_end();
13172          sItr != sEnd; ++sItr) {
13173       MachineBasicBlock* succ = *sItr;
13174       if (succ->isLiveIn(X86::EFLAGS))
13175         return false;
13176     }
13177   }
13178
13179   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13180   // out. SelectMI should have a kill flag on EFLAGS.
13181   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13182   return true;
13183 }
13184
13185 MachineBasicBlock *
13186 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13187                                      MachineBasicBlock *BB) const {
13188   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13189   DebugLoc DL = MI->getDebugLoc();
13190
13191   // To "insert" a SELECT_CC instruction, we actually have to insert the
13192   // diamond control-flow pattern.  The incoming instruction knows the
13193   // destination vreg to set, the condition code register to branch on, the
13194   // true/false values to select between, and a branch opcode to use.
13195   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13196   MachineFunction::iterator It = BB;
13197   ++It;
13198
13199   //  thisMBB:
13200   //  ...
13201   //   TrueVal = ...
13202   //   cmpTY ccX, r1, r2
13203   //   bCC copy1MBB
13204   //   fallthrough --> copy0MBB
13205   MachineBasicBlock *thisMBB = BB;
13206   MachineFunction *F = BB->getParent();
13207   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13208   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13209   F->insert(It, copy0MBB);
13210   F->insert(It, sinkMBB);
13211
13212   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13213   // live into the sink and copy blocks.
13214   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13215   if (!MI->killsRegister(X86::EFLAGS) &&
13216       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13217     copy0MBB->addLiveIn(X86::EFLAGS);
13218     sinkMBB->addLiveIn(X86::EFLAGS);
13219   }
13220
13221   // Transfer the remainder of BB and its successor edges to sinkMBB.
13222   sinkMBB->splice(sinkMBB->begin(), BB,
13223                   llvm::next(MachineBasicBlock::iterator(MI)),
13224                   BB->end());
13225   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13226
13227   // Add the true and fallthrough blocks as its successors.
13228   BB->addSuccessor(copy0MBB);
13229   BB->addSuccessor(sinkMBB);
13230
13231   // Create the conditional branch instruction.
13232   unsigned Opc =
13233     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13234   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13235
13236   //  copy0MBB:
13237   //   %FalseValue = ...
13238   //   # fallthrough to sinkMBB
13239   copy0MBB->addSuccessor(sinkMBB);
13240
13241   //  sinkMBB:
13242   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13243   //  ...
13244   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13245           TII->get(X86::PHI), MI->getOperand(0).getReg())
13246     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13247     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13248
13249   MI->eraseFromParent();   // The pseudo instruction is gone now.
13250   return sinkMBB;
13251 }
13252
13253 MachineBasicBlock *
13254 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13255                                         bool Is64Bit) const {
13256   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13257   DebugLoc DL = MI->getDebugLoc();
13258   MachineFunction *MF = BB->getParent();
13259   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13260
13261   assert(getTargetMachine().Options.EnableSegmentedStacks);
13262
13263   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13264   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13265
13266   // BB:
13267   //  ... [Till the alloca]
13268   // If stacklet is not large enough, jump to mallocMBB
13269   //
13270   // bumpMBB:
13271   //  Allocate by subtracting from RSP
13272   //  Jump to continueMBB
13273   //
13274   // mallocMBB:
13275   //  Allocate by call to runtime
13276   //
13277   // continueMBB:
13278   //  ...
13279   //  [rest of original BB]
13280   //
13281
13282   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13283   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13284   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13285
13286   MachineRegisterInfo &MRI = MF->getRegInfo();
13287   const TargetRegisterClass *AddrRegClass =
13288     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13289
13290   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13291     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13292     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13293     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13294     sizeVReg = MI->getOperand(1).getReg(),
13295     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13296
13297   MachineFunction::iterator MBBIter = BB;
13298   ++MBBIter;
13299
13300   MF->insert(MBBIter, bumpMBB);
13301   MF->insert(MBBIter, mallocMBB);
13302   MF->insert(MBBIter, continueMBB);
13303
13304   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13305                       (MachineBasicBlock::iterator(MI)), BB->end());
13306   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13307
13308   // Add code to the main basic block to check if the stack limit has been hit,
13309   // and if so, jump to mallocMBB otherwise to bumpMBB.
13310   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13311   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13312     .addReg(tmpSPVReg).addReg(sizeVReg);
13313   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13314     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13315     .addReg(SPLimitVReg);
13316   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13317
13318   // bumpMBB simply decreases the stack pointer, since we know the current
13319   // stacklet has enough space.
13320   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13321     .addReg(SPLimitVReg);
13322   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13323     .addReg(SPLimitVReg);
13324   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13325
13326   // Calls into a routine in libgcc to allocate more space from the heap.
13327   const uint32_t *RegMask =
13328     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13329   if (Is64Bit) {
13330     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13331       .addReg(sizeVReg);
13332     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13333       .addExternalSymbol("__morestack_allocate_stack_space")
13334       .addRegMask(RegMask)
13335       .addReg(X86::RDI, RegState::Implicit)
13336       .addReg(X86::RAX, RegState::ImplicitDefine);
13337   } else {
13338     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13339       .addImm(12);
13340     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13341     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13342       .addExternalSymbol("__morestack_allocate_stack_space")
13343       .addRegMask(RegMask)
13344       .addReg(X86::EAX, RegState::ImplicitDefine);
13345   }
13346
13347   if (!Is64Bit)
13348     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13349       .addImm(16);
13350
13351   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13352     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13353   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13354
13355   // Set up the CFG correctly.
13356   BB->addSuccessor(bumpMBB);
13357   BB->addSuccessor(mallocMBB);
13358   mallocMBB->addSuccessor(continueMBB);
13359   bumpMBB->addSuccessor(continueMBB);
13360
13361   // Take care of the PHI nodes.
13362   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13363           MI->getOperand(0).getReg())
13364     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13365     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13366
13367   // Delete the original pseudo instruction.
13368   MI->eraseFromParent();
13369
13370   // And we're done.
13371   return continueMBB;
13372 }
13373
13374 MachineBasicBlock *
13375 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13376                                           MachineBasicBlock *BB) const {
13377   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13378   DebugLoc DL = MI->getDebugLoc();
13379
13380   assert(!Subtarget->isTargetEnvMacho());
13381
13382   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13383   // non-trivial part is impdef of ESP.
13384
13385   if (Subtarget->isTargetWin64()) {
13386     if (Subtarget->isTargetCygMing()) {
13387       // ___chkstk(Mingw64):
13388       // Clobbers R10, R11, RAX and EFLAGS.
13389       // Updates RSP.
13390       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13391         .addExternalSymbol("___chkstk")
13392         .addReg(X86::RAX, RegState::Implicit)
13393         .addReg(X86::RSP, RegState::Implicit)
13394         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13395         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13396         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13397     } else {
13398       // __chkstk(MSVCRT): does not update stack pointer.
13399       // Clobbers R10, R11 and EFLAGS.
13400       // FIXME: RAX(allocated size) might be reused and not killed.
13401       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13402         .addExternalSymbol("__chkstk")
13403         .addReg(X86::RAX, RegState::Implicit)
13404         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13405       // RAX has the offset to subtracted from RSP.
13406       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13407         .addReg(X86::RSP)
13408         .addReg(X86::RAX);
13409     }
13410   } else {
13411     const char *StackProbeSymbol =
13412       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13413
13414     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13415       .addExternalSymbol(StackProbeSymbol)
13416       .addReg(X86::EAX, RegState::Implicit)
13417       .addReg(X86::ESP, RegState::Implicit)
13418       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13419       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13420       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13421   }
13422
13423   MI->eraseFromParent();   // The pseudo instruction is gone now.
13424   return BB;
13425 }
13426
13427 MachineBasicBlock *
13428 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13429                                       MachineBasicBlock *BB) const {
13430   // This is pretty easy.  We're taking the value that we received from
13431   // our load from the relocation, sticking it in either RDI (x86-64)
13432   // or EAX and doing an indirect call.  The return value will then
13433   // be in the normal return register.
13434   const X86InstrInfo *TII
13435     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13436   DebugLoc DL = MI->getDebugLoc();
13437   MachineFunction *F = BB->getParent();
13438
13439   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13440   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13441
13442   // Get a register mask for the lowered call.
13443   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13444   // proper register mask.
13445   const uint32_t *RegMask =
13446     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13447   if (Subtarget->is64Bit()) {
13448     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13449                                       TII->get(X86::MOV64rm), X86::RDI)
13450     .addReg(X86::RIP)
13451     .addImm(0).addReg(0)
13452     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13453                       MI->getOperand(3).getTargetFlags())
13454     .addReg(0);
13455     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13456     addDirectMem(MIB, X86::RDI);
13457     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13458   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13459     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13460                                       TII->get(X86::MOV32rm), X86::EAX)
13461     .addReg(0)
13462     .addImm(0).addReg(0)
13463     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13464                       MI->getOperand(3).getTargetFlags())
13465     .addReg(0);
13466     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13467     addDirectMem(MIB, X86::EAX);
13468     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13469   } else {
13470     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13471                                       TII->get(X86::MOV32rm), X86::EAX)
13472     .addReg(TII->getGlobalBaseReg(F))
13473     .addImm(0).addReg(0)
13474     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13475                       MI->getOperand(3).getTargetFlags())
13476     .addReg(0);
13477     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13478     addDirectMem(MIB, X86::EAX);
13479     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13480   }
13481
13482   MI->eraseFromParent(); // The pseudo instruction is gone now.
13483   return BB;
13484 }
13485
13486 MachineBasicBlock *
13487 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13488                                     MachineBasicBlock *MBB) const {
13489   DebugLoc DL = MI->getDebugLoc();
13490   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13491
13492   MachineFunction *MF = MBB->getParent();
13493   MachineRegisterInfo &MRI = MF->getRegInfo();
13494
13495   const BasicBlock *BB = MBB->getBasicBlock();
13496   MachineFunction::iterator I = MBB;
13497   ++I;
13498
13499   // Memory Reference
13500   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13501   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13502
13503   unsigned DstReg;
13504   unsigned MemOpndSlot = 0;
13505
13506   unsigned CurOp = 0;
13507
13508   DstReg = MI->getOperand(CurOp++).getReg();
13509   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13510   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13511   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13512   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13513
13514   MemOpndSlot = CurOp;
13515
13516   MVT PVT = getPointerTy();
13517   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13518          "Invalid Pointer Size!");
13519
13520   // For v = setjmp(buf), we generate
13521   //
13522   // thisMBB:
13523   //  buf[LabelOffset] = restoreMBB
13524   //  SjLjSetup restoreMBB
13525   //
13526   // mainMBB:
13527   //  v_main = 0
13528   //
13529   // sinkMBB:
13530   //  v = phi(main, restore)
13531   //
13532   // restoreMBB:
13533   //  v_restore = 1
13534
13535   MachineBasicBlock *thisMBB = MBB;
13536   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13537   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13538   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13539   MF->insert(I, mainMBB);
13540   MF->insert(I, sinkMBB);
13541   MF->push_back(restoreMBB);
13542
13543   MachineInstrBuilder MIB;
13544
13545   // Transfer the remainder of BB and its successor edges to sinkMBB.
13546   sinkMBB->splice(sinkMBB->begin(), MBB,
13547                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13548   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13549
13550   // thisMBB:
13551   unsigned PtrStoreOpc = 0;
13552   unsigned LabelReg = 0;
13553   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13554   Reloc::Model RM = getTargetMachine().getRelocationModel();
13555   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13556                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13557
13558   // Prepare IP either in reg or imm.
13559   if (!UseImmLabel) {
13560     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13561     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13562     LabelReg = MRI.createVirtualRegister(PtrRC);
13563     if (Subtarget->is64Bit()) {
13564       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13565               .addReg(X86::RIP)
13566               .addImm(0)
13567               .addReg(0)
13568               .addMBB(restoreMBB)
13569               .addReg(0);
13570     } else {
13571       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13572       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13573               .addReg(XII->getGlobalBaseReg(MF))
13574               .addImm(0)
13575               .addReg(0)
13576               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13577               .addReg(0);
13578     }
13579   } else
13580     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13581   // Store IP
13582   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13583   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13584     if (i == X86::AddrDisp)
13585       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13586     else
13587       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13588   }
13589   if (!UseImmLabel)
13590     MIB.addReg(LabelReg);
13591   else
13592     MIB.addMBB(restoreMBB);
13593   MIB.setMemRefs(MMOBegin, MMOEnd);
13594   // Setup
13595   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13596           .addMBB(restoreMBB);
13597   MIB.addRegMask(RegInfo->getNoPreservedMask());
13598   thisMBB->addSuccessor(mainMBB);
13599   thisMBB->addSuccessor(restoreMBB);
13600
13601   // mainMBB:
13602   //  EAX = 0
13603   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13604   mainMBB->addSuccessor(sinkMBB);
13605
13606   // sinkMBB:
13607   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13608           TII->get(X86::PHI), DstReg)
13609     .addReg(mainDstReg).addMBB(mainMBB)
13610     .addReg(restoreDstReg).addMBB(restoreMBB);
13611
13612   // restoreMBB:
13613   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13614   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13615   restoreMBB->addSuccessor(sinkMBB);
13616
13617   MI->eraseFromParent();
13618   return sinkMBB;
13619 }
13620
13621 MachineBasicBlock *
13622 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13623                                      MachineBasicBlock *MBB) const {
13624   DebugLoc DL = MI->getDebugLoc();
13625   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13626
13627   MachineFunction *MF = MBB->getParent();
13628   MachineRegisterInfo &MRI = MF->getRegInfo();
13629
13630   // Memory Reference
13631   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13632   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13633
13634   MVT PVT = getPointerTy();
13635   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13636          "Invalid Pointer Size!");
13637
13638   const TargetRegisterClass *RC =
13639     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13640   unsigned Tmp = MRI.createVirtualRegister(RC);
13641   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13642   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13643   unsigned SP = RegInfo->getStackRegister();
13644
13645   MachineInstrBuilder MIB;
13646
13647   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13648   const int64_t SPOffset = 2 * PVT.getStoreSize();
13649
13650   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13651   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13652
13653   // Reload FP
13654   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13655   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13656     MIB.addOperand(MI->getOperand(i));
13657   MIB.setMemRefs(MMOBegin, MMOEnd);
13658   // Reload IP
13659   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13660   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13661     if (i == X86::AddrDisp)
13662       MIB.addDisp(MI->getOperand(i), LabelOffset);
13663     else
13664       MIB.addOperand(MI->getOperand(i));
13665   }
13666   MIB.setMemRefs(MMOBegin, MMOEnd);
13667   // Reload SP
13668   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13669   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13670     if (i == X86::AddrDisp)
13671       MIB.addDisp(MI->getOperand(i), SPOffset);
13672     else
13673       MIB.addOperand(MI->getOperand(i));
13674   }
13675   MIB.setMemRefs(MMOBegin, MMOEnd);
13676   // Jump
13677   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13678
13679   MI->eraseFromParent();
13680   return MBB;
13681 }
13682
13683 MachineBasicBlock *
13684 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13685                                                MachineBasicBlock *BB) const {
13686   switch (MI->getOpcode()) {
13687   default: llvm_unreachable("Unexpected instr type to insert");
13688   case X86::TAILJMPd64:
13689   case X86::TAILJMPr64:
13690   case X86::TAILJMPm64:
13691     llvm_unreachable("TAILJMP64 would not be touched here.");
13692   case X86::TCRETURNdi64:
13693   case X86::TCRETURNri64:
13694   case X86::TCRETURNmi64:
13695     return BB;
13696   case X86::WIN_ALLOCA:
13697     return EmitLoweredWinAlloca(MI, BB);
13698   case X86::SEG_ALLOCA_32:
13699     return EmitLoweredSegAlloca(MI, BB, false);
13700   case X86::SEG_ALLOCA_64:
13701     return EmitLoweredSegAlloca(MI, BB, true);
13702   case X86::TLSCall_32:
13703   case X86::TLSCall_64:
13704     return EmitLoweredTLSCall(MI, BB);
13705   case X86::CMOV_GR8:
13706   case X86::CMOV_FR32:
13707   case X86::CMOV_FR64:
13708   case X86::CMOV_V4F32:
13709   case X86::CMOV_V2F64:
13710   case X86::CMOV_V2I64:
13711   case X86::CMOV_V8F32:
13712   case X86::CMOV_V4F64:
13713   case X86::CMOV_V4I64:
13714   case X86::CMOV_GR16:
13715   case X86::CMOV_GR32:
13716   case X86::CMOV_RFP32:
13717   case X86::CMOV_RFP64:
13718   case X86::CMOV_RFP80:
13719     return EmitLoweredSelect(MI, BB);
13720
13721   case X86::FP32_TO_INT16_IN_MEM:
13722   case X86::FP32_TO_INT32_IN_MEM:
13723   case X86::FP32_TO_INT64_IN_MEM:
13724   case X86::FP64_TO_INT16_IN_MEM:
13725   case X86::FP64_TO_INT32_IN_MEM:
13726   case X86::FP64_TO_INT64_IN_MEM:
13727   case X86::FP80_TO_INT16_IN_MEM:
13728   case X86::FP80_TO_INT32_IN_MEM:
13729   case X86::FP80_TO_INT64_IN_MEM: {
13730     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13731     DebugLoc DL = MI->getDebugLoc();
13732
13733     // Change the floating point control register to use "round towards zero"
13734     // mode when truncating to an integer value.
13735     MachineFunction *F = BB->getParent();
13736     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13737     addFrameReference(BuildMI(*BB, MI, DL,
13738                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13739
13740     // Load the old value of the high byte of the control word...
13741     unsigned OldCW =
13742       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13743     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13744                       CWFrameIdx);
13745
13746     // Set the high part to be round to zero...
13747     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13748       .addImm(0xC7F);
13749
13750     // Reload the modified control word now...
13751     addFrameReference(BuildMI(*BB, MI, DL,
13752                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13753
13754     // Restore the memory image of control word to original value
13755     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13756       .addReg(OldCW);
13757
13758     // Get the X86 opcode to use.
13759     unsigned Opc;
13760     switch (MI->getOpcode()) {
13761     default: llvm_unreachable("illegal opcode!");
13762     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13763     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13764     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13765     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13766     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13767     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13768     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13769     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13770     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13771     }
13772
13773     X86AddressMode AM;
13774     MachineOperand &Op = MI->getOperand(0);
13775     if (Op.isReg()) {
13776       AM.BaseType = X86AddressMode::RegBase;
13777       AM.Base.Reg = Op.getReg();
13778     } else {
13779       AM.BaseType = X86AddressMode::FrameIndexBase;
13780       AM.Base.FrameIndex = Op.getIndex();
13781     }
13782     Op = MI->getOperand(1);
13783     if (Op.isImm())
13784       AM.Scale = Op.getImm();
13785     Op = MI->getOperand(2);
13786     if (Op.isImm())
13787       AM.IndexReg = Op.getImm();
13788     Op = MI->getOperand(3);
13789     if (Op.isGlobal()) {
13790       AM.GV = Op.getGlobal();
13791     } else {
13792       AM.Disp = Op.getImm();
13793     }
13794     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13795                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13796
13797     // Reload the original control word now.
13798     addFrameReference(BuildMI(*BB, MI, DL,
13799                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13800
13801     MI->eraseFromParent();   // The pseudo instruction is gone now.
13802     return BB;
13803   }
13804     // String/text processing lowering.
13805   case X86::PCMPISTRM128REG:
13806   case X86::VPCMPISTRM128REG:
13807   case X86::PCMPISTRM128MEM:
13808   case X86::VPCMPISTRM128MEM:
13809   case X86::PCMPESTRM128REG:
13810   case X86::VPCMPESTRM128REG:
13811   case X86::PCMPESTRM128MEM:
13812   case X86::VPCMPESTRM128MEM: {
13813     unsigned NumArgs;
13814     bool MemArg;
13815     switch (MI->getOpcode()) {
13816     default: llvm_unreachable("illegal opcode!");
13817     case X86::PCMPISTRM128REG:
13818     case X86::VPCMPISTRM128REG:
13819       NumArgs = 3; MemArg = false; break;
13820     case X86::PCMPISTRM128MEM:
13821     case X86::VPCMPISTRM128MEM:
13822       NumArgs = 3; MemArg = true; break;
13823     case X86::PCMPESTRM128REG:
13824     case X86::VPCMPESTRM128REG:
13825       NumArgs = 5; MemArg = false; break;
13826     case X86::PCMPESTRM128MEM:
13827     case X86::VPCMPESTRM128MEM:
13828       NumArgs = 5; MemArg = true; break;
13829     }
13830     return EmitPCMP(MI, BB, NumArgs, MemArg);
13831   }
13832
13833     // Thread synchronization.
13834   case X86::MONITOR:
13835     return EmitMonitor(MI, BB);
13836
13837     // Atomic Lowering.
13838   case X86::ATOMAND8:
13839   case X86::ATOMAND16:
13840   case X86::ATOMAND32:
13841   case X86::ATOMAND64:
13842     // Fall through
13843   case X86::ATOMOR8:
13844   case X86::ATOMOR16:
13845   case X86::ATOMOR32:
13846   case X86::ATOMOR64:
13847     // Fall through
13848   case X86::ATOMXOR16:
13849   case X86::ATOMXOR8:
13850   case X86::ATOMXOR32:
13851   case X86::ATOMXOR64:
13852     // Fall through
13853   case X86::ATOMNAND8:
13854   case X86::ATOMNAND16:
13855   case X86::ATOMNAND32:
13856   case X86::ATOMNAND64:
13857     // Fall through
13858   case X86::ATOMMAX8:
13859   case X86::ATOMMAX16:
13860   case X86::ATOMMAX32:
13861   case X86::ATOMMAX64:
13862     // Fall through
13863   case X86::ATOMMIN8:
13864   case X86::ATOMMIN16:
13865   case X86::ATOMMIN32:
13866   case X86::ATOMMIN64:
13867     // Fall through
13868   case X86::ATOMUMAX8:
13869   case X86::ATOMUMAX16:
13870   case X86::ATOMUMAX32:
13871   case X86::ATOMUMAX64:
13872     // Fall through
13873   case X86::ATOMUMIN8:
13874   case X86::ATOMUMIN16:
13875   case X86::ATOMUMIN32:
13876   case X86::ATOMUMIN64:
13877     return EmitAtomicLoadArith(MI, BB);
13878
13879   // This group does 64-bit operations on a 32-bit host.
13880   case X86::ATOMAND6432:
13881   case X86::ATOMOR6432:
13882   case X86::ATOMXOR6432:
13883   case X86::ATOMNAND6432:
13884   case X86::ATOMADD6432:
13885   case X86::ATOMSUB6432:
13886   case X86::ATOMMAX6432:
13887   case X86::ATOMMIN6432:
13888   case X86::ATOMUMAX6432:
13889   case X86::ATOMUMIN6432:
13890   case X86::ATOMSWAP6432:
13891     return EmitAtomicLoadArith6432(MI, BB);
13892
13893   case X86::VASTART_SAVE_XMM_REGS:
13894     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13895
13896   case X86::VAARG_64:
13897     return EmitVAARG64WithCustomInserter(MI, BB);
13898
13899   case X86::EH_SjLj_SetJmp32:
13900   case X86::EH_SjLj_SetJmp64:
13901     return emitEHSjLjSetJmp(MI, BB);
13902
13903   case X86::EH_SjLj_LongJmp32:
13904   case X86::EH_SjLj_LongJmp64:
13905     return emitEHSjLjLongJmp(MI, BB);
13906   }
13907 }
13908
13909 //===----------------------------------------------------------------------===//
13910 //                           X86 Optimization Hooks
13911 //===----------------------------------------------------------------------===//
13912
13913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13914                                                        APInt &KnownZero,
13915                                                        APInt &KnownOne,
13916                                                        const SelectionDAG &DAG,
13917                                                        unsigned Depth) const {
13918   unsigned BitWidth = KnownZero.getBitWidth();
13919   unsigned Opc = Op.getOpcode();
13920   assert((Opc >= ISD::BUILTIN_OP_END ||
13921           Opc == ISD::INTRINSIC_WO_CHAIN ||
13922           Opc == ISD::INTRINSIC_W_CHAIN ||
13923           Opc == ISD::INTRINSIC_VOID) &&
13924          "Should use MaskedValueIsZero if you don't know whether Op"
13925          " is a target node!");
13926
13927   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13928   switch (Opc) {
13929   default: break;
13930   case X86ISD::ADD:
13931   case X86ISD::SUB:
13932   case X86ISD::ADC:
13933   case X86ISD::SBB:
13934   case X86ISD::SMUL:
13935   case X86ISD::UMUL:
13936   case X86ISD::INC:
13937   case X86ISD::DEC:
13938   case X86ISD::OR:
13939   case X86ISD::XOR:
13940   case X86ISD::AND:
13941     // These nodes' second result is a boolean.
13942     if (Op.getResNo() == 0)
13943       break;
13944     // Fallthrough
13945   case X86ISD::SETCC:
13946     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13947     break;
13948   case ISD::INTRINSIC_WO_CHAIN: {
13949     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13950     unsigned NumLoBits = 0;
13951     switch (IntId) {
13952     default: break;
13953     case Intrinsic::x86_sse_movmsk_ps:
13954     case Intrinsic::x86_avx_movmsk_ps_256:
13955     case Intrinsic::x86_sse2_movmsk_pd:
13956     case Intrinsic::x86_avx_movmsk_pd_256:
13957     case Intrinsic::x86_mmx_pmovmskb:
13958     case Intrinsic::x86_sse2_pmovmskb_128:
13959     case Intrinsic::x86_avx2_pmovmskb: {
13960       // High bits of movmskp{s|d}, pmovmskb are known zero.
13961       switch (IntId) {
13962         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13963         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13964         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13965         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13966         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13967         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13968         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13969         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13970       }
13971       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13972       break;
13973     }
13974     }
13975     break;
13976   }
13977   }
13978 }
13979
13980 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13981                                                          unsigned Depth) const {
13982   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13983   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13984     return Op.getValueType().getScalarType().getSizeInBits();
13985
13986   // Fallback case.
13987   return 1;
13988 }
13989
13990 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13991 /// node is a GlobalAddress + offset.
13992 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13993                                        const GlobalValue* &GA,
13994                                        int64_t &Offset) const {
13995   if (N->getOpcode() == X86ISD::Wrapper) {
13996     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13997       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13998       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13999       return true;
14000     }
14001   }
14002   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14003 }
14004
14005 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14006 /// same as extracting the high 128-bit part of 256-bit vector and then
14007 /// inserting the result into the low part of a new 256-bit vector
14008 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14009   EVT VT = SVOp->getValueType(0);
14010   unsigned NumElems = VT.getVectorNumElements();
14011
14012   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14013   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14014     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14015         SVOp->getMaskElt(j) >= 0)
14016       return false;
14017
14018   return true;
14019 }
14020
14021 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14022 /// same as extracting the low 128-bit part of 256-bit vector and then
14023 /// inserting the result into the high part of a new 256-bit vector
14024 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14025   EVT VT = SVOp->getValueType(0);
14026   unsigned NumElems = VT.getVectorNumElements();
14027
14028   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14029   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14030     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14031         SVOp->getMaskElt(j) >= 0)
14032       return false;
14033
14034   return true;
14035 }
14036
14037 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14038 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14039                                         TargetLowering::DAGCombinerInfo &DCI,
14040                                         const X86Subtarget* Subtarget) {
14041   DebugLoc dl = N->getDebugLoc();
14042   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14043   SDValue V1 = SVOp->getOperand(0);
14044   SDValue V2 = SVOp->getOperand(1);
14045   EVT VT = SVOp->getValueType(0);
14046   unsigned NumElems = VT.getVectorNumElements();
14047
14048   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14049       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14050     //
14051     //                   0,0,0,...
14052     //                      |
14053     //    V      UNDEF    BUILD_VECTOR    UNDEF
14054     //     \      /           \           /
14055     //  CONCAT_VECTOR         CONCAT_VECTOR
14056     //         \                  /
14057     //          \                /
14058     //          RESULT: V + zero extended
14059     //
14060     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14061         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14062         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14063       return SDValue();
14064
14065     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14066       return SDValue();
14067
14068     // To match the shuffle mask, the first half of the mask should
14069     // be exactly the first vector, and all the rest a splat with the
14070     // first element of the second one.
14071     for (unsigned i = 0; i != NumElems/2; ++i)
14072       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14073           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14074         return SDValue();
14075
14076     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14077     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14078       if (Ld->hasNUsesOfValue(1, 0)) {
14079         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14080         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14081         SDValue ResNode =
14082           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14083                                   Ld->getMemoryVT(),
14084                                   Ld->getPointerInfo(),
14085                                   Ld->getAlignment(),
14086                                   false/*isVolatile*/, true/*ReadMem*/,
14087                                   false/*WriteMem*/);
14088         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14089       }
14090     }
14091
14092     // Emit a zeroed vector and insert the desired subvector on its
14093     // first half.
14094     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14095     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14096     return DCI.CombineTo(N, InsV);
14097   }
14098
14099   //===--------------------------------------------------------------------===//
14100   // Combine some shuffles into subvector extracts and inserts:
14101   //
14102
14103   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14104   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14105     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14106     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14107     return DCI.CombineTo(N, InsV);
14108   }
14109
14110   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14111   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14112     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14113     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14114     return DCI.CombineTo(N, InsV);
14115   }
14116
14117   return SDValue();
14118 }
14119
14120 /// PerformShuffleCombine - Performs several different shuffle combines.
14121 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14122                                      TargetLowering::DAGCombinerInfo &DCI,
14123                                      const X86Subtarget *Subtarget) {
14124   DebugLoc dl = N->getDebugLoc();
14125   EVT VT = N->getValueType(0);
14126
14127   // Don't create instructions with illegal types after legalize types has run.
14128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14129   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14130     return SDValue();
14131
14132   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14133   if (Subtarget->hasAVX() && VT.is256BitVector() &&
14134       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14135     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14136
14137   // Only handle 128 wide vector from here on.
14138   if (!VT.is128BitVector())
14139     return SDValue();
14140
14141   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14142   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14143   // consecutive, non-overlapping, and in the right order.
14144   SmallVector<SDValue, 16> Elts;
14145   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14146     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14147
14148   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14149 }
14150
14151
14152 /// PerformTruncateCombine - Converts truncate operation to
14153 /// a sequence of vector shuffle operations.
14154 /// It is possible when we truncate 256-bit vector to 128-bit vector
14155 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14156                                       TargetLowering::DAGCombinerInfo &DCI,
14157                                       const X86Subtarget *Subtarget)  {
14158   if (!DCI.isBeforeLegalizeOps())
14159     return SDValue();
14160
14161   if (!Subtarget->hasAVX())
14162     return SDValue();
14163
14164   EVT VT = N->getValueType(0);
14165   SDValue Op = N->getOperand(0);
14166   EVT OpVT = Op.getValueType();
14167   DebugLoc dl = N->getDebugLoc();
14168
14169   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14170
14171     if (Subtarget->hasAVX2()) {
14172       // AVX2: v4i64 -> v4i32
14173
14174       // VPERMD
14175       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14176
14177       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14178       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14179                                 ShufMask);
14180
14181       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14182                          DAG.getIntPtrConstant(0));
14183     }
14184
14185     // AVX: v4i64 -> v4i32
14186     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14187                                DAG.getIntPtrConstant(0));
14188
14189     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14190                                DAG.getIntPtrConstant(2));
14191
14192     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14193     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14194
14195     // PSHUFD
14196     static const int ShufMask1[] = {0, 2, 0, 0};
14197
14198     SDValue Undef = DAG.getUNDEF(VT);
14199     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14200     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14201
14202     // MOVLHPS
14203     static const int ShufMask2[] = {0, 1, 4, 5};
14204
14205     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14206   }
14207
14208   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14209
14210     if (Subtarget->hasAVX2()) {
14211       // AVX2: v8i32 -> v8i16
14212
14213       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14214
14215       // PSHUFB
14216       SmallVector<SDValue,32> pshufbMask;
14217       for (unsigned i = 0; i < 2; ++i) {
14218         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14219         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14220         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14221         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14222         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14223         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14224         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14225         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14226         for (unsigned j = 0; j < 8; ++j)
14227           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14228       }
14229       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14230                                &pshufbMask[0], 32);
14231       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14232
14233       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14234
14235       static const int ShufMask[] = {0,  2,  -1,  -1};
14236       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14237                                 &ShufMask[0]);
14238
14239       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14240                        DAG.getIntPtrConstant(0));
14241
14242       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14243     }
14244
14245     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14246                                DAG.getIntPtrConstant(0));
14247
14248     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14249                                DAG.getIntPtrConstant(4));
14250
14251     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14252     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14253
14254     // PSHUFB
14255     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14256                                    -1, -1, -1, -1, -1, -1, -1, -1};
14257
14258     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14259     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14260     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14261
14262     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14263     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14264
14265     // MOVLHPS
14266     static const int ShufMask2[] = {0, 1, 4, 5};
14267
14268     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14269     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14270   }
14271
14272   return SDValue();
14273 }
14274
14275 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14276 /// specific shuffle of a load can be folded into a single element load.
14277 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14278 /// shuffles have been customed lowered so we need to handle those here.
14279 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14280                                          TargetLowering::DAGCombinerInfo &DCI) {
14281   if (DCI.isBeforeLegalizeOps())
14282     return SDValue();
14283
14284   SDValue InVec = N->getOperand(0);
14285   SDValue EltNo = N->getOperand(1);
14286
14287   if (!isa<ConstantSDNode>(EltNo))
14288     return SDValue();
14289
14290   EVT VT = InVec.getValueType();
14291
14292   bool HasShuffleIntoBitcast = false;
14293   if (InVec.getOpcode() == ISD::BITCAST) {
14294     // Don't duplicate a load with other uses.
14295     if (!InVec.hasOneUse())
14296       return SDValue();
14297     EVT BCVT = InVec.getOperand(0).getValueType();
14298     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14299       return SDValue();
14300     InVec = InVec.getOperand(0);
14301     HasShuffleIntoBitcast = true;
14302   }
14303
14304   if (!isTargetShuffle(InVec.getOpcode()))
14305     return SDValue();
14306
14307   // Don't duplicate a load with other uses.
14308   if (!InVec.hasOneUse())
14309     return SDValue();
14310
14311   SmallVector<int, 16> ShuffleMask;
14312   bool UnaryShuffle;
14313   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14314                             UnaryShuffle))
14315     return SDValue();
14316
14317   // Select the input vector, guarding against out of range extract vector.
14318   unsigned NumElems = VT.getVectorNumElements();
14319   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14320   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14321   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14322                                          : InVec.getOperand(1);
14323
14324   // If inputs to shuffle are the same for both ops, then allow 2 uses
14325   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14326
14327   if (LdNode.getOpcode() == ISD::BITCAST) {
14328     // Don't duplicate a load with other uses.
14329     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14330       return SDValue();
14331
14332     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14333     LdNode = LdNode.getOperand(0);
14334   }
14335
14336   if (!ISD::isNormalLoad(LdNode.getNode()))
14337     return SDValue();
14338
14339   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14340
14341   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14342     return SDValue();
14343
14344   if (HasShuffleIntoBitcast) {
14345     // If there's a bitcast before the shuffle, check if the load type and
14346     // alignment is valid.
14347     unsigned Align = LN0->getAlignment();
14348     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14349     unsigned NewAlign = TLI.getDataLayout()->
14350       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14351
14352     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14353       return SDValue();
14354   }
14355
14356   // All checks match so transform back to vector_shuffle so that DAG combiner
14357   // can finish the job
14358   DebugLoc dl = N->getDebugLoc();
14359
14360   // Create shuffle node taking into account the case that its a unary shuffle
14361   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14362   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14363                                  InVec.getOperand(0), Shuffle,
14364                                  &ShuffleMask[0]);
14365   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14366   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14367                      EltNo);
14368 }
14369
14370 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14371 /// generation and convert it from being a bunch of shuffles and extracts
14372 /// to a simple store and scalar loads to extract the elements.
14373 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14374                                          TargetLowering::DAGCombinerInfo &DCI) {
14375   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14376   if (NewOp.getNode())
14377     return NewOp;
14378
14379   SDValue InputVector = N->getOperand(0);
14380
14381   // Only operate on vectors of 4 elements, where the alternative shuffling
14382   // gets to be more expensive.
14383   if (InputVector.getValueType() != MVT::v4i32)
14384     return SDValue();
14385
14386   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14387   // single use which is a sign-extend or zero-extend, and all elements are
14388   // used.
14389   SmallVector<SDNode *, 4> Uses;
14390   unsigned ExtractedElements = 0;
14391   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14392        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14393     if (UI.getUse().getResNo() != InputVector.getResNo())
14394       return SDValue();
14395
14396     SDNode *Extract = *UI;
14397     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14398       return SDValue();
14399
14400     if (Extract->getValueType(0) != MVT::i32)
14401       return SDValue();
14402     if (!Extract->hasOneUse())
14403       return SDValue();
14404     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14405         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14406       return SDValue();
14407     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14408       return SDValue();
14409
14410     // Record which element was extracted.
14411     ExtractedElements |=
14412       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14413
14414     Uses.push_back(Extract);
14415   }
14416
14417   // If not all the elements were used, this may not be worthwhile.
14418   if (ExtractedElements != 15)
14419     return SDValue();
14420
14421   // Ok, we've now decided to do the transformation.
14422   DebugLoc dl = InputVector.getDebugLoc();
14423
14424   // Store the value to a temporary stack slot.
14425   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14426   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14427                             MachinePointerInfo(), false, false, 0);
14428
14429   // Replace each use (extract) with a load of the appropriate element.
14430   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14431        UE = Uses.end(); UI != UE; ++UI) {
14432     SDNode *Extract = *UI;
14433
14434     // cOMpute the element's address.
14435     SDValue Idx = Extract->getOperand(1);
14436     unsigned EltSize =
14437         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14438     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14439     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14440     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14441
14442     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14443                                      StackPtr, OffsetVal);
14444
14445     // Load the scalar.
14446     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14447                                      ScalarAddr, MachinePointerInfo(),
14448                                      false, false, false, 0);
14449
14450     // Replace the exact with the load.
14451     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14452   }
14453
14454   // The replacement was made in place; don't return anything.
14455   return SDValue();
14456 }
14457
14458 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14459 /// nodes.
14460 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14461                                     TargetLowering::DAGCombinerInfo &DCI,
14462                                     const X86Subtarget *Subtarget) {
14463   DebugLoc DL = N->getDebugLoc();
14464   SDValue Cond = N->getOperand(0);
14465   // Get the LHS/RHS of the select.
14466   SDValue LHS = N->getOperand(1);
14467   SDValue RHS = N->getOperand(2);
14468   EVT VT = LHS.getValueType();
14469
14470   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14471   // instructions match the semantics of the common C idiom x<y?x:y but not
14472   // x<=y?x:y, because of how they handle negative zero (which can be
14473   // ignored in unsafe-math mode).
14474   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14475       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14476       (Subtarget->hasSSE2() ||
14477        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14478     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14479
14480     unsigned Opcode = 0;
14481     // Check for x CC y ? x : y.
14482     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14483         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14484       switch (CC) {
14485       default: break;
14486       case ISD::SETULT:
14487         // Converting this to a min would handle NaNs incorrectly, and swapping
14488         // the operands would cause it to handle comparisons between positive
14489         // and negative zero incorrectly.
14490         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14491           if (!DAG.getTarget().Options.UnsafeFPMath &&
14492               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14493             break;
14494           std::swap(LHS, RHS);
14495         }
14496         Opcode = X86ISD::FMIN;
14497         break;
14498       case ISD::SETOLE:
14499         // Converting this to a min would handle comparisons between positive
14500         // and negative zero incorrectly.
14501         if (!DAG.getTarget().Options.UnsafeFPMath &&
14502             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14503           break;
14504         Opcode = X86ISD::FMIN;
14505         break;
14506       case ISD::SETULE:
14507         // Converting this to a min would handle both negative zeros and NaNs
14508         // incorrectly, but we can swap the operands to fix both.
14509         std::swap(LHS, RHS);
14510       case ISD::SETOLT:
14511       case ISD::SETLT:
14512       case ISD::SETLE:
14513         Opcode = X86ISD::FMIN;
14514         break;
14515
14516       case ISD::SETOGE:
14517         // Converting this to a max would handle comparisons between positive
14518         // and negative zero incorrectly.
14519         if (!DAG.getTarget().Options.UnsafeFPMath &&
14520             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14521           break;
14522         Opcode = X86ISD::FMAX;
14523         break;
14524       case ISD::SETUGT:
14525         // Converting this to a max would handle NaNs incorrectly, and swapping
14526         // the operands would cause it to handle comparisons between positive
14527         // and negative zero incorrectly.
14528         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14529           if (!DAG.getTarget().Options.UnsafeFPMath &&
14530               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14531             break;
14532           std::swap(LHS, RHS);
14533         }
14534         Opcode = X86ISD::FMAX;
14535         break;
14536       case ISD::SETUGE:
14537         // Converting this to a max would handle both negative zeros and NaNs
14538         // incorrectly, but we can swap the operands to fix both.
14539         std::swap(LHS, RHS);
14540       case ISD::SETOGT:
14541       case ISD::SETGT:
14542       case ISD::SETGE:
14543         Opcode = X86ISD::FMAX;
14544         break;
14545       }
14546     // Check for x CC y ? y : x -- a min/max with reversed arms.
14547     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14548                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14549       switch (CC) {
14550       default: break;
14551       case ISD::SETOGE:
14552         // Converting this to a min would handle comparisons between positive
14553         // and negative zero incorrectly, and swapping the operands would
14554         // cause it to handle NaNs incorrectly.
14555         if (!DAG.getTarget().Options.UnsafeFPMath &&
14556             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14557           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14558             break;
14559           std::swap(LHS, RHS);
14560         }
14561         Opcode = X86ISD::FMIN;
14562         break;
14563       case ISD::SETUGT:
14564         // Converting this to a min would handle NaNs incorrectly.
14565         if (!DAG.getTarget().Options.UnsafeFPMath &&
14566             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14567           break;
14568         Opcode = X86ISD::FMIN;
14569         break;
14570       case ISD::SETUGE:
14571         // Converting this to a min would handle both negative zeros and NaNs
14572         // incorrectly, but we can swap the operands to fix both.
14573         std::swap(LHS, RHS);
14574       case ISD::SETOGT:
14575       case ISD::SETGT:
14576       case ISD::SETGE:
14577         Opcode = X86ISD::FMIN;
14578         break;
14579
14580       case ISD::SETULT:
14581         // Converting this to a max would handle NaNs incorrectly.
14582         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14583           break;
14584         Opcode = X86ISD::FMAX;
14585         break;
14586       case ISD::SETOLE:
14587         // Converting this to a max would handle comparisons between positive
14588         // and negative zero incorrectly, and swapping the operands would
14589         // cause it to handle NaNs incorrectly.
14590         if (!DAG.getTarget().Options.UnsafeFPMath &&
14591             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14592           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14593             break;
14594           std::swap(LHS, RHS);
14595         }
14596         Opcode = X86ISD::FMAX;
14597         break;
14598       case ISD::SETULE:
14599         // Converting this to a max would handle both negative zeros and NaNs
14600         // incorrectly, but we can swap the operands to fix both.
14601         std::swap(LHS, RHS);
14602       case ISD::SETOLT:
14603       case ISD::SETLT:
14604       case ISD::SETLE:
14605         Opcode = X86ISD::FMAX;
14606         break;
14607       }
14608     }
14609
14610     if (Opcode)
14611       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14612   }
14613
14614   // If this is a select between two integer constants, try to do some
14615   // optimizations.
14616   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14617     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14618       // Don't do this for crazy integer types.
14619       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14620         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14621         // so that TrueC (the true value) is larger than FalseC.
14622         bool NeedsCondInvert = false;
14623
14624         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14625             // Efficiently invertible.
14626             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14627              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14628               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14629           NeedsCondInvert = true;
14630           std::swap(TrueC, FalseC);
14631         }
14632
14633         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14634         if (FalseC->getAPIntValue() == 0 &&
14635             TrueC->getAPIntValue().isPowerOf2()) {
14636           if (NeedsCondInvert) // Invert the condition if needed.
14637             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14638                                DAG.getConstant(1, Cond.getValueType()));
14639
14640           // Zero extend the condition if needed.
14641           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14642
14643           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14644           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14645                              DAG.getConstant(ShAmt, MVT::i8));
14646         }
14647
14648         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14649         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14650           if (NeedsCondInvert) // Invert the condition if needed.
14651             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14652                                DAG.getConstant(1, Cond.getValueType()));
14653
14654           // Zero extend the condition if needed.
14655           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14656                              FalseC->getValueType(0), Cond);
14657           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14658                              SDValue(FalseC, 0));
14659         }
14660
14661         // Optimize cases that will turn into an LEA instruction.  This requires
14662         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14663         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14664           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14665           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14666
14667           bool isFastMultiplier = false;
14668           if (Diff < 10) {
14669             switch ((unsigned char)Diff) {
14670               default: break;
14671               case 1:  // result = add base, cond
14672               case 2:  // result = lea base(    , cond*2)
14673               case 3:  // result = lea base(cond, cond*2)
14674               case 4:  // result = lea base(    , cond*4)
14675               case 5:  // result = lea base(cond, cond*4)
14676               case 8:  // result = lea base(    , cond*8)
14677               case 9:  // result = lea base(cond, cond*8)
14678                 isFastMultiplier = true;
14679                 break;
14680             }
14681           }
14682
14683           if (isFastMultiplier) {
14684             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14685             if (NeedsCondInvert) // Invert the condition if needed.
14686               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14687                                  DAG.getConstant(1, Cond.getValueType()));
14688
14689             // Zero extend the condition if needed.
14690             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14691                                Cond);
14692             // Scale the condition by the difference.
14693             if (Diff != 1)
14694               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14695                                  DAG.getConstant(Diff, Cond.getValueType()));
14696
14697             // Add the base if non-zero.
14698             if (FalseC->getAPIntValue() != 0)
14699               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14700                                  SDValue(FalseC, 0));
14701             return Cond;
14702           }
14703         }
14704       }
14705   }
14706
14707   // Canonicalize max and min:
14708   // (x > y) ? x : y -> (x >= y) ? x : y
14709   // (x < y) ? x : y -> (x <= y) ? x : y
14710   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14711   // the need for an extra compare
14712   // against zero. e.g.
14713   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14714   // subl   %esi, %edi
14715   // testl  %edi, %edi
14716   // movl   $0, %eax
14717   // cmovgl %edi, %eax
14718   // =>
14719   // xorl   %eax, %eax
14720   // subl   %esi, $edi
14721   // cmovsl %eax, %edi
14722   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14723       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14724       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14725     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14726     switch (CC) {
14727     default: break;
14728     case ISD::SETLT:
14729     case ISD::SETGT: {
14730       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14731       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14732                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14733       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14734     }
14735     }
14736   }
14737
14738   // If we know that this node is legal then we know that it is going to be
14739   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14740   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14741   // to simplify previous instructions.
14742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14743   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14744       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14745     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14746
14747     // Don't optimize vector selects that map to mask-registers.
14748     if (BitWidth == 1)
14749       return SDValue();
14750
14751     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14752     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14753
14754     APInt KnownZero, KnownOne;
14755     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14756                                           DCI.isBeforeLegalizeOps());
14757     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14758         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14759       DCI.CommitTargetLoweringOpt(TLO);
14760   }
14761
14762   return SDValue();
14763 }
14764
14765 // Check whether a boolean test is testing a boolean value generated by
14766 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14767 // code.
14768 //
14769 // Simplify the following patterns:
14770 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14771 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14772 // to (Op EFLAGS Cond)
14773 //
14774 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14775 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14776 // to (Op EFLAGS !Cond)
14777 //
14778 // where Op could be BRCOND or CMOV.
14779 //
14780 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14781   // Quit if not CMP and SUB with its value result used.
14782   if (Cmp.getOpcode() != X86ISD::CMP &&
14783       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14784       return SDValue();
14785
14786   // Quit if not used as a boolean value.
14787   if (CC != X86::COND_E && CC != X86::COND_NE)
14788     return SDValue();
14789
14790   // Check CMP operands. One of them should be 0 or 1 and the other should be
14791   // an SetCC or extended from it.
14792   SDValue Op1 = Cmp.getOperand(0);
14793   SDValue Op2 = Cmp.getOperand(1);
14794
14795   SDValue SetCC;
14796   const ConstantSDNode* C = 0;
14797   bool needOppositeCond = (CC == X86::COND_E);
14798
14799   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14800     SetCC = Op2;
14801   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14802     SetCC = Op1;
14803   else // Quit if all operands are not constants.
14804     return SDValue();
14805
14806   if (C->getZExtValue() == 1)
14807     needOppositeCond = !needOppositeCond;
14808   else if (C->getZExtValue() != 0)
14809     // Quit if the constant is neither 0 or 1.
14810     return SDValue();
14811
14812   // Skip 'zext' node.
14813   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14814     SetCC = SetCC.getOperand(0);
14815
14816   switch (SetCC.getOpcode()) {
14817   case X86ISD::SETCC:
14818     // Set the condition code or opposite one if necessary.
14819     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14820     if (needOppositeCond)
14821       CC = X86::GetOppositeBranchCondition(CC);
14822     return SetCC.getOperand(1);
14823   case X86ISD::CMOV: {
14824     // Check whether false/true value has canonical one, i.e. 0 or 1.
14825     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14826     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14827     // Quit if true value is not a constant.
14828     if (!TVal)
14829       return SDValue();
14830     // Quit if false value is not a constant.
14831     if (!FVal) {
14832       // A special case for rdrand, where 0 is set if false cond is found.
14833       SDValue Op = SetCC.getOperand(0);
14834       if (Op.getOpcode() != X86ISD::RDRAND)
14835         return SDValue();
14836     }
14837     // Quit if false value is not the constant 0 or 1.
14838     bool FValIsFalse = true;
14839     if (FVal && FVal->getZExtValue() != 0) {
14840       if (FVal->getZExtValue() != 1)
14841         return SDValue();
14842       // If FVal is 1, opposite cond is needed.
14843       needOppositeCond = !needOppositeCond;
14844       FValIsFalse = false;
14845     }
14846     // Quit if TVal is not the constant opposite of FVal.
14847     if (FValIsFalse && TVal->getZExtValue() != 1)
14848       return SDValue();
14849     if (!FValIsFalse && TVal->getZExtValue() != 0)
14850       return SDValue();
14851     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14852     if (needOppositeCond)
14853       CC = X86::GetOppositeBranchCondition(CC);
14854     return SetCC.getOperand(3);
14855   }
14856   }
14857
14858   return SDValue();
14859 }
14860
14861 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14862 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14863                                   TargetLowering::DAGCombinerInfo &DCI,
14864                                   const X86Subtarget *Subtarget) {
14865   DebugLoc DL = N->getDebugLoc();
14866
14867   // If the flag operand isn't dead, don't touch this CMOV.
14868   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14869     return SDValue();
14870
14871   SDValue FalseOp = N->getOperand(0);
14872   SDValue TrueOp = N->getOperand(1);
14873   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14874   SDValue Cond = N->getOperand(3);
14875
14876   if (CC == X86::COND_E || CC == X86::COND_NE) {
14877     switch (Cond.getOpcode()) {
14878     default: break;
14879     case X86ISD::BSR:
14880     case X86ISD::BSF:
14881       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14882       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14883         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14884     }
14885   }
14886
14887   SDValue Flags;
14888
14889   Flags = checkBoolTestSetCCCombine(Cond, CC);
14890   if (Flags.getNode() &&
14891       // Extra check as FCMOV only supports a subset of X86 cond.
14892       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14893     SDValue Ops[] = { FalseOp, TrueOp,
14894                       DAG.getConstant(CC, MVT::i8), Flags };
14895     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14896                        Ops, array_lengthof(Ops));
14897   }
14898
14899   // If this is a select between two integer constants, try to do some
14900   // optimizations.  Note that the operands are ordered the opposite of SELECT
14901   // operands.
14902   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14903     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14904       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14905       // larger than FalseC (the false value).
14906       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14907         CC = X86::GetOppositeBranchCondition(CC);
14908         std::swap(TrueC, FalseC);
14909         std::swap(TrueOp, FalseOp);
14910       }
14911
14912       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14913       // This is efficient for any integer data type (including i8/i16) and
14914       // shift amount.
14915       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14916         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14917                            DAG.getConstant(CC, MVT::i8), Cond);
14918
14919         // Zero extend the condition if needed.
14920         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14921
14922         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14923         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14924                            DAG.getConstant(ShAmt, MVT::i8));
14925         if (N->getNumValues() == 2)  // Dead flag value?
14926           return DCI.CombineTo(N, Cond, SDValue());
14927         return Cond;
14928       }
14929
14930       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14931       // for any integer data type, including i8/i16.
14932       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14933         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14934                            DAG.getConstant(CC, MVT::i8), Cond);
14935
14936         // Zero extend the condition if needed.
14937         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14938                            FalseC->getValueType(0), Cond);
14939         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14940                            SDValue(FalseC, 0));
14941
14942         if (N->getNumValues() == 2)  // Dead flag value?
14943           return DCI.CombineTo(N, Cond, SDValue());
14944         return Cond;
14945       }
14946
14947       // Optimize cases that will turn into an LEA instruction.  This requires
14948       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14949       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14950         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14951         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14952
14953         bool isFastMultiplier = false;
14954         if (Diff < 10) {
14955           switch ((unsigned char)Diff) {
14956           default: break;
14957           case 1:  // result = add base, cond
14958           case 2:  // result = lea base(    , cond*2)
14959           case 3:  // result = lea base(cond, cond*2)
14960           case 4:  // result = lea base(    , cond*4)
14961           case 5:  // result = lea base(cond, cond*4)
14962           case 8:  // result = lea base(    , cond*8)
14963           case 9:  // result = lea base(cond, cond*8)
14964             isFastMultiplier = true;
14965             break;
14966           }
14967         }
14968
14969         if (isFastMultiplier) {
14970           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14971           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14972                              DAG.getConstant(CC, MVT::i8), Cond);
14973           // Zero extend the condition if needed.
14974           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14975                              Cond);
14976           // Scale the condition by the difference.
14977           if (Diff != 1)
14978             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14979                                DAG.getConstant(Diff, Cond.getValueType()));
14980
14981           // Add the base if non-zero.
14982           if (FalseC->getAPIntValue() != 0)
14983             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14984                                SDValue(FalseC, 0));
14985           if (N->getNumValues() == 2)  // Dead flag value?
14986             return DCI.CombineTo(N, Cond, SDValue());
14987           return Cond;
14988         }
14989       }
14990     }
14991   }
14992
14993   // Handle these cases:
14994   //   (select (x != c), e, c) -> select (x != c), e, x),
14995   //   (select (x == c), c, e) -> select (x == c), x, e)
14996   // where the c is an integer constant, and the "select" is the combination
14997   // of CMOV and CMP.
14998   //
14999   // The rationale for this change is that the conditional-move from a constant
15000   // needs two instructions, however, conditional-move from a register needs
15001   // only one instruction.
15002   //
15003   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15004   //  some instruction-combining opportunities. This opt needs to be
15005   //  postponed as late as possible.
15006   //
15007   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15008     // the DCI.xxxx conditions are provided to postpone the optimization as
15009     // late as possible.
15010
15011     ConstantSDNode *CmpAgainst = 0;
15012     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15013         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15014         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15015
15016       if (CC == X86::COND_NE &&
15017           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15018         CC = X86::GetOppositeBranchCondition(CC);
15019         std::swap(TrueOp, FalseOp);
15020       }
15021
15022       if (CC == X86::COND_E &&
15023           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15024         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15025                           DAG.getConstant(CC, MVT::i8), Cond };
15026         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15027                            array_lengthof(Ops));
15028       }
15029     }
15030   }
15031
15032   return SDValue();
15033 }
15034
15035
15036 /// PerformMulCombine - Optimize a single multiply with constant into two
15037 /// in order to implement it with two cheaper instructions, e.g.
15038 /// LEA + SHL, LEA + LEA.
15039 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15040                                  TargetLowering::DAGCombinerInfo &DCI) {
15041   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15042     return SDValue();
15043
15044   EVT VT = N->getValueType(0);
15045   if (VT != MVT::i64)
15046     return SDValue();
15047
15048   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15049   if (!C)
15050     return SDValue();
15051   uint64_t MulAmt = C->getZExtValue();
15052   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15053     return SDValue();
15054
15055   uint64_t MulAmt1 = 0;
15056   uint64_t MulAmt2 = 0;
15057   if ((MulAmt % 9) == 0) {
15058     MulAmt1 = 9;
15059     MulAmt2 = MulAmt / 9;
15060   } else if ((MulAmt % 5) == 0) {
15061     MulAmt1 = 5;
15062     MulAmt2 = MulAmt / 5;
15063   } else if ((MulAmt % 3) == 0) {
15064     MulAmt1 = 3;
15065     MulAmt2 = MulAmt / 3;
15066   }
15067   if (MulAmt2 &&
15068       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15069     DebugLoc DL = N->getDebugLoc();
15070
15071     if (isPowerOf2_64(MulAmt2) &&
15072         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15073       // If second multiplifer is pow2, issue it first. We want the multiply by
15074       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15075       // is an add.
15076       std::swap(MulAmt1, MulAmt2);
15077
15078     SDValue NewMul;
15079     if (isPowerOf2_64(MulAmt1))
15080       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15081                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15082     else
15083       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15084                            DAG.getConstant(MulAmt1, VT));
15085
15086     if (isPowerOf2_64(MulAmt2))
15087       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15088                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15089     else
15090       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15091                            DAG.getConstant(MulAmt2, VT));
15092
15093     // Do not add new nodes to DAG combiner worklist.
15094     DCI.CombineTo(N, NewMul, false);
15095   }
15096   return SDValue();
15097 }
15098
15099 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15100   SDValue N0 = N->getOperand(0);
15101   SDValue N1 = N->getOperand(1);
15102   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15103   EVT VT = N0.getValueType();
15104
15105   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15106   // since the result of setcc_c is all zero's or all ones.
15107   if (VT.isInteger() && !VT.isVector() &&
15108       N1C && N0.getOpcode() == ISD::AND &&
15109       N0.getOperand(1).getOpcode() == ISD::Constant) {
15110     SDValue N00 = N0.getOperand(0);
15111     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15112         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15113           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15114          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15115       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15116       APInt ShAmt = N1C->getAPIntValue();
15117       Mask = Mask.shl(ShAmt);
15118       if (Mask != 0)
15119         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15120                            N00, DAG.getConstant(Mask, VT));
15121     }
15122   }
15123
15124
15125   // Hardware support for vector shifts is sparse which makes us scalarize the
15126   // vector operations in many cases. Also, on sandybridge ADD is faster than
15127   // shl.
15128   // (shl V, 1) -> add V,V
15129   if (isSplatVector(N1.getNode())) {
15130     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15131     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15132     // We shift all of the values by one. In many cases we do not have
15133     // hardware support for this operation. This is better expressed as an ADD
15134     // of two values.
15135     if (N1C && (1 == N1C->getZExtValue())) {
15136       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15137     }
15138   }
15139
15140   return SDValue();
15141 }
15142
15143 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15144 ///                       when possible.
15145 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15146                                    TargetLowering::DAGCombinerInfo &DCI,
15147                                    const X86Subtarget *Subtarget) {
15148   EVT VT = N->getValueType(0);
15149   if (N->getOpcode() == ISD::SHL) {
15150     SDValue V = PerformSHLCombine(N, DAG);
15151     if (V.getNode()) return V;
15152   }
15153
15154   // On X86 with SSE2 support, we can transform this to a vector shift if
15155   // all elements are shifted by the same amount.  We can't do this in legalize
15156   // because the a constant vector is typically transformed to a constant pool
15157   // so we have no knowledge of the shift amount.
15158   if (!Subtarget->hasSSE2())
15159     return SDValue();
15160
15161   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15162       (!Subtarget->hasAVX2() ||
15163        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15164     return SDValue();
15165
15166   SDValue ShAmtOp = N->getOperand(1);
15167   EVT EltVT = VT.getVectorElementType();
15168   DebugLoc DL = N->getDebugLoc();
15169   SDValue BaseShAmt = SDValue();
15170   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15171     unsigned NumElts = VT.getVectorNumElements();
15172     unsigned i = 0;
15173     for (; i != NumElts; ++i) {
15174       SDValue Arg = ShAmtOp.getOperand(i);
15175       if (Arg.getOpcode() == ISD::UNDEF) continue;
15176       BaseShAmt = Arg;
15177       break;
15178     }
15179     // Handle the case where the build_vector is all undef
15180     // FIXME: Should DAG allow this?
15181     if (i == NumElts)
15182       return SDValue();
15183
15184     for (; i != NumElts; ++i) {
15185       SDValue Arg = ShAmtOp.getOperand(i);
15186       if (Arg.getOpcode() == ISD::UNDEF) continue;
15187       if (Arg != BaseShAmt) {
15188         return SDValue();
15189       }
15190     }
15191   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15192              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15193     SDValue InVec = ShAmtOp.getOperand(0);
15194     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15195       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15196       unsigned i = 0;
15197       for (; i != NumElts; ++i) {
15198         SDValue Arg = InVec.getOperand(i);
15199         if (Arg.getOpcode() == ISD::UNDEF) continue;
15200         BaseShAmt = Arg;
15201         break;
15202       }
15203     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15204        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15205          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15206          if (C->getZExtValue() == SplatIdx)
15207            BaseShAmt = InVec.getOperand(1);
15208        }
15209     }
15210     if (BaseShAmt.getNode() == 0) {
15211       // Don't create instructions with illegal types after legalize
15212       // types has run.
15213       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15214           !DCI.isBeforeLegalize())
15215         return SDValue();
15216
15217       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15218                               DAG.getIntPtrConstant(0));
15219     }
15220   } else
15221     return SDValue();
15222
15223   // The shift amount is an i32.
15224   if (EltVT.bitsGT(MVT::i32))
15225     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15226   else if (EltVT.bitsLT(MVT::i32))
15227     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15228
15229   // The shift amount is identical so we can do a vector shift.
15230   SDValue  ValOp = N->getOperand(0);
15231   switch (N->getOpcode()) {
15232   default:
15233     llvm_unreachable("Unknown shift opcode!");
15234   case ISD::SHL:
15235     switch (VT.getSimpleVT().SimpleTy) {
15236     default: return SDValue();
15237     case MVT::v2i64:
15238     case MVT::v4i32:
15239     case MVT::v8i16:
15240     case MVT::v4i64:
15241     case MVT::v8i32:
15242     case MVT::v16i16:
15243       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15244     }
15245   case ISD::SRA:
15246     switch (VT.getSimpleVT().SimpleTy) {
15247     default: return SDValue();
15248     case MVT::v4i32:
15249     case MVT::v8i16:
15250     case MVT::v8i32:
15251     case MVT::v16i16:
15252       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15253     }
15254   case ISD::SRL:
15255     switch (VT.getSimpleVT().SimpleTy) {
15256     default: return SDValue();
15257     case MVT::v2i64:
15258     case MVT::v4i32:
15259     case MVT::v8i16:
15260     case MVT::v4i64:
15261     case MVT::v8i32:
15262     case MVT::v16i16:
15263       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15264     }
15265   }
15266 }
15267
15268
15269 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15270 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15271 // and friends.  Likewise for OR -> CMPNEQSS.
15272 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15273                             TargetLowering::DAGCombinerInfo &DCI,
15274                             const X86Subtarget *Subtarget) {
15275   unsigned opcode;
15276
15277   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15278   // we're requiring SSE2 for both.
15279   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15280     SDValue N0 = N->getOperand(0);
15281     SDValue N1 = N->getOperand(1);
15282     SDValue CMP0 = N0->getOperand(1);
15283     SDValue CMP1 = N1->getOperand(1);
15284     DebugLoc DL = N->getDebugLoc();
15285
15286     // The SETCCs should both refer to the same CMP.
15287     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15288       return SDValue();
15289
15290     SDValue CMP00 = CMP0->getOperand(0);
15291     SDValue CMP01 = CMP0->getOperand(1);
15292     EVT     VT    = CMP00.getValueType();
15293
15294     if (VT == MVT::f32 || VT == MVT::f64) {
15295       bool ExpectingFlags = false;
15296       // Check for any users that want flags:
15297       for (SDNode::use_iterator UI = N->use_begin(),
15298              UE = N->use_end();
15299            !ExpectingFlags && UI != UE; ++UI)
15300         switch (UI->getOpcode()) {
15301         default:
15302         case ISD::BR_CC:
15303         case ISD::BRCOND:
15304         case ISD::SELECT:
15305           ExpectingFlags = true;
15306           break;
15307         case ISD::CopyToReg:
15308         case ISD::SIGN_EXTEND:
15309         case ISD::ZERO_EXTEND:
15310         case ISD::ANY_EXTEND:
15311           break;
15312         }
15313
15314       if (!ExpectingFlags) {
15315         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15316         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15317
15318         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15319           X86::CondCode tmp = cc0;
15320           cc0 = cc1;
15321           cc1 = tmp;
15322         }
15323
15324         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15325             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15326           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15327           X86ISD::NodeType NTOperator = is64BitFP ?
15328             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15329           // FIXME: need symbolic constants for these magic numbers.
15330           // See X86ATTInstPrinter.cpp:printSSECC().
15331           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15332           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15333                                               DAG.getConstant(x86cc, MVT::i8));
15334           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15335                                               OnesOrZeroesF);
15336           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15337                                       DAG.getConstant(1, MVT::i32));
15338           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15339           return OneBitOfTruth;
15340         }
15341       }
15342     }
15343   }
15344   return SDValue();
15345 }
15346
15347 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15348 /// so it can be folded inside ANDNP.
15349 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15350   EVT VT = N->getValueType(0);
15351
15352   // Match direct AllOnes for 128 and 256-bit vectors
15353   if (ISD::isBuildVectorAllOnes(N))
15354     return true;
15355
15356   // Look through a bit convert.
15357   if (N->getOpcode() == ISD::BITCAST)
15358     N = N->getOperand(0).getNode();
15359
15360   // Sometimes the operand may come from a insert_subvector building a 256-bit
15361   // allones vector
15362   if (VT.is256BitVector() &&
15363       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15364     SDValue V1 = N->getOperand(0);
15365     SDValue V2 = N->getOperand(1);
15366
15367     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15368         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15369         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15370         ISD::isBuildVectorAllOnes(V2.getNode()))
15371       return true;
15372   }
15373
15374   return false;
15375 }
15376
15377 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15378                                  TargetLowering::DAGCombinerInfo &DCI,
15379                                  const X86Subtarget *Subtarget) {
15380   if (DCI.isBeforeLegalizeOps())
15381     return SDValue();
15382
15383   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15384   if (R.getNode())
15385     return R;
15386
15387   EVT VT = N->getValueType(0);
15388
15389   // Create ANDN, BLSI, and BLSR instructions
15390   // BLSI is X & (-X)
15391   // BLSR is X & (X-1)
15392   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15393     SDValue N0 = N->getOperand(0);
15394     SDValue N1 = N->getOperand(1);
15395     DebugLoc DL = N->getDebugLoc();
15396
15397     // Check LHS for not
15398     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15399       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15400     // Check RHS for not
15401     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15402       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15403
15404     // Check LHS for neg
15405     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15406         isZero(N0.getOperand(0)))
15407       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15408
15409     // Check RHS for neg
15410     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15411         isZero(N1.getOperand(0)))
15412       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15413
15414     // Check LHS for X-1
15415     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15416         isAllOnes(N0.getOperand(1)))
15417       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15418
15419     // Check RHS for X-1
15420     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15421         isAllOnes(N1.getOperand(1)))
15422       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15423
15424     return SDValue();
15425   }
15426
15427   // Want to form ANDNP nodes:
15428   // 1) In the hopes of then easily combining them with OR and AND nodes
15429   //    to form PBLEND/PSIGN.
15430   // 2) To match ANDN packed intrinsics
15431   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15432     return SDValue();
15433
15434   SDValue N0 = N->getOperand(0);
15435   SDValue N1 = N->getOperand(1);
15436   DebugLoc DL = N->getDebugLoc();
15437
15438   // Check LHS for vnot
15439   if (N0.getOpcode() == ISD::XOR &&
15440       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15441       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15442     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15443
15444   // Check RHS for vnot
15445   if (N1.getOpcode() == ISD::XOR &&
15446       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15447       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15448     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15449
15450   return SDValue();
15451 }
15452
15453 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15454                                 TargetLowering::DAGCombinerInfo &DCI,
15455                                 const X86Subtarget *Subtarget) {
15456   if (DCI.isBeforeLegalizeOps())
15457     return SDValue();
15458
15459   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15460   if (R.getNode())
15461     return R;
15462
15463   EVT VT = N->getValueType(0);
15464
15465   SDValue N0 = N->getOperand(0);
15466   SDValue N1 = N->getOperand(1);
15467
15468   // look for psign/blend
15469   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15470     if (!Subtarget->hasSSSE3() ||
15471         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15472       return SDValue();
15473
15474     // Canonicalize pandn to RHS
15475     if (N0.getOpcode() == X86ISD::ANDNP)
15476       std::swap(N0, N1);
15477     // or (and (m, y), (pandn m, x))
15478     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15479       SDValue Mask = N1.getOperand(0);
15480       SDValue X    = N1.getOperand(1);
15481       SDValue Y;
15482       if (N0.getOperand(0) == Mask)
15483         Y = N0.getOperand(1);
15484       if (N0.getOperand(1) == Mask)
15485         Y = N0.getOperand(0);
15486
15487       // Check to see if the mask appeared in both the AND and ANDNP and
15488       if (!Y.getNode())
15489         return SDValue();
15490
15491       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15492       // Look through mask bitcast.
15493       if (Mask.getOpcode() == ISD::BITCAST)
15494         Mask = Mask.getOperand(0);
15495       if (X.getOpcode() == ISD::BITCAST)
15496         X = X.getOperand(0);
15497       if (Y.getOpcode() == ISD::BITCAST)
15498         Y = Y.getOperand(0);
15499
15500       EVT MaskVT = Mask.getValueType();
15501
15502       // Validate that the Mask operand is a vector sra node.
15503       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15504       // there is no psrai.b
15505       if (Mask.getOpcode() != X86ISD::VSRAI)
15506         return SDValue();
15507
15508       // Check that the SRA is all signbits.
15509       SDValue SraC = Mask.getOperand(1);
15510       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15511       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15512       if ((SraAmt + 1) != EltBits)
15513         return SDValue();
15514
15515       DebugLoc DL = N->getDebugLoc();
15516
15517       // Now we know we at least have a plendvb with the mask val.  See if
15518       // we can form a psignb/w/d.
15519       // psign = x.type == y.type == mask.type && y = sub(0, x);
15520       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15521           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15522           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15523         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15524                "Unsupported VT for PSIGN");
15525         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15526         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15527       }
15528       // PBLENDVB only available on SSE 4.1
15529       if (!Subtarget->hasSSE41())
15530         return SDValue();
15531
15532       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15533
15534       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15535       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15536       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15537       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15538       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15539     }
15540   }
15541
15542   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15543     return SDValue();
15544
15545   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15546   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15547     std::swap(N0, N1);
15548   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15549     return SDValue();
15550   if (!N0.hasOneUse() || !N1.hasOneUse())
15551     return SDValue();
15552
15553   SDValue ShAmt0 = N0.getOperand(1);
15554   if (ShAmt0.getValueType() != MVT::i8)
15555     return SDValue();
15556   SDValue ShAmt1 = N1.getOperand(1);
15557   if (ShAmt1.getValueType() != MVT::i8)
15558     return SDValue();
15559   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15560     ShAmt0 = ShAmt0.getOperand(0);
15561   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15562     ShAmt1 = ShAmt1.getOperand(0);
15563
15564   DebugLoc DL = N->getDebugLoc();
15565   unsigned Opc = X86ISD::SHLD;
15566   SDValue Op0 = N0.getOperand(0);
15567   SDValue Op1 = N1.getOperand(0);
15568   if (ShAmt0.getOpcode() == ISD::SUB) {
15569     Opc = X86ISD::SHRD;
15570     std::swap(Op0, Op1);
15571     std::swap(ShAmt0, ShAmt1);
15572   }
15573
15574   unsigned Bits = VT.getSizeInBits();
15575   if (ShAmt1.getOpcode() == ISD::SUB) {
15576     SDValue Sum = ShAmt1.getOperand(0);
15577     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15578       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15579       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15580         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15581       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15582         return DAG.getNode(Opc, DL, VT,
15583                            Op0, Op1,
15584                            DAG.getNode(ISD::TRUNCATE, DL,
15585                                        MVT::i8, ShAmt0));
15586     }
15587   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15588     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15589     if (ShAmt0C &&
15590         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15591       return DAG.getNode(Opc, DL, VT,
15592                          N0.getOperand(0), N1.getOperand(0),
15593                          DAG.getNode(ISD::TRUNCATE, DL,
15594                                        MVT::i8, ShAmt0));
15595   }
15596
15597   return SDValue();
15598 }
15599
15600 // Generate NEG and CMOV for integer abs.
15601 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15602   EVT VT = N->getValueType(0);
15603
15604   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15605   // 8-bit integer abs to NEG and CMOV.
15606   if (VT.isInteger() && VT.getSizeInBits() == 8)
15607     return SDValue();
15608
15609   SDValue N0 = N->getOperand(0);
15610   SDValue N1 = N->getOperand(1);
15611   DebugLoc DL = N->getDebugLoc();
15612
15613   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15614   // and change it to SUB and CMOV.
15615   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15616       N0.getOpcode() == ISD::ADD &&
15617       N0.getOperand(1) == N1 &&
15618       N1.getOpcode() == ISD::SRA &&
15619       N1.getOperand(0) == N0.getOperand(0))
15620     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15621       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15622         // Generate SUB & CMOV.
15623         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15624                                   DAG.getConstant(0, VT), N0.getOperand(0));
15625
15626         SDValue Ops[] = { N0.getOperand(0), Neg,
15627                           DAG.getConstant(X86::COND_GE, MVT::i8),
15628                           SDValue(Neg.getNode(), 1) };
15629         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15630                            Ops, array_lengthof(Ops));
15631       }
15632   return SDValue();
15633 }
15634
15635 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15636 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15637                                  TargetLowering::DAGCombinerInfo &DCI,
15638                                  const X86Subtarget *Subtarget) {
15639   if (DCI.isBeforeLegalizeOps())
15640     return SDValue();
15641
15642   if (Subtarget->hasCMov()) {
15643     SDValue RV = performIntegerAbsCombine(N, DAG);
15644     if (RV.getNode())
15645       return RV;
15646   }
15647
15648   // Try forming BMI if it is available.
15649   if (!Subtarget->hasBMI())
15650     return SDValue();
15651
15652   EVT VT = N->getValueType(0);
15653
15654   if (VT != MVT::i32 && VT != MVT::i64)
15655     return SDValue();
15656
15657   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15658
15659   // Create BLSMSK instructions by finding X ^ (X-1)
15660   SDValue N0 = N->getOperand(0);
15661   SDValue N1 = N->getOperand(1);
15662   DebugLoc DL = N->getDebugLoc();
15663
15664   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15665       isAllOnes(N0.getOperand(1)))
15666     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15667
15668   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15669       isAllOnes(N1.getOperand(1)))
15670     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15671
15672   return SDValue();
15673 }
15674
15675 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15676 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15677                                   TargetLowering::DAGCombinerInfo &DCI,
15678                                   const X86Subtarget *Subtarget) {
15679   LoadSDNode *Ld = cast<LoadSDNode>(N);
15680   EVT RegVT = Ld->getValueType(0);
15681   EVT MemVT = Ld->getMemoryVT();
15682   DebugLoc dl = Ld->getDebugLoc();
15683   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15684
15685   ISD::LoadExtType Ext = Ld->getExtensionType();
15686
15687   // If this is a vector EXT Load then attempt to optimize it using a
15688   // shuffle. We need SSSE3 shuffles.
15689   // TODO: It is possible to support ZExt by zeroing the undef values
15690   // during the shuffle phase or after the shuffle.
15691   if (RegVT.isVector() && RegVT.isInteger() &&
15692       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15693     assert(MemVT != RegVT && "Cannot extend to the same type");
15694     assert(MemVT.isVector() && "Must load a vector from memory");
15695
15696     unsigned NumElems = RegVT.getVectorNumElements();
15697     unsigned RegSz = RegVT.getSizeInBits();
15698     unsigned MemSz = MemVT.getSizeInBits();
15699     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15700
15701     // All sizes must be a power of two.
15702     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15703       return SDValue();
15704
15705     // Attempt to load the original value using scalar loads.
15706     // Find the largest scalar type that divides the total loaded size.
15707     MVT SclrLoadTy = MVT::i8;
15708     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15709          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15710       MVT Tp = (MVT::SimpleValueType)tp;
15711       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15712         SclrLoadTy = Tp;
15713       }
15714     }
15715
15716     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15717     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15718         (64 <= MemSz))
15719       SclrLoadTy = MVT::f64;
15720
15721     // Calculate the number of scalar loads that we need to perform
15722     // in order to load our vector from memory.
15723     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15724
15725     // Represent our vector as a sequence of elements which are the
15726     // largest scalar that we can load.
15727     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15728       RegSz/SclrLoadTy.getSizeInBits());
15729
15730     // Represent the data using the same element type that is stored in
15731     // memory. In practice, we ''widen'' MemVT.
15732     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15733                                   RegSz/MemVT.getScalarType().getSizeInBits());
15734
15735     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15736       "Invalid vector type");
15737
15738     // We can't shuffle using an illegal type.
15739     if (!TLI.isTypeLegal(WideVecVT))
15740       return SDValue();
15741
15742     SmallVector<SDValue, 8> Chains;
15743     SDValue Ptr = Ld->getBasePtr();
15744     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15745                                         TLI.getPointerTy());
15746     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15747
15748     for (unsigned i = 0; i < NumLoads; ++i) {
15749       // Perform a single load.
15750       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15751                                        Ptr, Ld->getPointerInfo(),
15752                                        Ld->isVolatile(), Ld->isNonTemporal(),
15753                                        Ld->isInvariant(), Ld->getAlignment());
15754       Chains.push_back(ScalarLoad.getValue(1));
15755       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15756       // another round of DAGCombining.
15757       if (i == 0)
15758         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15759       else
15760         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15761                           ScalarLoad, DAG.getIntPtrConstant(i));
15762
15763       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15764     }
15765
15766     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15767                                Chains.size());
15768
15769     // Bitcast the loaded value to a vector of the original element type, in
15770     // the size of the target vector type.
15771     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15772     unsigned SizeRatio = RegSz/MemSz;
15773
15774     // Redistribute the loaded elements into the different locations.
15775     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15776     for (unsigned i = 0; i != NumElems; ++i)
15777       ShuffleVec[i*SizeRatio] = i;
15778
15779     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15780                                          DAG.getUNDEF(WideVecVT),
15781                                          &ShuffleVec[0]);
15782
15783     // Bitcast to the requested type.
15784     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15785     // Replace the original load with the new sequence
15786     // and return the new chain.
15787     return DCI.CombineTo(N, Shuff, TF, true);
15788   }
15789
15790   return SDValue();
15791 }
15792
15793 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15794 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15795                                    const X86Subtarget *Subtarget) {
15796   StoreSDNode *St = cast<StoreSDNode>(N);
15797   EVT VT = St->getValue().getValueType();
15798   EVT StVT = St->getMemoryVT();
15799   DebugLoc dl = St->getDebugLoc();
15800   SDValue StoredVal = St->getOperand(1);
15801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15802
15803   // If we are saving a concatenation of two XMM registers, perform two stores.
15804   // On Sandy Bridge, 256-bit memory operations are executed by two
15805   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15806   // memory  operation.
15807   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15808       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15809       StoredVal.getNumOperands() == 2) {
15810     SDValue Value0 = StoredVal.getOperand(0);
15811     SDValue Value1 = StoredVal.getOperand(1);
15812
15813     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15814     SDValue Ptr0 = St->getBasePtr();
15815     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15816
15817     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15818                                 St->getPointerInfo(), St->isVolatile(),
15819                                 St->isNonTemporal(), St->getAlignment());
15820     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15821                                 St->getPointerInfo(), St->isVolatile(),
15822                                 St->isNonTemporal(), St->getAlignment());
15823     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15824   }
15825
15826   // Optimize trunc store (of multiple scalars) to shuffle and store.
15827   // First, pack all of the elements in one place. Next, store to memory
15828   // in fewer chunks.
15829   if (St->isTruncatingStore() && VT.isVector()) {
15830     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15831     unsigned NumElems = VT.getVectorNumElements();
15832     assert(StVT != VT && "Cannot truncate to the same type");
15833     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15834     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15835
15836     // From, To sizes and ElemCount must be pow of two
15837     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15838     // We are going to use the original vector elt for storing.
15839     // Accumulated smaller vector elements must be a multiple of the store size.
15840     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15841
15842     unsigned SizeRatio  = FromSz / ToSz;
15843
15844     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15845
15846     // Create a type on which we perform the shuffle
15847     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15848             StVT.getScalarType(), NumElems*SizeRatio);
15849
15850     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15851
15852     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15853     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15854     for (unsigned i = 0; i != NumElems; ++i)
15855       ShuffleVec[i] = i * SizeRatio;
15856
15857     // Can't shuffle using an illegal type.
15858     if (!TLI.isTypeLegal(WideVecVT))
15859       return SDValue();
15860
15861     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15862                                          DAG.getUNDEF(WideVecVT),
15863                                          &ShuffleVec[0]);
15864     // At this point all of the data is stored at the bottom of the
15865     // register. We now need to save it to mem.
15866
15867     // Find the largest store unit
15868     MVT StoreType = MVT::i8;
15869     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15870          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15871       MVT Tp = (MVT::SimpleValueType)tp;
15872       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15873         StoreType = Tp;
15874     }
15875
15876     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15877     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15878         (64 <= NumElems * ToSz))
15879       StoreType = MVT::f64;
15880
15881     // Bitcast the original vector into a vector of store-size units
15882     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15883             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15884     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15885     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15886     SmallVector<SDValue, 8> Chains;
15887     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15888                                         TLI.getPointerTy());
15889     SDValue Ptr = St->getBasePtr();
15890
15891     // Perform one or more big stores into memory.
15892     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15893       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15894                                    StoreType, ShuffWide,
15895                                    DAG.getIntPtrConstant(i));
15896       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15897                                 St->getPointerInfo(), St->isVolatile(),
15898                                 St->isNonTemporal(), St->getAlignment());
15899       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15900       Chains.push_back(Ch);
15901     }
15902
15903     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15904                                Chains.size());
15905   }
15906
15907
15908   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15909   // the FP state in cases where an emms may be missing.
15910   // A preferable solution to the general problem is to figure out the right
15911   // places to insert EMMS.  This qualifies as a quick hack.
15912
15913   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15914   if (VT.getSizeInBits() != 64)
15915     return SDValue();
15916
15917   const Function *F = DAG.getMachineFunction().getFunction();
15918   bool NoImplicitFloatOps = F->getFnAttributes().
15919     hasAttribute(Attributes::NoImplicitFloat);
15920   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15921                      && Subtarget->hasSSE2();
15922   if ((VT.isVector() ||
15923        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15924       isa<LoadSDNode>(St->getValue()) &&
15925       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15926       St->getChain().hasOneUse() && !St->isVolatile()) {
15927     SDNode* LdVal = St->getValue().getNode();
15928     LoadSDNode *Ld = 0;
15929     int TokenFactorIndex = -1;
15930     SmallVector<SDValue, 8> Ops;
15931     SDNode* ChainVal = St->getChain().getNode();
15932     // Must be a store of a load.  We currently handle two cases:  the load
15933     // is a direct child, and it's under an intervening TokenFactor.  It is
15934     // possible to dig deeper under nested TokenFactors.
15935     if (ChainVal == LdVal)
15936       Ld = cast<LoadSDNode>(St->getChain());
15937     else if (St->getValue().hasOneUse() &&
15938              ChainVal->getOpcode() == ISD::TokenFactor) {
15939       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15940         if (ChainVal->getOperand(i).getNode() == LdVal) {
15941           TokenFactorIndex = i;
15942           Ld = cast<LoadSDNode>(St->getValue());
15943         } else
15944           Ops.push_back(ChainVal->getOperand(i));
15945       }
15946     }
15947
15948     if (!Ld || !ISD::isNormalLoad(Ld))
15949       return SDValue();
15950
15951     // If this is not the MMX case, i.e. we are just turning i64 load/store
15952     // into f64 load/store, avoid the transformation if there are multiple
15953     // uses of the loaded value.
15954     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15955       return SDValue();
15956
15957     DebugLoc LdDL = Ld->getDebugLoc();
15958     DebugLoc StDL = N->getDebugLoc();
15959     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15960     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15961     // pair instead.
15962     if (Subtarget->is64Bit() || F64IsLegal) {
15963       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15964       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15965                                   Ld->getPointerInfo(), Ld->isVolatile(),
15966                                   Ld->isNonTemporal(), Ld->isInvariant(),
15967                                   Ld->getAlignment());
15968       SDValue NewChain = NewLd.getValue(1);
15969       if (TokenFactorIndex != -1) {
15970         Ops.push_back(NewChain);
15971         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15972                                Ops.size());
15973       }
15974       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15975                           St->getPointerInfo(),
15976                           St->isVolatile(), St->isNonTemporal(),
15977                           St->getAlignment());
15978     }
15979
15980     // Otherwise, lower to two pairs of 32-bit loads / stores.
15981     SDValue LoAddr = Ld->getBasePtr();
15982     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15983                                  DAG.getConstant(4, MVT::i32));
15984
15985     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15986                                Ld->getPointerInfo(),
15987                                Ld->isVolatile(), Ld->isNonTemporal(),
15988                                Ld->isInvariant(), Ld->getAlignment());
15989     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15990                                Ld->getPointerInfo().getWithOffset(4),
15991                                Ld->isVolatile(), Ld->isNonTemporal(),
15992                                Ld->isInvariant(),
15993                                MinAlign(Ld->getAlignment(), 4));
15994
15995     SDValue NewChain = LoLd.getValue(1);
15996     if (TokenFactorIndex != -1) {
15997       Ops.push_back(LoLd);
15998       Ops.push_back(HiLd);
15999       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16000                              Ops.size());
16001     }
16002
16003     LoAddr = St->getBasePtr();
16004     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16005                          DAG.getConstant(4, MVT::i32));
16006
16007     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16008                                 St->getPointerInfo(),
16009                                 St->isVolatile(), St->isNonTemporal(),
16010                                 St->getAlignment());
16011     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16012                                 St->getPointerInfo().getWithOffset(4),
16013                                 St->isVolatile(),
16014                                 St->isNonTemporal(),
16015                                 MinAlign(St->getAlignment(), 4));
16016     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16017   }
16018   return SDValue();
16019 }
16020
16021 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16022 /// and return the operands for the horizontal operation in LHS and RHS.  A
16023 /// horizontal operation performs the binary operation on successive elements
16024 /// of its first operand, then on successive elements of its second operand,
16025 /// returning the resulting values in a vector.  For example, if
16026 ///   A = < float a0, float a1, float a2, float a3 >
16027 /// and
16028 ///   B = < float b0, float b1, float b2, float b3 >
16029 /// then the result of doing a horizontal operation on A and B is
16030 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16031 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16032 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16033 /// set to A, RHS to B, and the routine returns 'true'.
16034 /// Note that the binary operation should have the property that if one of the
16035 /// operands is UNDEF then the result is UNDEF.
16036 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16037   // Look for the following pattern: if
16038   //   A = < float a0, float a1, float a2, float a3 >
16039   //   B = < float b0, float b1, float b2, float b3 >
16040   // and
16041   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16042   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16043   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16044   // which is A horizontal-op B.
16045
16046   // At least one of the operands should be a vector shuffle.
16047   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16048       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16049     return false;
16050
16051   EVT VT = LHS.getValueType();
16052
16053   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16054          "Unsupported vector type for horizontal add/sub");
16055
16056   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16057   // operate independently on 128-bit lanes.
16058   unsigned NumElts = VT.getVectorNumElements();
16059   unsigned NumLanes = VT.getSizeInBits()/128;
16060   unsigned NumLaneElts = NumElts / NumLanes;
16061   assert((NumLaneElts % 2 == 0) &&
16062          "Vector type should have an even number of elements in each lane");
16063   unsigned HalfLaneElts = NumLaneElts/2;
16064
16065   // View LHS in the form
16066   //   LHS = VECTOR_SHUFFLE A, B, LMask
16067   // If LHS is not a shuffle then pretend it is the shuffle
16068   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16069   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16070   // type VT.
16071   SDValue A, B;
16072   SmallVector<int, 16> LMask(NumElts);
16073   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16074     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16075       A = LHS.getOperand(0);
16076     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16077       B = LHS.getOperand(1);
16078     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16079     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16080   } else {
16081     if (LHS.getOpcode() != ISD::UNDEF)
16082       A = LHS;
16083     for (unsigned i = 0; i != NumElts; ++i)
16084       LMask[i] = i;
16085   }
16086
16087   // Likewise, view RHS in the form
16088   //   RHS = VECTOR_SHUFFLE C, D, RMask
16089   SDValue C, D;
16090   SmallVector<int, 16> RMask(NumElts);
16091   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16092     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16093       C = RHS.getOperand(0);
16094     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16095       D = RHS.getOperand(1);
16096     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16097     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16098   } else {
16099     if (RHS.getOpcode() != ISD::UNDEF)
16100       C = RHS;
16101     for (unsigned i = 0; i != NumElts; ++i)
16102       RMask[i] = i;
16103   }
16104
16105   // Check that the shuffles are both shuffling the same vectors.
16106   if (!(A == C && B == D) && !(A == D && B == C))
16107     return false;
16108
16109   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16110   if (!A.getNode() && !B.getNode())
16111     return false;
16112
16113   // If A and B occur in reverse order in RHS, then "swap" them (which means
16114   // rewriting the mask).
16115   if (A != C)
16116     CommuteVectorShuffleMask(RMask, NumElts);
16117
16118   // At this point LHS and RHS are equivalent to
16119   //   LHS = VECTOR_SHUFFLE A, B, LMask
16120   //   RHS = VECTOR_SHUFFLE A, B, RMask
16121   // Check that the masks correspond to performing a horizontal operation.
16122   for (unsigned i = 0; i != NumElts; ++i) {
16123     int LIdx = LMask[i], RIdx = RMask[i];
16124
16125     // Ignore any UNDEF components.
16126     if (LIdx < 0 || RIdx < 0 ||
16127         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16128         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16129       continue;
16130
16131     // Check that successive elements are being operated on.  If not, this is
16132     // not a horizontal operation.
16133     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16134     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16135     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16136     if (!(LIdx == Index && RIdx == Index + 1) &&
16137         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16138       return false;
16139   }
16140
16141   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16142   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16143   return true;
16144 }
16145
16146 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16147 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16148                                   const X86Subtarget *Subtarget) {
16149   EVT VT = N->getValueType(0);
16150   SDValue LHS = N->getOperand(0);
16151   SDValue RHS = N->getOperand(1);
16152
16153   // Try to synthesize horizontal adds from adds of shuffles.
16154   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16155        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16156       isHorizontalBinOp(LHS, RHS, true))
16157     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16158   return SDValue();
16159 }
16160
16161 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16162 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16163                                   const X86Subtarget *Subtarget) {
16164   EVT VT = N->getValueType(0);
16165   SDValue LHS = N->getOperand(0);
16166   SDValue RHS = N->getOperand(1);
16167
16168   // Try to synthesize horizontal subs from subs of shuffles.
16169   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16170        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16171       isHorizontalBinOp(LHS, RHS, false))
16172     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16173   return SDValue();
16174 }
16175
16176 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16177 /// X86ISD::FXOR nodes.
16178 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16179   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16180   // F[X]OR(0.0, x) -> x
16181   // F[X]OR(x, 0.0) -> x
16182   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16183     if (C->getValueAPF().isPosZero())
16184       return N->getOperand(1);
16185   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16186     if (C->getValueAPF().isPosZero())
16187       return N->getOperand(0);
16188   return SDValue();
16189 }
16190
16191 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16192 /// X86ISD::FMAX nodes.
16193 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16194   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16195
16196   // Only perform optimizations if UnsafeMath is used.
16197   if (!DAG.getTarget().Options.UnsafeFPMath)
16198     return SDValue();
16199
16200   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16201   // into FMINC and FMAXC, which are Commutative operations.
16202   unsigned NewOp = 0;
16203   switch (N->getOpcode()) {
16204     default: llvm_unreachable("unknown opcode");
16205     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16206     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16207   }
16208
16209   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16210                      N->getOperand(0), N->getOperand(1));
16211 }
16212
16213
16214 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16215 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16216   // FAND(0.0, x) -> 0.0
16217   // FAND(x, 0.0) -> 0.0
16218   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16219     if (C->getValueAPF().isPosZero())
16220       return N->getOperand(0);
16221   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16222     if (C->getValueAPF().isPosZero())
16223       return N->getOperand(1);
16224   return SDValue();
16225 }
16226
16227 static SDValue PerformBTCombine(SDNode *N,
16228                                 SelectionDAG &DAG,
16229                                 TargetLowering::DAGCombinerInfo &DCI) {
16230   // BT ignores high bits in the bit index operand.
16231   SDValue Op1 = N->getOperand(1);
16232   if (Op1.hasOneUse()) {
16233     unsigned BitWidth = Op1.getValueSizeInBits();
16234     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16235     APInt KnownZero, KnownOne;
16236     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16237                                           !DCI.isBeforeLegalizeOps());
16238     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16239     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16240         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16241       DCI.CommitTargetLoweringOpt(TLO);
16242   }
16243   return SDValue();
16244 }
16245
16246 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16247   SDValue Op = N->getOperand(0);
16248   if (Op.getOpcode() == ISD::BITCAST)
16249     Op = Op.getOperand(0);
16250   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16251   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16252       VT.getVectorElementType().getSizeInBits() ==
16253       OpVT.getVectorElementType().getSizeInBits()) {
16254     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16255   }
16256   return SDValue();
16257 }
16258
16259 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16260                                   TargetLowering::DAGCombinerInfo &DCI,
16261                                   const X86Subtarget *Subtarget) {
16262   if (!DCI.isBeforeLegalizeOps())
16263     return SDValue();
16264
16265   if (!Subtarget->hasAVX())
16266     return SDValue();
16267
16268   EVT VT = N->getValueType(0);
16269   SDValue Op = N->getOperand(0);
16270   EVT OpVT = Op.getValueType();
16271   DebugLoc dl = N->getDebugLoc();
16272
16273   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16274       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16275
16276     if (Subtarget->hasAVX2())
16277       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16278
16279     // Optimize vectors in AVX mode
16280     // Sign extend  v8i16 to v8i32 and
16281     //              v4i32 to v4i64
16282     //
16283     // Divide input vector into two parts
16284     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16285     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16286     // concat the vectors to original VT
16287
16288     unsigned NumElems = OpVT.getVectorNumElements();
16289     SDValue Undef = DAG.getUNDEF(OpVT);
16290
16291     SmallVector<int,8> ShufMask1(NumElems, -1);
16292     for (unsigned i = 0; i != NumElems/2; ++i)
16293       ShufMask1[i] = i;
16294
16295     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16296
16297     SmallVector<int,8> ShufMask2(NumElems, -1);
16298     for (unsigned i = 0; i != NumElems/2; ++i)
16299       ShufMask2[i] = i + NumElems/2;
16300
16301     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16302
16303     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16304                                   VT.getVectorNumElements()/2);
16305
16306     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16307     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16308
16309     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16310   }
16311   return SDValue();
16312 }
16313
16314 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16315                                  const X86Subtarget* Subtarget) {
16316   DebugLoc dl = N->getDebugLoc();
16317   EVT VT = N->getValueType(0);
16318
16319   // Let legalize expand this if it isn't a legal type yet.
16320   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16321     return SDValue();
16322
16323   EVT ScalarVT = VT.getScalarType();
16324   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16325       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16326     return SDValue();
16327
16328   SDValue A = N->getOperand(0);
16329   SDValue B = N->getOperand(1);
16330   SDValue C = N->getOperand(2);
16331
16332   bool NegA = (A.getOpcode() == ISD::FNEG);
16333   bool NegB = (B.getOpcode() == ISD::FNEG);
16334   bool NegC = (C.getOpcode() == ISD::FNEG);
16335
16336   // Negative multiplication when NegA xor NegB
16337   bool NegMul = (NegA != NegB);
16338   if (NegA)
16339     A = A.getOperand(0);
16340   if (NegB)
16341     B = B.getOperand(0);
16342   if (NegC)
16343     C = C.getOperand(0);
16344
16345   unsigned Opcode;
16346   if (!NegMul)
16347     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16348   else
16349     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16350
16351   return DAG.getNode(Opcode, dl, VT, A, B, C);
16352 }
16353
16354 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16355                                   TargetLowering::DAGCombinerInfo &DCI,
16356                                   const X86Subtarget *Subtarget) {
16357   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16358   //           (and (i32 x86isd::setcc_carry), 1)
16359   // This eliminates the zext. This transformation is necessary because
16360   // ISD::SETCC is always legalized to i8.
16361   DebugLoc dl = N->getDebugLoc();
16362   SDValue N0 = N->getOperand(0);
16363   EVT VT = N->getValueType(0);
16364   EVT OpVT = N0.getValueType();
16365
16366   if (N0.getOpcode() == ISD::AND &&
16367       N0.hasOneUse() &&
16368       N0.getOperand(0).hasOneUse()) {
16369     SDValue N00 = N0.getOperand(0);
16370     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16371       return SDValue();
16372     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16373     if (!C || C->getZExtValue() != 1)
16374       return SDValue();
16375     return DAG.getNode(ISD::AND, dl, VT,
16376                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16377                                    N00.getOperand(0), N00.getOperand(1)),
16378                        DAG.getConstant(1, VT));
16379   }
16380
16381   // Optimize vectors in AVX mode:
16382   //
16383   //   v8i16 -> v8i32
16384   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16385   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16386   //   Concat upper and lower parts.
16387   //
16388   //   v4i32 -> v4i64
16389   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16390   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16391   //   Concat upper and lower parts.
16392   //
16393   if (!DCI.isBeforeLegalizeOps())
16394     return SDValue();
16395
16396   if (!Subtarget->hasAVX())
16397     return SDValue();
16398
16399   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16400       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16401
16402     if (Subtarget->hasAVX2())
16403       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16404
16405     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16406     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16407     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16408
16409     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16410                                VT.getVectorNumElements()/2);
16411
16412     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16413     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16414
16415     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16416   }
16417
16418   return SDValue();
16419 }
16420
16421 // Optimize x == -y --> x+y == 0
16422 //          x != -y --> x+y != 0
16423 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16424   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16425   SDValue LHS = N->getOperand(0);
16426   SDValue RHS = N->getOperand(1);
16427
16428   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16429     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16430       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16431         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16432                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16433         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16434                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16435       }
16436   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16437     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16438       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16439         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16440                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16441         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16442                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16443       }
16444   return SDValue();
16445 }
16446
16447 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16448 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16449                                    TargetLowering::DAGCombinerInfo &DCI,
16450                                    const X86Subtarget *Subtarget) {
16451   DebugLoc DL = N->getDebugLoc();
16452   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16453   SDValue EFLAGS = N->getOperand(1);
16454
16455   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16456   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16457   // cases.
16458   if (CC == X86::COND_B)
16459     return DAG.getNode(ISD::AND, DL, MVT::i8,
16460                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16461                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16462                        DAG.getConstant(1, MVT::i8));
16463
16464   SDValue Flags;
16465
16466   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16467   if (Flags.getNode()) {
16468     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16469     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16470   }
16471
16472   return SDValue();
16473 }
16474
16475 // Optimize branch condition evaluation.
16476 //
16477 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16478                                     TargetLowering::DAGCombinerInfo &DCI,
16479                                     const X86Subtarget *Subtarget) {
16480   DebugLoc DL = N->getDebugLoc();
16481   SDValue Chain = N->getOperand(0);
16482   SDValue Dest = N->getOperand(1);
16483   SDValue EFLAGS = N->getOperand(3);
16484   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16485
16486   SDValue Flags;
16487
16488   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16489   if (Flags.getNode()) {
16490     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16491     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16492                        Flags);
16493   }
16494
16495   return SDValue();
16496 }
16497
16498 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16499                                         const X86TargetLowering *XTLI) {
16500   SDValue Op0 = N->getOperand(0);
16501   EVT InVT = Op0->getValueType(0);
16502
16503   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16504   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16505     DebugLoc dl = N->getDebugLoc();
16506     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16507     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16508     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16509   }
16510
16511   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16512   // a 32-bit target where SSE doesn't support i64->FP operations.
16513   if (Op0.getOpcode() == ISD::LOAD) {
16514     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16515     EVT VT = Ld->getValueType(0);
16516     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16517         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16518         !XTLI->getSubtarget()->is64Bit() &&
16519         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16520       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16521                                           Ld->getChain(), Op0, DAG);
16522       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16523       return FILDChain;
16524     }
16525   }
16526   return SDValue();
16527 }
16528
16529 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16530 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16531                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16532   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16533   // the result is either zero or one (depending on the input carry bit).
16534   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16535   if (X86::isZeroNode(N->getOperand(0)) &&
16536       X86::isZeroNode(N->getOperand(1)) &&
16537       // We don't have a good way to replace an EFLAGS use, so only do this when
16538       // dead right now.
16539       SDValue(N, 1).use_empty()) {
16540     DebugLoc DL = N->getDebugLoc();
16541     EVT VT = N->getValueType(0);
16542     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16543     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16544                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16545                                            DAG.getConstant(X86::COND_B,MVT::i8),
16546                                            N->getOperand(2)),
16547                                DAG.getConstant(1, VT));
16548     return DCI.CombineTo(N, Res1, CarryOut);
16549   }
16550
16551   return SDValue();
16552 }
16553
16554 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16555 //      (add Y, (setne X, 0)) -> sbb -1, Y
16556 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16557 //      (sub (setne X, 0), Y) -> adc -1, Y
16558 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16559   DebugLoc DL = N->getDebugLoc();
16560
16561   // Look through ZExts.
16562   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16563   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16564     return SDValue();
16565
16566   SDValue SetCC = Ext.getOperand(0);
16567   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16568     return SDValue();
16569
16570   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16571   if (CC != X86::COND_E && CC != X86::COND_NE)
16572     return SDValue();
16573
16574   SDValue Cmp = SetCC.getOperand(1);
16575   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16576       !X86::isZeroNode(Cmp.getOperand(1)) ||
16577       !Cmp.getOperand(0).getValueType().isInteger())
16578     return SDValue();
16579
16580   SDValue CmpOp0 = Cmp.getOperand(0);
16581   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16582                                DAG.getConstant(1, CmpOp0.getValueType()));
16583
16584   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16585   if (CC == X86::COND_NE)
16586     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16587                        DL, OtherVal.getValueType(), OtherVal,
16588                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16589   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16590                      DL, OtherVal.getValueType(), OtherVal,
16591                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16592 }
16593
16594 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16595 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16596                                  const X86Subtarget *Subtarget) {
16597   EVT VT = N->getValueType(0);
16598   SDValue Op0 = N->getOperand(0);
16599   SDValue Op1 = N->getOperand(1);
16600
16601   // Try to synthesize horizontal adds from adds of shuffles.
16602   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16603        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16604       isHorizontalBinOp(Op0, Op1, true))
16605     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16606
16607   return OptimizeConditionalInDecrement(N, DAG);
16608 }
16609
16610 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16611                                  const X86Subtarget *Subtarget) {
16612   SDValue Op0 = N->getOperand(0);
16613   SDValue Op1 = N->getOperand(1);
16614
16615   // X86 can't encode an immediate LHS of a sub. See if we can push the
16616   // negation into a preceding instruction.
16617   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16618     // If the RHS of the sub is a XOR with one use and a constant, invert the
16619     // immediate. Then add one to the LHS of the sub so we can turn
16620     // X-Y -> X+~Y+1, saving one register.
16621     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16622         isa<ConstantSDNode>(Op1.getOperand(1))) {
16623       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16624       EVT VT = Op0.getValueType();
16625       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16626                                    Op1.getOperand(0),
16627                                    DAG.getConstant(~XorC, VT));
16628       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16629                          DAG.getConstant(C->getAPIntValue()+1, VT));
16630     }
16631   }
16632
16633   // Try to synthesize horizontal adds from adds of shuffles.
16634   EVT VT = N->getValueType(0);
16635   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16636        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16637       isHorizontalBinOp(Op0, Op1, true))
16638     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16639
16640   return OptimizeConditionalInDecrement(N, DAG);
16641 }
16642
16643 /// performVZEXTCombine - Performs build vector combines
16644 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16645                                         TargetLowering::DAGCombinerInfo &DCI,
16646                                         const X86Subtarget *Subtarget) {
16647   // (vzext (bitcast (vzext (x)) -> (vzext x)
16648   SDValue In = N->getOperand(0);
16649   while (In.getOpcode() == ISD::BITCAST)
16650     In = In.getOperand(0);
16651
16652   if (In.getOpcode() != X86ISD::VZEXT)
16653     return SDValue();
16654
16655   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16656 }
16657
16658 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16659                                              DAGCombinerInfo &DCI) const {
16660   SelectionDAG &DAG = DCI.DAG;
16661   switch (N->getOpcode()) {
16662   default: break;
16663   case ISD::EXTRACT_VECTOR_ELT:
16664     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16665   case ISD::VSELECT:
16666   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16667   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16668   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16669   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16670   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16671   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16672   case ISD::SHL:
16673   case ISD::SRA:
16674   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16675   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16676   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16677   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16678   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16679   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16680   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16681   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16682   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16683   case X86ISD::FXOR:
16684   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16685   case X86ISD::FMIN:
16686   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16687   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16688   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16689   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16690   case ISD::ANY_EXTEND:
16691   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16692   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16693   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16694   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16695   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16696   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16697   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
16698   case X86ISD::SHUFP:       // Handle all target specific shuffles
16699   case X86ISD::PALIGN:
16700   case X86ISD::UNPCKH:
16701   case X86ISD::UNPCKL:
16702   case X86ISD::MOVHLPS:
16703   case X86ISD::MOVLHPS:
16704   case X86ISD::PSHUFD:
16705   case X86ISD::PSHUFHW:
16706   case X86ISD::PSHUFLW:
16707   case X86ISD::MOVSS:
16708   case X86ISD::MOVSD:
16709   case X86ISD::VPERMILP:
16710   case X86ISD::VPERM2X128:
16711   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16712   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16713   }
16714
16715   return SDValue();
16716 }
16717
16718 /// isTypeDesirableForOp - Return true if the target has native support for
16719 /// the specified value type and it is 'desirable' to use the type for the
16720 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16721 /// instruction encodings are longer and some i16 instructions are slow.
16722 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16723   if (!isTypeLegal(VT))
16724     return false;
16725   if (VT != MVT::i16)
16726     return true;
16727
16728   switch (Opc) {
16729   default:
16730     return true;
16731   case ISD::LOAD:
16732   case ISD::SIGN_EXTEND:
16733   case ISD::ZERO_EXTEND:
16734   case ISD::ANY_EXTEND:
16735   case ISD::SHL:
16736   case ISD::SRL:
16737   case ISD::SUB:
16738   case ISD::ADD:
16739   case ISD::MUL:
16740   case ISD::AND:
16741   case ISD::OR:
16742   case ISD::XOR:
16743     return false;
16744   }
16745 }
16746
16747 /// IsDesirableToPromoteOp - This method query the target whether it is
16748 /// beneficial for dag combiner to promote the specified node. If true, it
16749 /// should return the desired promotion type by reference.
16750 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16751   EVT VT = Op.getValueType();
16752   if (VT != MVT::i16)
16753     return false;
16754
16755   bool Promote = false;
16756   bool Commute = false;
16757   switch (Op.getOpcode()) {
16758   default: break;
16759   case ISD::LOAD: {
16760     LoadSDNode *LD = cast<LoadSDNode>(Op);
16761     // If the non-extending load has a single use and it's not live out, then it
16762     // might be folded.
16763     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16764                                                      Op.hasOneUse()*/) {
16765       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16766              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16767         // The only case where we'd want to promote LOAD (rather then it being
16768         // promoted as an operand is when it's only use is liveout.
16769         if (UI->getOpcode() != ISD::CopyToReg)
16770           return false;
16771       }
16772     }
16773     Promote = true;
16774     break;
16775   }
16776   case ISD::SIGN_EXTEND:
16777   case ISD::ZERO_EXTEND:
16778   case ISD::ANY_EXTEND:
16779     Promote = true;
16780     break;
16781   case ISD::SHL:
16782   case ISD::SRL: {
16783     SDValue N0 = Op.getOperand(0);
16784     // Look out for (store (shl (load), x)).
16785     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16786       return false;
16787     Promote = true;
16788     break;
16789   }
16790   case ISD::ADD:
16791   case ISD::MUL:
16792   case ISD::AND:
16793   case ISD::OR:
16794   case ISD::XOR:
16795     Commute = true;
16796     // fallthrough
16797   case ISD::SUB: {
16798     SDValue N0 = Op.getOperand(0);
16799     SDValue N1 = Op.getOperand(1);
16800     if (!Commute && MayFoldLoad(N1))
16801       return false;
16802     // Avoid disabling potential load folding opportunities.
16803     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16804       return false;
16805     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16806       return false;
16807     Promote = true;
16808   }
16809   }
16810
16811   PVT = MVT::i32;
16812   return Promote;
16813 }
16814
16815 //===----------------------------------------------------------------------===//
16816 //                           X86 Inline Assembly Support
16817 //===----------------------------------------------------------------------===//
16818
16819 namespace {
16820   // Helper to match a string separated by whitespace.
16821   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16822     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16823
16824     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16825       StringRef piece(*args[i]);
16826       if (!s.startswith(piece)) // Check if the piece matches.
16827         return false;
16828
16829       s = s.substr(piece.size());
16830       StringRef::size_type pos = s.find_first_not_of(" \t");
16831       if (pos == 0) // We matched a prefix.
16832         return false;
16833
16834       s = s.substr(pos);
16835     }
16836
16837     return s.empty();
16838   }
16839   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16840 }
16841
16842 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16843   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16844
16845   std::string AsmStr = IA->getAsmString();
16846
16847   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16848   if (!Ty || Ty->getBitWidth() % 16 != 0)
16849     return false;
16850
16851   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16852   SmallVector<StringRef, 4> AsmPieces;
16853   SplitString(AsmStr, AsmPieces, ";\n");
16854
16855   switch (AsmPieces.size()) {
16856   default: return false;
16857   case 1:
16858     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16859     // we will turn this bswap into something that will be lowered to logical
16860     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16861     // lower so don't worry about this.
16862     // bswap $0
16863     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16864         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16865         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16866         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16867         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16868         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16869       // No need to check constraints, nothing other than the equivalent of
16870       // "=r,0" would be valid here.
16871       return IntrinsicLowering::LowerToByteSwap(CI);
16872     }
16873
16874     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16875     if (CI->getType()->isIntegerTy(16) &&
16876         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16877         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16878          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16879       AsmPieces.clear();
16880       const std::string &ConstraintsStr = IA->getConstraintString();
16881       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16882       std::sort(AsmPieces.begin(), AsmPieces.end());
16883       if (AsmPieces.size() == 4 &&
16884           AsmPieces[0] == "~{cc}" &&
16885           AsmPieces[1] == "~{dirflag}" &&
16886           AsmPieces[2] == "~{flags}" &&
16887           AsmPieces[3] == "~{fpsr}")
16888       return IntrinsicLowering::LowerToByteSwap(CI);
16889     }
16890     break;
16891   case 3:
16892     if (CI->getType()->isIntegerTy(32) &&
16893         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16894         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16895         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16896         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16897       AsmPieces.clear();
16898       const std::string &ConstraintsStr = IA->getConstraintString();
16899       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16900       std::sort(AsmPieces.begin(), AsmPieces.end());
16901       if (AsmPieces.size() == 4 &&
16902           AsmPieces[0] == "~{cc}" &&
16903           AsmPieces[1] == "~{dirflag}" &&
16904           AsmPieces[2] == "~{flags}" &&
16905           AsmPieces[3] == "~{fpsr}")
16906         return IntrinsicLowering::LowerToByteSwap(CI);
16907     }
16908
16909     if (CI->getType()->isIntegerTy(64)) {
16910       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16911       if (Constraints.size() >= 2 &&
16912           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16913           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16914         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16915         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16916             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16917             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16918           return IntrinsicLowering::LowerToByteSwap(CI);
16919       }
16920     }
16921     break;
16922   }
16923   return false;
16924 }
16925
16926
16927
16928 /// getConstraintType - Given a constraint letter, return the type of
16929 /// constraint it is for this target.
16930 X86TargetLowering::ConstraintType
16931 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16932   if (Constraint.size() == 1) {
16933     switch (Constraint[0]) {
16934     case 'R':
16935     case 'q':
16936     case 'Q':
16937     case 'f':
16938     case 't':
16939     case 'u':
16940     case 'y':
16941     case 'x':
16942     case 'Y':
16943     case 'l':
16944       return C_RegisterClass;
16945     case 'a':
16946     case 'b':
16947     case 'c':
16948     case 'd':
16949     case 'S':
16950     case 'D':
16951     case 'A':
16952       return C_Register;
16953     case 'I':
16954     case 'J':
16955     case 'K':
16956     case 'L':
16957     case 'M':
16958     case 'N':
16959     case 'G':
16960     case 'C':
16961     case 'e':
16962     case 'Z':
16963       return C_Other;
16964     default:
16965       break;
16966     }
16967   }
16968   return TargetLowering::getConstraintType(Constraint);
16969 }
16970
16971 /// Examine constraint type and operand type and determine a weight value.
16972 /// This object must already have been set up with the operand type
16973 /// and the current alternative constraint selected.
16974 TargetLowering::ConstraintWeight
16975   X86TargetLowering::getSingleConstraintMatchWeight(
16976     AsmOperandInfo &info, const char *constraint) const {
16977   ConstraintWeight weight = CW_Invalid;
16978   Value *CallOperandVal = info.CallOperandVal;
16979     // If we don't have a value, we can't do a match,
16980     // but allow it at the lowest weight.
16981   if (CallOperandVal == NULL)
16982     return CW_Default;
16983   Type *type = CallOperandVal->getType();
16984   // Look at the constraint type.
16985   switch (*constraint) {
16986   default:
16987     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16988   case 'R':
16989   case 'q':
16990   case 'Q':
16991   case 'a':
16992   case 'b':
16993   case 'c':
16994   case 'd':
16995   case 'S':
16996   case 'D':
16997   case 'A':
16998     if (CallOperandVal->getType()->isIntegerTy())
16999       weight = CW_SpecificReg;
17000     break;
17001   case 'f':
17002   case 't':
17003   case 'u':
17004       if (type->isFloatingPointTy())
17005         weight = CW_SpecificReg;
17006       break;
17007   case 'y':
17008       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17009         weight = CW_SpecificReg;
17010       break;
17011   case 'x':
17012   case 'Y':
17013     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17014         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
17015       weight = CW_Register;
17016     break;
17017   case 'I':
17018     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17019       if (C->getZExtValue() <= 31)
17020         weight = CW_Constant;
17021     }
17022     break;
17023   case 'J':
17024     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17025       if (C->getZExtValue() <= 63)
17026         weight = CW_Constant;
17027     }
17028     break;
17029   case 'K':
17030     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17031       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17032         weight = CW_Constant;
17033     }
17034     break;
17035   case 'L':
17036     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17037       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17038         weight = CW_Constant;
17039     }
17040     break;
17041   case 'M':
17042     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17043       if (C->getZExtValue() <= 3)
17044         weight = CW_Constant;
17045     }
17046     break;
17047   case 'N':
17048     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17049       if (C->getZExtValue() <= 0xff)
17050         weight = CW_Constant;
17051     }
17052     break;
17053   case 'G':
17054   case 'C':
17055     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17056       weight = CW_Constant;
17057     }
17058     break;
17059   case 'e':
17060     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17061       if ((C->getSExtValue() >= -0x80000000LL) &&
17062           (C->getSExtValue() <= 0x7fffffffLL))
17063         weight = CW_Constant;
17064     }
17065     break;
17066   case 'Z':
17067     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17068       if (C->getZExtValue() <= 0xffffffff)
17069         weight = CW_Constant;
17070     }
17071     break;
17072   }
17073   return weight;
17074 }
17075
17076 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17077 /// with another that has more specific requirements based on the type of the
17078 /// corresponding operand.
17079 const char *X86TargetLowering::
17080 LowerXConstraint(EVT ConstraintVT) const {
17081   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17082   // 'f' like normal targets.
17083   if (ConstraintVT.isFloatingPoint()) {
17084     if (Subtarget->hasSSE2())
17085       return "Y";
17086     if (Subtarget->hasSSE1())
17087       return "x";
17088   }
17089
17090   return TargetLowering::LowerXConstraint(ConstraintVT);
17091 }
17092
17093 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17094 /// vector.  If it is invalid, don't add anything to Ops.
17095 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17096                                                      std::string &Constraint,
17097                                                      std::vector<SDValue>&Ops,
17098                                                      SelectionDAG &DAG) const {
17099   SDValue Result(0, 0);
17100
17101   // Only support length 1 constraints for now.
17102   if (Constraint.length() > 1) return;
17103
17104   char ConstraintLetter = Constraint[0];
17105   switch (ConstraintLetter) {
17106   default: break;
17107   case 'I':
17108     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17109       if (C->getZExtValue() <= 31) {
17110         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17111         break;
17112       }
17113     }
17114     return;
17115   case 'J':
17116     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17117       if (C->getZExtValue() <= 63) {
17118         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17119         break;
17120       }
17121     }
17122     return;
17123   case 'K':
17124     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17125       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17126         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17127         break;
17128       }
17129     }
17130     return;
17131   case 'N':
17132     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17133       if (C->getZExtValue() <= 255) {
17134         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17135         break;
17136       }
17137     }
17138     return;
17139   case 'e': {
17140     // 32-bit signed value
17141     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17142       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17143                                            C->getSExtValue())) {
17144         // Widen to 64 bits here to get it sign extended.
17145         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17146         break;
17147       }
17148     // FIXME gcc accepts some relocatable values here too, but only in certain
17149     // memory models; it's complicated.
17150     }
17151     return;
17152   }
17153   case 'Z': {
17154     // 32-bit unsigned value
17155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17156       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17157                                            C->getZExtValue())) {
17158         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17159         break;
17160       }
17161     }
17162     // FIXME gcc accepts some relocatable values here too, but only in certain
17163     // memory models; it's complicated.
17164     return;
17165   }
17166   case 'i': {
17167     // Literal immediates are always ok.
17168     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17169       // Widen to 64 bits here to get it sign extended.
17170       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17171       break;
17172     }
17173
17174     // In any sort of PIC mode addresses need to be computed at runtime by
17175     // adding in a register or some sort of table lookup.  These can't
17176     // be used as immediates.
17177     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17178       return;
17179
17180     // If we are in non-pic codegen mode, we allow the address of a global (with
17181     // an optional displacement) to be used with 'i'.
17182     GlobalAddressSDNode *GA = 0;
17183     int64_t Offset = 0;
17184
17185     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17186     while (1) {
17187       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17188         Offset += GA->getOffset();
17189         break;
17190       } else if (Op.getOpcode() == ISD::ADD) {
17191         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17192           Offset += C->getZExtValue();
17193           Op = Op.getOperand(0);
17194           continue;
17195         }
17196       } else if (Op.getOpcode() == ISD::SUB) {
17197         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17198           Offset += -C->getZExtValue();
17199           Op = Op.getOperand(0);
17200           continue;
17201         }
17202       }
17203
17204       // Otherwise, this isn't something we can handle, reject it.
17205       return;
17206     }
17207
17208     const GlobalValue *GV = GA->getGlobal();
17209     // If we require an extra load to get this address, as in PIC mode, we
17210     // can't accept it.
17211     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17212                                                         getTargetMachine())))
17213       return;
17214
17215     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17216                                         GA->getValueType(0), Offset);
17217     break;
17218   }
17219   }
17220
17221   if (Result.getNode()) {
17222     Ops.push_back(Result);
17223     return;
17224   }
17225   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17226 }
17227
17228 std::pair<unsigned, const TargetRegisterClass*>
17229 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17230                                                 EVT VT) const {
17231   // First, see if this is a constraint that directly corresponds to an LLVM
17232   // register class.
17233   if (Constraint.size() == 1) {
17234     // GCC Constraint Letters
17235     switch (Constraint[0]) {
17236     default: break;
17237       // TODO: Slight differences here in allocation order and leaving
17238       // RIP in the class. Do they matter any more here than they do
17239       // in the normal allocation?
17240     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17241       if (Subtarget->is64Bit()) {
17242         if (VT == MVT::i32 || VT == MVT::f32)
17243           return std::make_pair(0U, &X86::GR32RegClass);
17244         if (VT == MVT::i16)
17245           return std::make_pair(0U, &X86::GR16RegClass);
17246         if (VT == MVT::i8 || VT == MVT::i1)
17247           return std::make_pair(0U, &X86::GR8RegClass);
17248         if (VT == MVT::i64 || VT == MVT::f64)
17249           return std::make_pair(0U, &X86::GR64RegClass);
17250         break;
17251       }
17252       // 32-bit fallthrough
17253     case 'Q':   // Q_REGS
17254       if (VT == MVT::i32 || VT == MVT::f32)
17255         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17256       if (VT == MVT::i16)
17257         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17258       if (VT == MVT::i8 || VT == MVT::i1)
17259         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17260       if (VT == MVT::i64)
17261         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17262       break;
17263     case 'r':   // GENERAL_REGS
17264     case 'l':   // INDEX_REGS
17265       if (VT == MVT::i8 || VT == MVT::i1)
17266         return std::make_pair(0U, &X86::GR8RegClass);
17267       if (VT == MVT::i16)
17268         return std::make_pair(0U, &X86::GR16RegClass);
17269       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17270         return std::make_pair(0U, &X86::GR32RegClass);
17271       return std::make_pair(0U, &X86::GR64RegClass);
17272     case 'R':   // LEGACY_REGS
17273       if (VT == MVT::i8 || VT == MVT::i1)
17274         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17275       if (VT == MVT::i16)
17276         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17277       if (VT == MVT::i32 || !Subtarget->is64Bit())
17278         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17279       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17280     case 'f':  // FP Stack registers.
17281       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17282       // value to the correct fpstack register class.
17283       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17284         return std::make_pair(0U, &X86::RFP32RegClass);
17285       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17286         return std::make_pair(0U, &X86::RFP64RegClass);
17287       return std::make_pair(0U, &X86::RFP80RegClass);
17288     case 'y':   // MMX_REGS if MMX allowed.
17289       if (!Subtarget->hasMMX()) break;
17290       return std::make_pair(0U, &X86::VR64RegClass);
17291     case 'Y':   // SSE_REGS if SSE2 allowed
17292       if (!Subtarget->hasSSE2()) break;
17293       // FALL THROUGH.
17294     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17295       if (!Subtarget->hasSSE1()) break;
17296
17297       switch (VT.getSimpleVT().SimpleTy) {
17298       default: break;
17299       // Scalar SSE types.
17300       case MVT::f32:
17301       case MVT::i32:
17302         return std::make_pair(0U, &X86::FR32RegClass);
17303       case MVT::f64:
17304       case MVT::i64:
17305         return std::make_pair(0U, &X86::FR64RegClass);
17306       // Vector types.
17307       case MVT::v16i8:
17308       case MVT::v8i16:
17309       case MVT::v4i32:
17310       case MVT::v2i64:
17311       case MVT::v4f32:
17312       case MVT::v2f64:
17313         return std::make_pair(0U, &X86::VR128RegClass);
17314       // AVX types.
17315       case MVT::v32i8:
17316       case MVT::v16i16:
17317       case MVT::v8i32:
17318       case MVT::v4i64:
17319       case MVT::v8f32:
17320       case MVT::v4f64:
17321         return std::make_pair(0U, &X86::VR256RegClass);
17322       }
17323       break;
17324     }
17325   }
17326
17327   // Use the default implementation in TargetLowering to convert the register
17328   // constraint into a member of a register class.
17329   std::pair<unsigned, const TargetRegisterClass*> Res;
17330   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17331
17332   // Not found as a standard register?
17333   if (Res.second == 0) {
17334     // Map st(0) -> st(7) -> ST0
17335     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17336         tolower(Constraint[1]) == 's' &&
17337         tolower(Constraint[2]) == 't' &&
17338         Constraint[3] == '(' &&
17339         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17340         Constraint[5] == ')' &&
17341         Constraint[6] == '}') {
17342
17343       Res.first = X86::ST0+Constraint[4]-'0';
17344       Res.second = &X86::RFP80RegClass;
17345       return Res;
17346     }
17347
17348     // GCC allows "st(0)" to be called just plain "st".
17349     if (StringRef("{st}").equals_lower(Constraint)) {
17350       Res.first = X86::ST0;
17351       Res.second = &X86::RFP80RegClass;
17352       return Res;
17353     }
17354
17355     // flags -> EFLAGS
17356     if (StringRef("{flags}").equals_lower(Constraint)) {
17357       Res.first = X86::EFLAGS;
17358       Res.second = &X86::CCRRegClass;
17359       return Res;
17360     }
17361
17362     // 'A' means EAX + EDX.
17363     if (Constraint == "A") {
17364       Res.first = X86::EAX;
17365       Res.second = &X86::GR32_ADRegClass;
17366       return Res;
17367     }
17368     return Res;
17369   }
17370
17371   // Otherwise, check to see if this is a register class of the wrong value
17372   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17373   // turn into {ax},{dx}.
17374   if (Res.second->hasType(VT))
17375     return Res;   // Correct type already, nothing to do.
17376
17377   // All of the single-register GCC register classes map their values onto
17378   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17379   // really want an 8-bit or 32-bit register, map to the appropriate register
17380   // class and return the appropriate register.
17381   if (Res.second == &X86::GR16RegClass) {
17382     if (VT == MVT::i8) {
17383       unsigned DestReg = 0;
17384       switch (Res.first) {
17385       default: break;
17386       case X86::AX: DestReg = X86::AL; break;
17387       case X86::DX: DestReg = X86::DL; break;
17388       case X86::CX: DestReg = X86::CL; break;
17389       case X86::BX: DestReg = X86::BL; break;
17390       }
17391       if (DestReg) {
17392         Res.first = DestReg;
17393         Res.second = &X86::GR8RegClass;
17394       }
17395     } else if (VT == MVT::i32) {
17396       unsigned DestReg = 0;
17397       switch (Res.first) {
17398       default: break;
17399       case X86::AX: DestReg = X86::EAX; break;
17400       case X86::DX: DestReg = X86::EDX; break;
17401       case X86::CX: DestReg = X86::ECX; break;
17402       case X86::BX: DestReg = X86::EBX; break;
17403       case X86::SI: DestReg = X86::ESI; break;
17404       case X86::DI: DestReg = X86::EDI; break;
17405       case X86::BP: DestReg = X86::EBP; break;
17406       case X86::SP: DestReg = X86::ESP; break;
17407       }
17408       if (DestReg) {
17409         Res.first = DestReg;
17410         Res.second = &X86::GR32RegClass;
17411       }
17412     } else if (VT == MVT::i64) {
17413       unsigned DestReg = 0;
17414       switch (Res.first) {
17415       default: break;
17416       case X86::AX: DestReg = X86::RAX; break;
17417       case X86::DX: DestReg = X86::RDX; break;
17418       case X86::CX: DestReg = X86::RCX; break;
17419       case X86::BX: DestReg = X86::RBX; break;
17420       case X86::SI: DestReg = X86::RSI; break;
17421       case X86::DI: DestReg = X86::RDI; break;
17422       case X86::BP: DestReg = X86::RBP; break;
17423       case X86::SP: DestReg = X86::RSP; break;
17424       }
17425       if (DestReg) {
17426         Res.first = DestReg;
17427         Res.second = &X86::GR64RegClass;
17428       }
17429     }
17430   } else if (Res.second == &X86::FR32RegClass ||
17431              Res.second == &X86::FR64RegClass ||
17432              Res.second == &X86::VR128RegClass) {
17433     // Handle references to XMM physical registers that got mapped into the
17434     // wrong class.  This can happen with constraints like {xmm0} where the
17435     // target independent register mapper will just pick the first match it can
17436     // find, ignoring the required type.
17437
17438     if (VT == MVT::f32 || VT == MVT::i32)
17439       Res.second = &X86::FR32RegClass;
17440     else if (VT == MVT::f64 || VT == MVT::i64)
17441       Res.second = &X86::FR64RegClass;
17442     else if (X86::VR128RegClass.hasType(VT))
17443       Res.second = &X86::VR128RegClass;
17444     else if (X86::VR256RegClass.hasType(VT))
17445       Res.second = &X86::VR256RegClass;
17446   }
17447
17448   return Res;
17449 }