Add __builtin_setjmp/_longjmp supprt in X86 backend
[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, not
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
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
729            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
730     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
745     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
747     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
784     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
785     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
789     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
790              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
791       setTruncStoreAction((MVT::SimpleValueType)VT,
792                           (MVT::SimpleValueType)InnerVT, Expand);
793     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
794     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
796   }
797
798   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
799   // with -msoft-float, disable use of MMX as well.
800   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
801     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
802     // No operations on x86mmx supported, everything uses intrinsics.
803   }
804
805   // MMX-sized vectors (other than x86mmx) are expected to be expanded
806   // into smaller operations.
807   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
808   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
809   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
811   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
812   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
813   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
814   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
815   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
816   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
817   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
818   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
819   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
820   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
821   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
822   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
823   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
827   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
828   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
829   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
830   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
832   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
836
837   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
838     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
839
840     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
846     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
847     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
848     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
849     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
850     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
852   }
853
854   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
855     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
856
857     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
858     // registers cannot be used even for integer operations.
859     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
860     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
861     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
862     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
863
864     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
865     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
866     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
867     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
868     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
869     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
870     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
871     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
872     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
874     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
875     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
879     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
880     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
881
882     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
883     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
886
887     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
892
893     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
894     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895       MVT VT = (MVT::SimpleValueType)i;
896       // Do not attempt to custom lower non-power-of-2 vectors
897       if (!isPowerOf2_32(VT.getVectorNumElements()))
898         continue;
899       // Do not attempt to custom lower non-128-bit vectors
900       if (!VT.is128BitVector())
901         continue;
902       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
903       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
904       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
905     }
906
907     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
909     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
912     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
913
914     if (Subtarget->is64Bit()) {
915       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
916       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
917     }
918
919     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
920     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
921       MVT VT = (MVT::SimpleValueType)i;
922
923       // Do not attempt to promote non-128-bit vectors
924       if (!VT.is128BitVector())
925         continue;
926
927       setOperationAction(ISD::AND,    VT, Promote);
928       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
929       setOperationAction(ISD::OR,     VT, Promote);
930       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
931       setOperationAction(ISD::XOR,    VT, Promote);
932       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
933       setOperationAction(ISD::LOAD,   VT, Promote);
934       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
935       setOperationAction(ISD::SELECT, VT, Promote);
936       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
937     }
938
939     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
940
941     // Custom lower v2i64 and v2f64 selects.
942     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
943     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
944     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
945     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
946
947     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
948     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
949
950     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
951     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
952
953     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
954   }
955
956   if (Subtarget->hasSSE41()) {
957     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
958     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
959     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
960     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
961     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
962     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
963     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
964     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
965     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
966     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
967
968     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
969     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
970
971     // FIXME: Do we need to handle scalar-to-vector here?
972     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
973
974     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
975     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
976     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
977     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
978     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
979
980     // i8 and i16 vectors are custom , because the source register and source
981     // source memory operand types are not the same width.  f32 vectors are
982     // custom since the immediate controlling the insert encodes additional
983     // information.
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
988
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
993
994     // FIXME: these should be Legal but thats only for the case where
995     // the index is constant.  For now custom expand to deal with that.
996     if (Subtarget->is64Bit()) {
997       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
998       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999     }
1000   }
1001
1002   if (Subtarget->hasSSE2()) {
1003     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1004     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1005
1006     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1007     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1008
1009     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1010     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1011
1012     if (Subtarget->hasAVX2()) {
1013       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1014       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1015
1016       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1017       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1018
1019       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1020     } else {
1021       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1022       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1023
1024       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1025       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1026
1027       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1028     }
1029   }
1030
1031   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1059     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1060
1061     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1062     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1063     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1064
1065     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1066
1067     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1068     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1069
1070     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1071     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1072
1073     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1074     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1075
1076     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1077     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1078     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1079     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1080
1081     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1082     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1083     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1084
1085     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1086     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1087     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1088     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1089
1090     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1091       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1092       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1093       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1094       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1095       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1096       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1097     }
1098
1099     if (Subtarget->hasAVX2()) {
1100       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1101       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1102       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1103       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1104
1105       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1106       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1107       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1108       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1109
1110       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1112       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1113       // Don't lower v32i8 because there is no 128-bit byte mul
1114
1115       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1116
1117       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1118       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1119
1120       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1121       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1122
1123       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1124     } else {
1125       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1126       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1127       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1128       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1129
1130       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1131       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1132       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1133       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1134
1135       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1136       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1137       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1138       // Don't lower v32i8 because there is no 128-bit byte mul
1139
1140       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1141       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1142
1143       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1144       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1145
1146       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1147     }
1148
1149     // Custom lower several nodes for 256-bit types.
1150     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1151              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1152       MVT VT = (MVT::SimpleValueType)i;
1153
1154       // Extract subvector is special because the value type
1155       // (result) is 128-bit but the source is 256-bit wide.
1156       if (VT.is128BitVector())
1157         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1158
1159       // Do not attempt to custom lower other non-256-bit vectors
1160       if (!VT.is256BitVector())
1161         continue;
1162
1163       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1164       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1165       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1166       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1167       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1168       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1169       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1170     }
1171
1172     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1173     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1174       MVT VT = (MVT::SimpleValueType)i;
1175
1176       // Do not attempt to promote non-256-bit vectors
1177       if (!VT.is256BitVector())
1178         continue;
1179
1180       setOperationAction(ISD::AND,    VT, Promote);
1181       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1182       setOperationAction(ISD::OR,     VT, Promote);
1183       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1184       setOperationAction(ISD::XOR,    VT, Promote);
1185       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1186       setOperationAction(ISD::LOAD,   VT, Promote);
1187       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1188       setOperationAction(ISD::SELECT, VT, Promote);
1189       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1190     }
1191   }
1192
1193   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1194   // of this type with custom code.
1195   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1196            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1197     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1198                        Custom);
1199   }
1200
1201   // We want to custom lower some of our intrinsics.
1202   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1203   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1204
1205
1206   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1207   // handle type legalization for these operations here.
1208   //
1209   // FIXME: We really should do custom legalization for addition and
1210   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1211   // than generic legalization for 64-bit multiplication-with-overflow, though.
1212   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1213     // Add/Sub/Mul with overflow operations are custom lowered.
1214     MVT VT = IntVTs[i];
1215     setOperationAction(ISD::SADDO, VT, Custom);
1216     setOperationAction(ISD::UADDO, VT, Custom);
1217     setOperationAction(ISD::SSUBO, VT, Custom);
1218     setOperationAction(ISD::USUBO, VT, Custom);
1219     setOperationAction(ISD::SMULO, VT, Custom);
1220     setOperationAction(ISD::UMULO, VT, Custom);
1221   }
1222
1223   // There are no 8-bit 3-address imul/mul instructions
1224   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1225   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1226
1227   if (!Subtarget->is64Bit()) {
1228     // These libcalls are not available in 32-bit.
1229     setLibcallName(RTLIB::SHL_I128, 0);
1230     setLibcallName(RTLIB::SRL_I128, 0);
1231     setLibcallName(RTLIB::SRA_I128, 0);
1232   }
1233
1234   // We have target-specific dag combine patterns for the following nodes:
1235   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1236   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1237   setTargetDAGCombine(ISD::VSELECT);
1238   setTargetDAGCombine(ISD::SELECT);
1239   setTargetDAGCombine(ISD::SHL);
1240   setTargetDAGCombine(ISD::SRA);
1241   setTargetDAGCombine(ISD::SRL);
1242   setTargetDAGCombine(ISD::OR);
1243   setTargetDAGCombine(ISD::AND);
1244   setTargetDAGCombine(ISD::ADD);
1245   setTargetDAGCombine(ISD::FADD);
1246   setTargetDAGCombine(ISD::FSUB);
1247   setTargetDAGCombine(ISD::FMA);
1248   setTargetDAGCombine(ISD::SUB);
1249   setTargetDAGCombine(ISD::LOAD);
1250   setTargetDAGCombine(ISD::STORE);
1251   setTargetDAGCombine(ISD::ZERO_EXTEND);
1252   setTargetDAGCombine(ISD::ANY_EXTEND);
1253   setTargetDAGCombine(ISD::SIGN_EXTEND);
1254   setTargetDAGCombine(ISD::TRUNCATE);
1255   setTargetDAGCombine(ISD::UINT_TO_FP);
1256   setTargetDAGCombine(ISD::SINT_TO_FP);
1257   setTargetDAGCombine(ISD::SETCC);
1258   setTargetDAGCombine(ISD::FP_TO_SINT);
1259   if (Subtarget->is64Bit())
1260     setTargetDAGCombine(ISD::MUL);
1261   setTargetDAGCombine(ISD::XOR);
1262
1263   computeRegisterProperties();
1264
1265   // On Darwin, -Os means optimize for size without hurting performance,
1266   // do not reduce the limit.
1267   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1268   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1269   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1270   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1271   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1272   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1273   setPrefLoopAlignment(4); // 2^4 bytes.
1274   benefitFromCodePlacementOpt = true;
1275
1276   // Predictable cmov don't hurt on atom because it's in-order.
1277   predictableSelectIsExpensive = !Subtarget->isAtom();
1278
1279   setPrefFunctionAlignment(4); // 2^4 bytes.
1280 }
1281
1282
1283 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1284   if (!VT.isVector()) return MVT::i8;
1285   return VT.changeVectorElementTypeToInteger();
1286 }
1287
1288
1289 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1290 /// the desired ByVal argument alignment.
1291 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1292   if (MaxAlign == 16)
1293     return;
1294   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1295     if (VTy->getBitWidth() == 128)
1296       MaxAlign = 16;
1297   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1298     unsigned EltAlign = 0;
1299     getMaxByValAlign(ATy->getElementType(), EltAlign);
1300     if (EltAlign > MaxAlign)
1301       MaxAlign = EltAlign;
1302   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1303     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1304       unsigned EltAlign = 0;
1305       getMaxByValAlign(STy->getElementType(i), EltAlign);
1306       if (EltAlign > MaxAlign)
1307         MaxAlign = EltAlign;
1308       if (MaxAlign == 16)
1309         break;
1310     }
1311   }
1312 }
1313
1314 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1315 /// function arguments in the caller parameter area. For X86, aggregates
1316 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1317 /// are at 4-byte boundaries.
1318 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1319   if (Subtarget->is64Bit()) {
1320     // Max of 8 and alignment of type.
1321     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1322     if (TyAlign > 8)
1323       return TyAlign;
1324     return 8;
1325   }
1326
1327   unsigned Align = 4;
1328   if (Subtarget->hasSSE1())
1329     getMaxByValAlign(Ty, Align);
1330   return Align;
1331 }
1332
1333 /// getOptimalMemOpType - Returns the target specific optimal type for load
1334 /// and store operations as a result of memset, memcpy, and memmove
1335 /// lowering. If DstAlign is zero that means it's safe to destination
1336 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1337 /// means there isn't a need to check it against alignment requirement,
1338 /// probably because the source does not need to be loaded. If
1339 /// 'IsZeroVal' is true, that means it's safe to return a
1340 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1341 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1342 /// constant so it does not need to be loaded.
1343 /// It returns EVT::Other if the type should be determined using generic
1344 /// target-independent logic.
1345 EVT
1346 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1347                                        unsigned DstAlign, unsigned SrcAlign,
1348                                        bool IsZeroVal,
1349                                        bool MemcpyStrSrc,
1350                                        MachineFunction &MF) const {
1351   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1352   // linux.  This is because the stack realignment code can't handle certain
1353   // cases like PR2962.  This should be removed when PR2962 is fixed.
1354   const Function *F = MF.getFunction();
1355   if (IsZeroVal &&
1356       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1357     if (Size >= 16 &&
1358         (Subtarget->isUnalignedMemAccessFast() ||
1359          ((DstAlign == 0 || DstAlign >= 16) &&
1360           (SrcAlign == 0 || SrcAlign >= 16))) &&
1361         Subtarget->getStackAlignment() >= 16) {
1362       if (Subtarget->getStackAlignment() >= 32) {
1363         if (Subtarget->hasAVX2())
1364           return MVT::v8i32;
1365         if (Subtarget->hasAVX())
1366           return MVT::v8f32;
1367       }
1368       if (Subtarget->hasSSE2())
1369         return MVT::v4i32;
1370       if (Subtarget->hasSSE1())
1371         return MVT::v4f32;
1372     } else if (!MemcpyStrSrc && Size >= 8 &&
1373                !Subtarget->is64Bit() &&
1374                Subtarget->getStackAlignment() >= 8 &&
1375                Subtarget->hasSSE2()) {
1376       // Do not use f64 to lower memcpy if source is string constant. It's
1377       // better to use i32 to avoid the loads.
1378       return MVT::f64;
1379     }
1380   }
1381   if (Subtarget->is64Bit() && Size >= 8)
1382     return MVT::i64;
1383   return MVT::i32;
1384 }
1385
1386 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1387 /// current function.  The returned value is a member of the
1388 /// MachineJumpTableInfo::JTEntryKind enum.
1389 unsigned X86TargetLowering::getJumpTableEncoding() const {
1390   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1391   // symbol.
1392   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1393       Subtarget->isPICStyleGOT())
1394     return MachineJumpTableInfo::EK_Custom32;
1395
1396   // Otherwise, use the normal jump table encoding heuristics.
1397   return TargetLowering::getJumpTableEncoding();
1398 }
1399
1400 const MCExpr *
1401 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1402                                              const MachineBasicBlock *MBB,
1403                                              unsigned uid,MCContext &Ctx) const{
1404   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1405          Subtarget->isPICStyleGOT());
1406   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1407   // entries.
1408   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1409                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1410 }
1411
1412 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1413 /// jumptable.
1414 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1415                                                     SelectionDAG &DAG) const {
1416   if (!Subtarget->is64Bit())
1417     // This doesn't have DebugLoc associated with it, but is not really the
1418     // same as a Register.
1419     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1420   return Table;
1421 }
1422
1423 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1424 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1425 /// MCExpr.
1426 const MCExpr *X86TargetLowering::
1427 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1428                              MCContext &Ctx) const {
1429   // X86-64 uses RIP relative addressing based on the jump table label.
1430   if (Subtarget->isPICStyleRIPRel())
1431     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1432
1433   // Otherwise, the reference is relative to the PIC base.
1434   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1435 }
1436
1437 // FIXME: Why this routine is here? Move to RegInfo!
1438 std::pair<const TargetRegisterClass*, uint8_t>
1439 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1440   const TargetRegisterClass *RRC = 0;
1441   uint8_t Cost = 1;
1442   switch (VT.getSimpleVT().SimpleTy) {
1443   default:
1444     return TargetLowering::findRepresentativeClass(VT);
1445   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1446     RRC = Subtarget->is64Bit() ?
1447       (const TargetRegisterClass*)&X86::GR64RegClass :
1448       (const TargetRegisterClass*)&X86::GR32RegClass;
1449     break;
1450   case MVT::x86mmx:
1451     RRC = &X86::VR64RegClass;
1452     break;
1453   case MVT::f32: case MVT::f64:
1454   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1455   case MVT::v4f32: case MVT::v2f64:
1456   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1457   case MVT::v4f64:
1458     RRC = &X86::VR128RegClass;
1459     break;
1460   }
1461   return std::make_pair(RRC, Cost);
1462 }
1463
1464 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1465                                                unsigned &Offset) const {
1466   if (!Subtarget->isTargetLinux())
1467     return false;
1468
1469   if (Subtarget->is64Bit()) {
1470     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1471     Offset = 0x28;
1472     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1473       AddressSpace = 256;
1474     else
1475       AddressSpace = 257;
1476   } else {
1477     // %gs:0x14 on i386
1478     Offset = 0x14;
1479     AddressSpace = 256;
1480   }
1481   return true;
1482 }
1483
1484
1485 //===----------------------------------------------------------------------===//
1486 //               Return Value Calling Convention Implementation
1487 //===----------------------------------------------------------------------===//
1488
1489 #include "X86GenCallingConv.inc"
1490
1491 bool
1492 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1493                                   MachineFunction &MF, bool isVarArg,
1494                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1495                         LLVMContext &Context) const {
1496   SmallVector<CCValAssign, 16> RVLocs;
1497   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1498                  RVLocs, Context);
1499   return CCInfo.CheckReturn(Outs, RetCC_X86);
1500 }
1501
1502 SDValue
1503 X86TargetLowering::LowerReturn(SDValue Chain,
1504                                CallingConv::ID CallConv, bool isVarArg,
1505                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1506                                const SmallVectorImpl<SDValue> &OutVals,
1507                                DebugLoc dl, SelectionDAG &DAG) const {
1508   MachineFunction &MF = DAG.getMachineFunction();
1509   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1510
1511   SmallVector<CCValAssign, 16> RVLocs;
1512   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1513                  RVLocs, *DAG.getContext());
1514   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1515
1516   // Add the regs to the liveout set for the function.
1517   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1518   for (unsigned i = 0; i != RVLocs.size(); ++i)
1519     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1520       MRI.addLiveOut(RVLocs[i].getLocReg());
1521
1522   SDValue Flag;
1523
1524   SmallVector<SDValue, 6> RetOps;
1525   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1526   // Operand #1 = Bytes To Pop
1527   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1528                    MVT::i16));
1529
1530   // Copy the result values into the output registers.
1531   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1532     CCValAssign &VA = RVLocs[i];
1533     assert(VA.isRegLoc() && "Can only return in registers!");
1534     SDValue ValToCopy = OutVals[i];
1535     EVT ValVT = ValToCopy.getValueType();
1536
1537     // Promote values to the appropriate types
1538     if (VA.getLocInfo() == CCValAssign::SExt)
1539       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1540     else if (VA.getLocInfo() == CCValAssign::ZExt)
1541       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1542     else if (VA.getLocInfo() == CCValAssign::AExt)
1543       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1544     else if (VA.getLocInfo() == CCValAssign::BCvt)
1545       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1546
1547     // If this is x86-64, and we disabled SSE, we can't return FP values,
1548     // or SSE or MMX vectors.
1549     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1550          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1551           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1552       report_fatal_error("SSE register return with SSE disabled");
1553     }
1554     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1555     // llvm-gcc has never done it right and no one has noticed, so this
1556     // should be OK for now.
1557     if (ValVT == MVT::f64 &&
1558         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1559       report_fatal_error("SSE2 register return with SSE2 disabled");
1560
1561     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1562     // the RET instruction and handled by the FP Stackifier.
1563     if (VA.getLocReg() == X86::ST0 ||
1564         VA.getLocReg() == X86::ST1) {
1565       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1566       // change the value to the FP stack register class.
1567       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1568         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1569       RetOps.push_back(ValToCopy);
1570       // Don't emit a copytoreg.
1571       continue;
1572     }
1573
1574     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1575     // which is returned in RAX / RDX.
1576     if (Subtarget->is64Bit()) {
1577       if (ValVT == MVT::x86mmx) {
1578         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1579           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1580           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1581                                   ValToCopy);
1582           // If we don't have SSE2 available, convert to v4f32 so the generated
1583           // register is legal.
1584           if (!Subtarget->hasSSE2())
1585             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1586         }
1587       }
1588     }
1589
1590     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1591     Flag = Chain.getValue(1);
1592   }
1593
1594   // The x86-64 ABI for returning structs by value requires that we copy
1595   // the sret argument into %rax for the return. We saved the argument into
1596   // a virtual register in the entry block, so now we copy the value out
1597   // and into %rax.
1598   if (Subtarget->is64Bit() &&
1599       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1600     MachineFunction &MF = DAG.getMachineFunction();
1601     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1602     unsigned Reg = FuncInfo->getSRetReturnReg();
1603     assert(Reg &&
1604            "SRetReturnReg should have been set in LowerFormalArguments().");
1605     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1606
1607     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1608     Flag = Chain.getValue(1);
1609
1610     // RAX now acts like a return value.
1611     MRI.addLiveOut(X86::RAX);
1612   }
1613
1614   RetOps[0] = Chain;  // Update chain.
1615
1616   // Add the flag if we have it.
1617   if (Flag.getNode())
1618     RetOps.push_back(Flag);
1619
1620   return DAG.getNode(X86ISD::RET_FLAG, dl,
1621                      MVT::Other, &RetOps[0], RetOps.size());
1622 }
1623
1624 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1625   if (N->getNumValues() != 1)
1626     return false;
1627   if (!N->hasNUsesOfValue(1, 0))
1628     return false;
1629
1630   SDValue TCChain = Chain;
1631   SDNode *Copy = *N->use_begin();
1632   if (Copy->getOpcode() == ISD::CopyToReg) {
1633     // If the copy has a glue operand, we conservatively assume it isn't safe to
1634     // perform a tail call.
1635     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1636       return false;
1637     TCChain = Copy->getOperand(0);
1638   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1639     return false;
1640
1641   bool HasRet = false;
1642   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1643        UI != UE; ++UI) {
1644     if (UI->getOpcode() != X86ISD::RET_FLAG)
1645       return false;
1646     HasRet = true;
1647   }
1648
1649   if (!HasRet)
1650     return false;
1651
1652   Chain = TCChain;
1653   return true;
1654 }
1655
1656 EVT
1657 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1658                                             ISD::NodeType ExtendKind) const {
1659   MVT ReturnMVT;
1660   // TODO: Is this also valid on 32-bit?
1661   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1662     ReturnMVT = MVT::i8;
1663   else
1664     ReturnMVT = MVT::i32;
1665
1666   EVT MinVT = getRegisterType(Context, ReturnMVT);
1667   return VT.bitsLT(MinVT) ? MinVT : VT;
1668 }
1669
1670 /// LowerCallResult - Lower the result values of a call into the
1671 /// appropriate copies out of appropriate physical registers.
1672 ///
1673 SDValue
1674 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1675                                    CallingConv::ID CallConv, bool isVarArg,
1676                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1677                                    DebugLoc dl, SelectionDAG &DAG,
1678                                    SmallVectorImpl<SDValue> &InVals) const {
1679
1680   // Assign locations to each value returned by this call.
1681   SmallVector<CCValAssign, 16> RVLocs;
1682   bool Is64Bit = Subtarget->is64Bit();
1683   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1684                  getTargetMachine(), RVLocs, *DAG.getContext());
1685   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1686
1687   // Copy all of the result registers out of their specified physreg.
1688   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1689     CCValAssign &VA = RVLocs[i];
1690     EVT CopyVT = VA.getValVT();
1691
1692     // If this is x86-64, and we disabled SSE, we can't return FP values
1693     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1694         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1695       report_fatal_error("SSE register return with SSE disabled");
1696     }
1697
1698     SDValue Val;
1699
1700     // If this is a call to a function that returns an fp value on the floating
1701     // point stack, we must guarantee the value is popped from the stack, so
1702     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1703     // if the return value is not used. We use the FpPOP_RETVAL instruction
1704     // instead.
1705     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1706       // If we prefer to use the value in xmm registers, copy it out as f80 and
1707       // use a truncate to move it from fp stack reg to xmm reg.
1708       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1709       SDValue Ops[] = { Chain, InFlag };
1710       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1711                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1712       Val = Chain.getValue(0);
1713
1714       // Round the f80 to the right size, which also moves it to the appropriate
1715       // xmm register.
1716       if (CopyVT != VA.getValVT())
1717         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1718                           // This truncation won't change the value.
1719                           DAG.getIntPtrConstant(1));
1720     } else {
1721       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1722                                  CopyVT, InFlag).getValue(1);
1723       Val = Chain.getValue(0);
1724     }
1725     InFlag = Chain.getValue(2);
1726     InVals.push_back(Val);
1727   }
1728
1729   return Chain;
1730 }
1731
1732
1733 //===----------------------------------------------------------------------===//
1734 //                C & StdCall & Fast Calling Convention implementation
1735 //===----------------------------------------------------------------------===//
1736 //  StdCall calling convention seems to be standard for many Windows' API
1737 //  routines and around. It differs from C calling convention just a little:
1738 //  callee should clean up the stack, not caller. Symbols should be also
1739 //  decorated in some fancy way :) It doesn't support any vector arguments.
1740 //  For info on fast calling convention see Fast Calling Convention (tail call)
1741 //  implementation LowerX86_32FastCCCallTo.
1742
1743 /// CallIsStructReturn - Determines whether a call uses struct return
1744 /// semantics.
1745 enum StructReturnType {
1746   NotStructReturn,
1747   RegStructReturn,
1748   StackStructReturn
1749 };
1750 static StructReturnType
1751 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1752   if (Outs.empty())
1753     return NotStructReturn;
1754
1755   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1756   if (!Flags.isSRet())
1757     return NotStructReturn;
1758   if (Flags.isInReg())
1759     return RegStructReturn;
1760   return StackStructReturn;
1761 }
1762
1763 /// ArgsAreStructReturn - Determines whether a function uses struct
1764 /// return semantics.
1765 static StructReturnType
1766 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1767   if (Ins.empty())
1768     return NotStructReturn;
1769
1770   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1771   if (!Flags.isSRet())
1772     return NotStructReturn;
1773   if (Flags.isInReg())
1774     return RegStructReturn;
1775   return StackStructReturn;
1776 }
1777
1778 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1779 /// by "Src" to address "Dst" with size and alignment information specified by
1780 /// the specific parameter attribute. The copy will be passed as a byval
1781 /// function parameter.
1782 static SDValue
1783 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1784                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1785                           DebugLoc dl) {
1786   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1787
1788   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1789                        /*isVolatile*/false, /*AlwaysInline=*/true,
1790                        MachinePointerInfo(), MachinePointerInfo());
1791 }
1792
1793 /// IsTailCallConvention - Return true if the calling convention is one that
1794 /// supports tail call optimization.
1795 static bool IsTailCallConvention(CallingConv::ID CC) {
1796   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1797 }
1798
1799 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1800   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1801     return false;
1802
1803   CallSite CS(CI);
1804   CallingConv::ID CalleeCC = CS.getCallingConv();
1805   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1806     return false;
1807
1808   return true;
1809 }
1810
1811 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1812 /// a tailcall target by changing its ABI.
1813 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1814                                    bool GuaranteedTailCallOpt) {
1815   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1816 }
1817
1818 SDValue
1819 X86TargetLowering::LowerMemArgument(SDValue Chain,
1820                                     CallingConv::ID CallConv,
1821                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1822                                     DebugLoc dl, SelectionDAG &DAG,
1823                                     const CCValAssign &VA,
1824                                     MachineFrameInfo *MFI,
1825                                     unsigned i) const {
1826   // Create the nodes corresponding to a load from this parameter slot.
1827   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1828   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1829                               getTargetMachine().Options.GuaranteedTailCallOpt);
1830   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1831   EVT ValVT;
1832
1833   // If value is passed by pointer we have address passed instead of the value
1834   // itself.
1835   if (VA.getLocInfo() == CCValAssign::Indirect)
1836     ValVT = VA.getLocVT();
1837   else
1838     ValVT = VA.getValVT();
1839
1840   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1841   // changed with more analysis.
1842   // In case of tail call optimization mark all arguments mutable. Since they
1843   // could be overwritten by lowering of arguments in case of a tail call.
1844   if (Flags.isByVal()) {
1845     unsigned Bytes = Flags.getByValSize();
1846     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1847     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1848     return DAG.getFrameIndex(FI, getPointerTy());
1849   } else {
1850     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1851                                     VA.getLocMemOffset(), isImmutable);
1852     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1853     return DAG.getLoad(ValVT, dl, Chain, FIN,
1854                        MachinePointerInfo::getFixedStack(FI),
1855                        false, false, false, 0);
1856   }
1857 }
1858
1859 SDValue
1860 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1861                                         CallingConv::ID CallConv,
1862                                         bool isVarArg,
1863                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1864                                         DebugLoc dl,
1865                                         SelectionDAG &DAG,
1866                                         SmallVectorImpl<SDValue> &InVals)
1867                                           const {
1868   MachineFunction &MF = DAG.getMachineFunction();
1869   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1870
1871   const Function* Fn = MF.getFunction();
1872   if (Fn->hasExternalLinkage() &&
1873       Subtarget->isTargetCygMing() &&
1874       Fn->getName() == "main")
1875     FuncInfo->setForceFramePointer(true);
1876
1877   MachineFrameInfo *MFI = MF.getFrameInfo();
1878   bool Is64Bit = Subtarget->is64Bit();
1879   bool IsWindows = Subtarget->isTargetWindows();
1880   bool IsWin64 = Subtarget->isTargetWin64();
1881
1882   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1883          "Var args not supported with calling convention fastcc or ghc");
1884
1885   // Assign locations to all of the incoming arguments.
1886   SmallVector<CCValAssign, 16> ArgLocs;
1887   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1888                  ArgLocs, *DAG.getContext());
1889
1890   // Allocate shadow area for Win64
1891   if (IsWin64) {
1892     CCInfo.AllocateStack(32, 8);
1893   }
1894
1895   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1896
1897   unsigned LastVal = ~0U;
1898   SDValue ArgValue;
1899   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1900     CCValAssign &VA = ArgLocs[i];
1901     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1902     // places.
1903     assert(VA.getValNo() != LastVal &&
1904            "Don't support value assigned to multiple locs yet");
1905     (void)LastVal;
1906     LastVal = VA.getValNo();
1907
1908     if (VA.isRegLoc()) {
1909       EVT RegVT = VA.getLocVT();
1910       const TargetRegisterClass *RC;
1911       if (RegVT == MVT::i32)
1912         RC = &X86::GR32RegClass;
1913       else if (Is64Bit && RegVT == MVT::i64)
1914         RC = &X86::GR64RegClass;
1915       else if (RegVT == MVT::f32)
1916         RC = &X86::FR32RegClass;
1917       else if (RegVT == MVT::f64)
1918         RC = &X86::FR64RegClass;
1919       else if (RegVT.is256BitVector())
1920         RC = &X86::VR256RegClass;
1921       else if (RegVT.is128BitVector())
1922         RC = &X86::VR128RegClass;
1923       else if (RegVT == MVT::x86mmx)
1924         RC = &X86::VR64RegClass;
1925       else
1926         llvm_unreachable("Unknown argument type!");
1927
1928       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1929       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1930
1931       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1932       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1933       // right size.
1934       if (VA.getLocInfo() == CCValAssign::SExt)
1935         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1936                                DAG.getValueType(VA.getValVT()));
1937       else if (VA.getLocInfo() == CCValAssign::ZExt)
1938         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1939                                DAG.getValueType(VA.getValVT()));
1940       else if (VA.getLocInfo() == CCValAssign::BCvt)
1941         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1942
1943       if (VA.isExtInLoc()) {
1944         // Handle MMX values passed in XMM regs.
1945         if (RegVT.isVector()) {
1946           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1947                                  ArgValue);
1948         } else
1949           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1950       }
1951     } else {
1952       assert(VA.isMemLoc());
1953       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1954     }
1955
1956     // If value is passed via pointer - do a load.
1957     if (VA.getLocInfo() == CCValAssign::Indirect)
1958       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1959                              MachinePointerInfo(), false, false, false, 0);
1960
1961     InVals.push_back(ArgValue);
1962   }
1963
1964   // The x86-64 ABI for returning structs by value requires that we copy
1965   // the sret argument into %rax for the return. Save the argument into
1966   // a virtual register so that we can access it from the return points.
1967   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1968     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1969     unsigned Reg = FuncInfo->getSRetReturnReg();
1970     if (!Reg) {
1971       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1972       FuncInfo->setSRetReturnReg(Reg);
1973     }
1974     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1975     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1976   }
1977
1978   unsigned StackSize = CCInfo.getNextStackOffset();
1979   // Align stack specially for tail calls.
1980   if (FuncIsMadeTailCallSafe(CallConv,
1981                              MF.getTarget().Options.GuaranteedTailCallOpt))
1982     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1983
1984   // If the function takes variable number of arguments, make a frame index for
1985   // the start of the first vararg value... for expansion of llvm.va_start.
1986   if (isVarArg) {
1987     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1988                     CallConv != CallingConv::X86_ThisCall)) {
1989       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1990     }
1991     if (Is64Bit) {
1992       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1993
1994       // FIXME: We should really autogenerate these arrays
1995       static const uint16_t GPR64ArgRegsWin64[] = {
1996         X86::RCX, X86::RDX, X86::R8,  X86::R9
1997       };
1998       static const uint16_t GPR64ArgRegs64Bit[] = {
1999         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2000       };
2001       static const uint16_t XMMArgRegs64Bit[] = {
2002         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2003         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2004       };
2005       const uint16_t *GPR64ArgRegs;
2006       unsigned NumXMMRegs = 0;
2007
2008       if (IsWin64) {
2009         // The XMM registers which might contain var arg parameters are shadowed
2010         // in their paired GPR.  So we only need to save the GPR to their home
2011         // slots.
2012         TotalNumIntRegs = 4;
2013         GPR64ArgRegs = GPR64ArgRegsWin64;
2014       } else {
2015         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2016         GPR64ArgRegs = GPR64ArgRegs64Bit;
2017
2018         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2019                                                 TotalNumXMMRegs);
2020       }
2021       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2022                                                        TotalNumIntRegs);
2023
2024       bool NoImplicitFloatOps = Fn->getFnAttributes().
2025         hasAttribute(Attributes::NoImplicitFloat);
2026       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2027              "SSE register cannot be used when SSE is disabled!");
2028       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2029                NoImplicitFloatOps) &&
2030              "SSE register cannot be used when SSE is disabled!");
2031       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2032           !Subtarget->hasSSE1())
2033         // Kernel mode asks for SSE to be disabled, so don't push them
2034         // on the stack.
2035         TotalNumXMMRegs = 0;
2036
2037       if (IsWin64) {
2038         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2039         // Get to the caller-allocated home save location.  Add 8 to account
2040         // for the return address.
2041         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2042         FuncInfo->setRegSaveFrameIndex(
2043           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2044         // Fixup to set vararg frame on shadow area (4 x i64).
2045         if (NumIntRegs < 4)
2046           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2047       } else {
2048         // For X86-64, if there are vararg parameters that are passed via
2049         // registers, then we must store them to their spots on the stack so
2050         // they may be loaded by deferencing the result of va_next.
2051         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2052         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2053         FuncInfo->setRegSaveFrameIndex(
2054           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2055                                false));
2056       }
2057
2058       // Store the integer parameter registers.
2059       SmallVector<SDValue, 8> MemOps;
2060       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2061                                         getPointerTy());
2062       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2063       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2064         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2065                                   DAG.getIntPtrConstant(Offset));
2066         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2067                                      &X86::GR64RegClass);
2068         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2069         SDValue Store =
2070           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2071                        MachinePointerInfo::getFixedStack(
2072                          FuncInfo->getRegSaveFrameIndex(), Offset),
2073                        false, false, 0);
2074         MemOps.push_back(Store);
2075         Offset += 8;
2076       }
2077
2078       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2079         // Now store the XMM (fp + vector) parameter registers.
2080         SmallVector<SDValue, 11> SaveXMMOps;
2081         SaveXMMOps.push_back(Chain);
2082
2083         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2084         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2085         SaveXMMOps.push_back(ALVal);
2086
2087         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2088                                FuncInfo->getRegSaveFrameIndex()));
2089         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2090                                FuncInfo->getVarArgsFPOffset()));
2091
2092         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2093           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2094                                        &X86::VR128RegClass);
2095           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2096           SaveXMMOps.push_back(Val);
2097         }
2098         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2099                                      MVT::Other,
2100                                      &SaveXMMOps[0], SaveXMMOps.size()));
2101       }
2102
2103       if (!MemOps.empty())
2104         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2105                             &MemOps[0], MemOps.size());
2106     }
2107   }
2108
2109   // Some CCs need callee pop.
2110   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2111                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2112     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2113   } else {
2114     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2115     // If this is an sret function, the return should pop the hidden pointer.
2116     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2117         argsAreStructReturn(Ins) == StackStructReturn)
2118       FuncInfo->setBytesToPopOnReturn(4);
2119   }
2120
2121   if (!Is64Bit) {
2122     // RegSaveFrameIndex is X86-64 only.
2123     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2124     if (CallConv == CallingConv::X86_FastCall ||
2125         CallConv == CallingConv::X86_ThisCall)
2126       // fastcc functions can't have varargs.
2127       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2128   }
2129
2130   FuncInfo->setArgumentStackSize(StackSize);
2131
2132   return Chain;
2133 }
2134
2135 SDValue
2136 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2137                                     SDValue StackPtr, SDValue Arg,
2138                                     DebugLoc dl, SelectionDAG &DAG,
2139                                     const CCValAssign &VA,
2140                                     ISD::ArgFlagsTy Flags) const {
2141   unsigned LocMemOffset = VA.getLocMemOffset();
2142   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2143   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2144   if (Flags.isByVal())
2145     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2146
2147   return DAG.getStore(Chain, dl, Arg, PtrOff,
2148                       MachinePointerInfo::getStack(LocMemOffset),
2149                       false, false, 0);
2150 }
2151
2152 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2153 /// optimization is performed and it is required.
2154 SDValue
2155 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2156                                            SDValue &OutRetAddr, SDValue Chain,
2157                                            bool IsTailCall, bool Is64Bit,
2158                                            int FPDiff, DebugLoc dl) const {
2159   // Adjust the Return address stack slot.
2160   EVT VT = getPointerTy();
2161   OutRetAddr = getReturnAddressFrameIndex(DAG);
2162
2163   // Load the "old" Return address.
2164   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2165                            false, false, false, 0);
2166   return SDValue(OutRetAddr.getNode(), 1);
2167 }
2168
2169 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2170 /// optimization is performed and it is required (FPDiff!=0).
2171 static SDValue
2172 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2173                          SDValue Chain, SDValue RetAddrFrIdx,
2174                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2175   // Store the return address to the appropriate stack slot.
2176   if (!FPDiff) return Chain;
2177   // Calculate the new stack slot for the return address.
2178   int SlotSize = Is64Bit ? 8 : 4;
2179   int NewReturnAddrFI =
2180     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2181   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2182   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2183   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2184                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2185                        false, false, 0);
2186   return Chain;
2187 }
2188
2189 SDValue
2190 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2191                              SmallVectorImpl<SDValue> &InVals) const {
2192   SelectionDAG &DAG                     = CLI.DAG;
2193   DebugLoc &dl                          = CLI.DL;
2194   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2195   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2196   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2197   SDValue Chain                         = CLI.Chain;
2198   SDValue Callee                        = CLI.Callee;
2199   CallingConv::ID CallConv              = CLI.CallConv;
2200   bool &isTailCall                      = CLI.IsTailCall;
2201   bool isVarArg                         = CLI.IsVarArg;
2202
2203   MachineFunction &MF = DAG.getMachineFunction();
2204   bool Is64Bit        = Subtarget->is64Bit();
2205   bool IsWin64        = Subtarget->isTargetWin64();
2206   bool IsWindows      = Subtarget->isTargetWindows();
2207   StructReturnType SR = callIsStructReturn(Outs);
2208   bool IsSibcall      = false;
2209
2210   if (MF.getTarget().Options.DisableTailCalls)
2211     isTailCall = false;
2212
2213   if (isTailCall) {
2214     // Check if it's really possible to do a tail call.
2215     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2216                     isVarArg, SR != NotStructReturn,
2217                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2218                     Outs, OutVals, Ins, DAG);
2219
2220     // Sibcalls are automatically detected tailcalls which do not require
2221     // ABI changes.
2222     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2223       IsSibcall = true;
2224
2225     if (isTailCall)
2226       ++NumTailCalls;
2227   }
2228
2229   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2230          "Var args not supported with calling convention fastcc or ghc");
2231
2232   // Analyze operands of the call, assigning locations to each operand.
2233   SmallVector<CCValAssign, 16> ArgLocs;
2234   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2235                  ArgLocs, *DAG.getContext());
2236
2237   // Allocate shadow area for Win64
2238   if (IsWin64) {
2239     CCInfo.AllocateStack(32, 8);
2240   }
2241
2242   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2243
2244   // Get a count of how many bytes are to be pushed on the stack.
2245   unsigned NumBytes = CCInfo.getNextStackOffset();
2246   if (IsSibcall)
2247     // This is a sibcall. The memory operands are available in caller's
2248     // own caller's stack.
2249     NumBytes = 0;
2250   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2251            IsTailCallConvention(CallConv))
2252     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2253
2254   int FPDiff = 0;
2255   if (isTailCall && !IsSibcall) {
2256     // Lower arguments at fp - stackoffset + fpdiff.
2257     unsigned NumBytesCallerPushed =
2258       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2259     FPDiff = NumBytesCallerPushed - NumBytes;
2260
2261     // Set the delta of movement of the returnaddr stackslot.
2262     // But only set if delta is greater than previous delta.
2263     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2264       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2265   }
2266
2267   if (!IsSibcall)
2268     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2269
2270   SDValue RetAddrFrIdx;
2271   // Load return address for tail calls.
2272   if (isTailCall && FPDiff)
2273     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2274                                     Is64Bit, FPDiff, dl);
2275
2276   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2277   SmallVector<SDValue, 8> MemOpChains;
2278   SDValue StackPtr;
2279
2280   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2281   // of tail call optimization arguments are handle later.
2282   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2283     CCValAssign &VA = ArgLocs[i];
2284     EVT RegVT = VA.getLocVT();
2285     SDValue Arg = OutVals[i];
2286     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2287     bool isByVal = Flags.isByVal();
2288
2289     // Promote the value if needed.
2290     switch (VA.getLocInfo()) {
2291     default: llvm_unreachable("Unknown loc info!");
2292     case CCValAssign::Full: break;
2293     case CCValAssign::SExt:
2294       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2295       break;
2296     case CCValAssign::ZExt:
2297       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2298       break;
2299     case CCValAssign::AExt:
2300       if (RegVT.is128BitVector()) {
2301         // Special case: passing MMX values in XMM registers.
2302         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2303         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2304         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2305       } else
2306         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2307       break;
2308     case CCValAssign::BCvt:
2309       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2310       break;
2311     case CCValAssign::Indirect: {
2312       // Store the argument.
2313       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2314       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2315       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2316                            MachinePointerInfo::getFixedStack(FI),
2317                            false, false, 0);
2318       Arg = SpillSlot;
2319       break;
2320     }
2321     }
2322
2323     if (VA.isRegLoc()) {
2324       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2325       if (isVarArg && IsWin64) {
2326         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2327         // shadow reg if callee is a varargs function.
2328         unsigned ShadowReg = 0;
2329         switch (VA.getLocReg()) {
2330         case X86::XMM0: ShadowReg = X86::RCX; break;
2331         case X86::XMM1: ShadowReg = X86::RDX; break;
2332         case X86::XMM2: ShadowReg = X86::R8; break;
2333         case X86::XMM3: ShadowReg = X86::R9; break;
2334         }
2335         if (ShadowReg)
2336           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2337       }
2338     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2339       assert(VA.isMemLoc());
2340       if (StackPtr.getNode() == 0)
2341         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2342       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2343                                              dl, DAG, VA, Flags));
2344     }
2345   }
2346
2347   if (!MemOpChains.empty())
2348     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2349                         &MemOpChains[0], MemOpChains.size());
2350
2351   if (Subtarget->isPICStyleGOT()) {
2352     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2353     // GOT pointer.
2354     if (!isTailCall) {
2355       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2356                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2357     } else {
2358       // If we are tail calling and generating PIC/GOT style code load the
2359       // address of the callee into ECX. The value in ecx is used as target of
2360       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2361       // for tail calls on PIC/GOT architectures. Normally we would just put the
2362       // address of GOT into ebx and then call target@PLT. But for tail calls
2363       // ebx would be restored (since ebx is callee saved) before jumping to the
2364       // target@PLT.
2365
2366       // Note: The actual moving to ECX is done further down.
2367       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2368       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2369           !G->getGlobal()->hasProtectedVisibility())
2370         Callee = LowerGlobalAddress(Callee, DAG);
2371       else if (isa<ExternalSymbolSDNode>(Callee))
2372         Callee = LowerExternalSymbol(Callee, DAG);
2373     }
2374   }
2375
2376   if (Is64Bit && isVarArg && !IsWin64) {
2377     // From AMD64 ABI document:
2378     // For calls that may call functions that use varargs or stdargs
2379     // (prototype-less calls or calls to functions containing ellipsis (...) in
2380     // the declaration) %al is used as hidden argument to specify the number
2381     // of SSE registers used. The contents of %al do not need to match exactly
2382     // the number of registers, but must be an ubound on the number of SSE
2383     // registers used and is in the range 0 - 8 inclusive.
2384
2385     // Count the number of XMM registers allocated.
2386     static const uint16_t XMMArgRegs[] = {
2387       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2388       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2389     };
2390     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2391     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2392            && "SSE registers cannot be used when SSE is disabled");
2393
2394     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2395                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2396   }
2397
2398   // For tail calls lower the arguments to the 'real' stack slot.
2399   if (isTailCall) {
2400     // Force all the incoming stack arguments to be loaded from the stack
2401     // before any new outgoing arguments are stored to the stack, because the
2402     // outgoing stack slots may alias the incoming argument stack slots, and
2403     // the alias isn't otherwise explicit. This is slightly more conservative
2404     // than necessary, because it means that each store effectively depends
2405     // on every argument instead of just those arguments it would clobber.
2406     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2407
2408     SmallVector<SDValue, 8> MemOpChains2;
2409     SDValue FIN;
2410     int FI = 0;
2411     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2412       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2413         CCValAssign &VA = ArgLocs[i];
2414         if (VA.isRegLoc())
2415           continue;
2416         assert(VA.isMemLoc());
2417         SDValue Arg = OutVals[i];
2418         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419         // Create frame index.
2420         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2421         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2422         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2423         FIN = DAG.getFrameIndex(FI, getPointerTy());
2424
2425         if (Flags.isByVal()) {
2426           // Copy relative to framepointer.
2427           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2428           if (StackPtr.getNode() == 0)
2429             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2430                                           getPointerTy());
2431           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2432
2433           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2434                                                            ArgChain,
2435                                                            Flags, DAG, dl));
2436         } else {
2437           // Store relative to framepointer.
2438           MemOpChains2.push_back(
2439             DAG.getStore(ArgChain, dl, Arg, FIN,
2440                          MachinePointerInfo::getFixedStack(FI),
2441                          false, false, 0));
2442         }
2443       }
2444     }
2445
2446     if (!MemOpChains2.empty())
2447       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2448                           &MemOpChains2[0], MemOpChains2.size());
2449
2450     // Store the return address to the appropriate stack slot.
2451     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2452                                      FPDiff, dl);
2453   }
2454
2455   // Build a sequence of copy-to-reg nodes chained together with token chain
2456   // and flag operands which copy the outgoing args into registers.
2457   SDValue InFlag;
2458   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2459     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2460                              RegsToPass[i].second, InFlag);
2461     InFlag = Chain.getValue(1);
2462   }
2463
2464   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2465     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2466     // In the 64-bit large code model, we have to make all calls
2467     // through a register, since the call instruction's 32-bit
2468     // pc-relative offset may not be large enough to hold the whole
2469     // address.
2470   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2471     // If the callee is a GlobalAddress node (quite common, every direct call
2472     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2473     // it.
2474
2475     // We should use extra load for direct calls to dllimported functions in
2476     // non-JIT mode.
2477     const GlobalValue *GV = G->getGlobal();
2478     if (!GV->hasDLLImportLinkage()) {
2479       unsigned char OpFlags = 0;
2480       bool ExtraLoad = false;
2481       unsigned WrapperKind = ISD::DELETED_NODE;
2482
2483       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2484       // external symbols most go through the PLT in PIC mode.  If the symbol
2485       // has hidden or protected visibility, or if it is static or local, then
2486       // we don't need to use the PLT - we can directly call it.
2487       if (Subtarget->isTargetELF() &&
2488           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2489           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2490         OpFlags = X86II::MO_PLT;
2491       } else if (Subtarget->isPICStyleStubAny() &&
2492                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2493                  (!Subtarget->getTargetTriple().isMacOSX() ||
2494                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2495         // PC-relative references to external symbols should go through $stub,
2496         // unless we're building with the leopard linker or later, which
2497         // automatically synthesizes these stubs.
2498         OpFlags = X86II::MO_DARWIN_STUB;
2499       } else if (Subtarget->isPICStyleRIPRel() &&
2500                  isa<Function>(GV) &&
2501                  cast<Function>(GV)->getFnAttributes().
2502                    hasAttribute(Attributes::NonLazyBind)) {
2503         // If the function is marked as non-lazy, generate an indirect call
2504         // which loads from the GOT directly. This avoids runtime overhead
2505         // at the cost of eager binding (and one extra byte of encoding).
2506         OpFlags = X86II::MO_GOTPCREL;
2507         WrapperKind = X86ISD::WrapperRIP;
2508         ExtraLoad = true;
2509       }
2510
2511       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2512                                           G->getOffset(), OpFlags);
2513
2514       // Add a wrapper if needed.
2515       if (WrapperKind != ISD::DELETED_NODE)
2516         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2517       // Add extra indirection if needed.
2518       if (ExtraLoad)
2519         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2520                              MachinePointerInfo::getGOT(),
2521                              false, false, false, 0);
2522     }
2523   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2524     unsigned char OpFlags = 0;
2525
2526     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2527     // external symbols should go through the PLT.
2528     if (Subtarget->isTargetELF() &&
2529         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2530       OpFlags = X86II::MO_PLT;
2531     } else if (Subtarget->isPICStyleStubAny() &&
2532                (!Subtarget->getTargetTriple().isMacOSX() ||
2533                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2534       // PC-relative references to external symbols should go through $stub,
2535       // unless we're building with the leopard linker or later, which
2536       // automatically synthesizes these stubs.
2537       OpFlags = X86II::MO_DARWIN_STUB;
2538     }
2539
2540     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2541                                          OpFlags);
2542   }
2543
2544   // Returns a chain & a flag for retval copy to use.
2545   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2546   SmallVector<SDValue, 8> Ops;
2547
2548   if (!IsSibcall && isTailCall) {
2549     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2550                            DAG.getIntPtrConstant(0, true), InFlag);
2551     InFlag = Chain.getValue(1);
2552   }
2553
2554   Ops.push_back(Chain);
2555   Ops.push_back(Callee);
2556
2557   if (isTailCall)
2558     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2559
2560   // Add argument registers to the end of the list so that they are known live
2561   // into the call.
2562   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2563     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2564                                   RegsToPass[i].second.getValueType()));
2565
2566   // Add a register mask operand representing the call-preserved registers.
2567   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2568   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2569   assert(Mask && "Missing call preserved mask for calling convention");
2570   Ops.push_back(DAG.getRegisterMask(Mask));
2571
2572   if (InFlag.getNode())
2573     Ops.push_back(InFlag);
2574
2575   if (isTailCall) {
2576     // We used to do:
2577     //// If this is the first return lowered for this function, add the regs
2578     //// to the liveout set for the function.
2579     // This isn't right, although it's probably harmless on x86; liveouts
2580     // should be computed from returns not tail calls.  Consider a void
2581     // function making a tail call to a function returning int.
2582     return DAG.getNode(X86ISD::TC_RETURN, dl,
2583                        NodeTys, &Ops[0], Ops.size());
2584   }
2585
2586   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2587   InFlag = Chain.getValue(1);
2588
2589   // Create the CALLSEQ_END node.
2590   unsigned NumBytesForCalleeToPush;
2591   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2592                        getTargetMachine().Options.GuaranteedTailCallOpt))
2593     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2594   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2595            SR == StackStructReturn)
2596     // If this is a call to a struct-return function, the callee
2597     // pops the hidden struct pointer, so we have to push it back.
2598     // This is common for Darwin/X86, Linux & Mingw32 targets.
2599     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2600     NumBytesForCalleeToPush = 4;
2601   else
2602     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2603
2604   // Returns a flag for retval copy to use.
2605   if (!IsSibcall) {
2606     Chain = DAG.getCALLSEQ_END(Chain,
2607                                DAG.getIntPtrConstant(NumBytes, true),
2608                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2609                                                      true),
2610                                InFlag);
2611     InFlag = Chain.getValue(1);
2612   }
2613
2614   // Handle result values, copying them out of physregs into vregs that we
2615   // return.
2616   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2617                          Ins, dl, DAG, InVals);
2618 }
2619
2620
2621 //===----------------------------------------------------------------------===//
2622 //                Fast Calling Convention (tail call) implementation
2623 //===----------------------------------------------------------------------===//
2624
2625 //  Like std call, callee cleans arguments, convention except that ECX is
2626 //  reserved for storing the tail called function address. Only 2 registers are
2627 //  free for argument passing (inreg). Tail call optimization is performed
2628 //  provided:
2629 //                * tailcallopt is enabled
2630 //                * caller/callee are fastcc
2631 //  On X86_64 architecture with GOT-style position independent code only local
2632 //  (within module) calls are supported at the moment.
2633 //  To keep the stack aligned according to platform abi the function
2634 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2635 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2636 //  If a tail called function callee has more arguments than the caller the
2637 //  caller needs to make sure that there is room to move the RETADDR to. This is
2638 //  achieved by reserving an area the size of the argument delta right after the
2639 //  original REtADDR, but before the saved framepointer or the spilled registers
2640 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2641 //  stack layout:
2642 //    arg1
2643 //    arg2
2644 //    RETADDR
2645 //    [ new RETADDR
2646 //      move area ]
2647 //    (possible EBP)
2648 //    ESI
2649 //    EDI
2650 //    local1 ..
2651
2652 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2653 /// for a 16 byte align requirement.
2654 unsigned
2655 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2656                                                SelectionDAG& DAG) const {
2657   MachineFunction &MF = DAG.getMachineFunction();
2658   const TargetMachine &TM = MF.getTarget();
2659   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2660   unsigned StackAlignment = TFI.getStackAlignment();
2661   uint64_t AlignMask = StackAlignment - 1;
2662   int64_t Offset = StackSize;
2663   uint64_t SlotSize = TD->getPointerSize(0);
2664   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2665     // Number smaller than 12 so just add the difference.
2666     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2667   } else {
2668     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2669     Offset = ((~AlignMask) & Offset) + StackAlignment +
2670       (StackAlignment-SlotSize);
2671   }
2672   return Offset;
2673 }
2674
2675 /// MatchingStackOffset - Return true if the given stack call argument is
2676 /// already available in the same position (relatively) of the caller's
2677 /// incoming argument stack.
2678 static
2679 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2680                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2681                          const X86InstrInfo *TII) {
2682   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2683   int FI = INT_MAX;
2684   if (Arg.getOpcode() == ISD::CopyFromReg) {
2685     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2686     if (!TargetRegisterInfo::isVirtualRegister(VR))
2687       return false;
2688     MachineInstr *Def = MRI->getVRegDef(VR);
2689     if (!Def)
2690       return false;
2691     if (!Flags.isByVal()) {
2692       if (!TII->isLoadFromStackSlot(Def, FI))
2693         return false;
2694     } else {
2695       unsigned Opcode = Def->getOpcode();
2696       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2697           Def->getOperand(1).isFI()) {
2698         FI = Def->getOperand(1).getIndex();
2699         Bytes = Flags.getByValSize();
2700       } else
2701         return false;
2702     }
2703   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2704     if (Flags.isByVal())
2705       // ByVal argument is passed in as a pointer but it's now being
2706       // dereferenced. e.g.
2707       // define @foo(%struct.X* %A) {
2708       //   tail call @bar(%struct.X* byval %A)
2709       // }
2710       return false;
2711     SDValue Ptr = Ld->getBasePtr();
2712     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2713     if (!FINode)
2714       return false;
2715     FI = FINode->getIndex();
2716   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2717     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2718     FI = FINode->getIndex();
2719     Bytes = Flags.getByValSize();
2720   } else
2721     return false;
2722
2723   assert(FI != INT_MAX);
2724   if (!MFI->isFixedObjectIndex(FI))
2725     return false;
2726   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2727 }
2728
2729 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2730 /// for tail call optimization. Targets which want to do tail call
2731 /// optimization should implement this function.
2732 bool
2733 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2734                                                      CallingConv::ID CalleeCC,
2735                                                      bool isVarArg,
2736                                                      bool isCalleeStructRet,
2737                                                      bool isCallerStructRet,
2738                                                      Type *RetTy,
2739                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2740                                     const SmallVectorImpl<SDValue> &OutVals,
2741                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2742                                                      SelectionDAG& DAG) const {
2743   if (!IsTailCallConvention(CalleeCC) &&
2744       CalleeCC != CallingConv::C)
2745     return false;
2746
2747   // If -tailcallopt is specified, make fastcc functions tail-callable.
2748   const MachineFunction &MF = DAG.getMachineFunction();
2749   const Function *CallerF = DAG.getMachineFunction().getFunction();
2750
2751   // If the function return type is x86_fp80 and the callee return type is not,
2752   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2753   // perform a tailcall optimization here.
2754   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2755     return false;
2756
2757   CallingConv::ID CallerCC = CallerF->getCallingConv();
2758   bool CCMatch = CallerCC == CalleeCC;
2759
2760   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2761     if (IsTailCallConvention(CalleeCC) && CCMatch)
2762       return true;
2763     return false;
2764   }
2765
2766   // Look for obvious safe cases to perform tail call optimization that do not
2767   // require ABI changes. This is what gcc calls sibcall.
2768
2769   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2770   // emit a special epilogue.
2771   if (RegInfo->needsStackRealignment(MF))
2772     return false;
2773
2774   // Also avoid sibcall optimization if either caller or callee uses struct
2775   // return semantics.
2776   if (isCalleeStructRet || isCallerStructRet)
2777     return false;
2778
2779   // An stdcall caller is expected to clean up its arguments; the callee
2780   // isn't going to do that.
2781   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2782     return false;
2783
2784   // Do not sibcall optimize vararg calls unless all arguments are passed via
2785   // registers.
2786   if (isVarArg && !Outs.empty()) {
2787
2788     // Optimizing for varargs on Win64 is unlikely to be safe without
2789     // additional testing.
2790     if (Subtarget->isTargetWin64())
2791       return false;
2792
2793     SmallVector<CCValAssign, 16> ArgLocs;
2794     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2795                    getTargetMachine(), ArgLocs, *DAG.getContext());
2796
2797     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2798     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2799       if (!ArgLocs[i].isRegLoc())
2800         return false;
2801   }
2802
2803   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2804   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2805   // this into a sibcall.
2806   bool Unused = false;
2807   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2808     if (!Ins[i].Used) {
2809       Unused = true;
2810       break;
2811     }
2812   }
2813   if (Unused) {
2814     SmallVector<CCValAssign, 16> RVLocs;
2815     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2816                    getTargetMachine(), RVLocs, *DAG.getContext());
2817     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2818     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2819       CCValAssign &VA = RVLocs[i];
2820       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2821         return false;
2822     }
2823   }
2824
2825   // If the calling conventions do not match, then we'd better make sure the
2826   // results are returned in the same way as what the caller expects.
2827   if (!CCMatch) {
2828     SmallVector<CCValAssign, 16> RVLocs1;
2829     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2830                     getTargetMachine(), RVLocs1, *DAG.getContext());
2831     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2832
2833     SmallVector<CCValAssign, 16> RVLocs2;
2834     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2835                     getTargetMachine(), RVLocs2, *DAG.getContext());
2836     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2837
2838     if (RVLocs1.size() != RVLocs2.size())
2839       return false;
2840     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2841       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2842         return false;
2843       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2844         return false;
2845       if (RVLocs1[i].isRegLoc()) {
2846         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2847           return false;
2848       } else {
2849         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2850           return false;
2851       }
2852     }
2853   }
2854
2855   // If the callee takes no arguments then go on to check the results of the
2856   // call.
2857   if (!Outs.empty()) {
2858     // Check if stack adjustment is needed. For now, do not do this if any
2859     // argument is passed on the stack.
2860     SmallVector<CCValAssign, 16> ArgLocs;
2861     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2862                    getTargetMachine(), ArgLocs, *DAG.getContext());
2863
2864     // Allocate shadow area for Win64
2865     if (Subtarget->isTargetWin64()) {
2866       CCInfo.AllocateStack(32, 8);
2867     }
2868
2869     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2870     if (CCInfo.getNextStackOffset()) {
2871       MachineFunction &MF = DAG.getMachineFunction();
2872       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2873         return false;
2874
2875       // Check if the arguments are already laid out in the right way as
2876       // the caller's fixed stack objects.
2877       MachineFrameInfo *MFI = MF.getFrameInfo();
2878       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2879       const X86InstrInfo *TII =
2880         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2881       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2882         CCValAssign &VA = ArgLocs[i];
2883         SDValue Arg = OutVals[i];
2884         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2885         if (VA.getLocInfo() == CCValAssign::Indirect)
2886           return false;
2887         if (!VA.isRegLoc()) {
2888           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2889                                    MFI, MRI, TII))
2890             return false;
2891         }
2892       }
2893     }
2894
2895     // If the tailcall address may be in a register, then make sure it's
2896     // possible to register allocate for it. In 32-bit, the call address can
2897     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2898     // callee-saved registers are restored. These happen to be the same
2899     // registers used to pass 'inreg' arguments so watch out for those.
2900     if (!Subtarget->is64Bit() &&
2901         !isa<GlobalAddressSDNode>(Callee) &&
2902         !isa<ExternalSymbolSDNode>(Callee)) {
2903       unsigned NumInRegs = 0;
2904       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2905         CCValAssign &VA = ArgLocs[i];
2906         if (!VA.isRegLoc())
2907           continue;
2908         unsigned Reg = VA.getLocReg();
2909         switch (Reg) {
2910         default: break;
2911         case X86::EAX: case X86::EDX: case X86::ECX:
2912           if (++NumInRegs == 3)
2913             return false;
2914           break;
2915         }
2916       }
2917     }
2918   }
2919
2920   return true;
2921 }
2922
2923 FastISel *
2924 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2925                                   const TargetLibraryInfo *libInfo) const {
2926   return X86::createFastISel(funcInfo, libInfo);
2927 }
2928
2929
2930 //===----------------------------------------------------------------------===//
2931 //                           Other Lowering Hooks
2932 //===----------------------------------------------------------------------===//
2933
2934 static bool MayFoldLoad(SDValue Op) {
2935   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2936 }
2937
2938 static bool MayFoldIntoStore(SDValue Op) {
2939   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2940 }
2941
2942 static bool isTargetShuffle(unsigned Opcode) {
2943   switch(Opcode) {
2944   default: return false;
2945   case X86ISD::PSHUFD:
2946   case X86ISD::PSHUFHW:
2947   case X86ISD::PSHUFLW:
2948   case X86ISD::SHUFP:
2949   case X86ISD::PALIGN:
2950   case X86ISD::MOVLHPS:
2951   case X86ISD::MOVLHPD:
2952   case X86ISD::MOVHLPS:
2953   case X86ISD::MOVLPS:
2954   case X86ISD::MOVLPD:
2955   case X86ISD::MOVSHDUP:
2956   case X86ISD::MOVSLDUP:
2957   case X86ISD::MOVDDUP:
2958   case X86ISD::MOVSS:
2959   case X86ISD::MOVSD:
2960   case X86ISD::UNPCKL:
2961   case X86ISD::UNPCKH:
2962   case X86ISD::VPERMILP:
2963   case X86ISD::VPERM2X128:
2964   case X86ISD::VPERMI:
2965     return true;
2966   }
2967 }
2968
2969 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2970                                     SDValue V1, SelectionDAG &DAG) {
2971   switch(Opc) {
2972   default: llvm_unreachable("Unknown x86 shuffle node");
2973   case X86ISD::MOVSHDUP:
2974   case X86ISD::MOVSLDUP:
2975   case X86ISD::MOVDDUP:
2976     return DAG.getNode(Opc, dl, VT, V1);
2977   }
2978 }
2979
2980 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2981                                     SDValue V1, unsigned TargetMask,
2982                                     SelectionDAG &DAG) {
2983   switch(Opc) {
2984   default: llvm_unreachable("Unknown x86 shuffle node");
2985   case X86ISD::PSHUFD:
2986   case X86ISD::PSHUFHW:
2987   case X86ISD::PSHUFLW:
2988   case X86ISD::VPERMILP:
2989   case X86ISD::VPERMI:
2990     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2991   }
2992 }
2993
2994 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2995                                     SDValue V1, SDValue V2, unsigned TargetMask,
2996                                     SelectionDAG &DAG) {
2997   switch(Opc) {
2998   default: llvm_unreachable("Unknown x86 shuffle node");
2999   case X86ISD::PALIGN:
3000   case X86ISD::SHUFP:
3001   case X86ISD::VPERM2X128:
3002     return DAG.getNode(Opc, dl, VT, V1, V2,
3003                        DAG.getConstant(TargetMask, MVT::i8));
3004   }
3005 }
3006
3007 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3008                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3009   switch(Opc) {
3010   default: llvm_unreachable("Unknown x86 shuffle node");
3011   case X86ISD::MOVLHPS:
3012   case X86ISD::MOVLHPD:
3013   case X86ISD::MOVHLPS:
3014   case X86ISD::MOVLPS:
3015   case X86ISD::MOVLPD:
3016   case X86ISD::MOVSS:
3017   case X86ISD::MOVSD:
3018   case X86ISD::UNPCKL:
3019   case X86ISD::UNPCKH:
3020     return DAG.getNode(Opc, dl, VT, V1, V2);
3021   }
3022 }
3023
3024 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3025   MachineFunction &MF = DAG.getMachineFunction();
3026   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3027   int ReturnAddrIndex = FuncInfo->getRAIndex();
3028
3029   if (ReturnAddrIndex == 0) {
3030     // Set up a frame object for the return address.
3031     uint64_t SlotSize = TD->getPointerSize(0);
3032     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3033                                                            false);
3034     FuncInfo->setRAIndex(ReturnAddrIndex);
3035   }
3036
3037   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3038 }
3039
3040
3041 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3042                                        bool hasSymbolicDisplacement) {
3043   // Offset should fit into 32 bit immediate field.
3044   if (!isInt<32>(Offset))
3045     return false;
3046
3047   // If we don't have a symbolic displacement - we don't have any extra
3048   // restrictions.
3049   if (!hasSymbolicDisplacement)
3050     return true;
3051
3052   // FIXME: Some tweaks might be needed for medium code model.
3053   if (M != CodeModel::Small && M != CodeModel::Kernel)
3054     return false;
3055
3056   // For small code model we assume that latest object is 16MB before end of 31
3057   // bits boundary. We may also accept pretty large negative constants knowing
3058   // that all objects are in the positive half of address space.
3059   if (M == CodeModel::Small && Offset < 16*1024*1024)
3060     return true;
3061
3062   // For kernel code model we know that all object resist in the negative half
3063   // of 32bits address space. We may not accept negative offsets, since they may
3064   // be just off and we may accept pretty large positive ones.
3065   if (M == CodeModel::Kernel && Offset > 0)
3066     return true;
3067
3068   return false;
3069 }
3070
3071 /// isCalleePop - Determines whether the callee is required to pop its
3072 /// own arguments. Callee pop is necessary to support tail calls.
3073 bool X86::isCalleePop(CallingConv::ID CallingConv,
3074                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3075   if (IsVarArg)
3076     return false;
3077
3078   switch (CallingConv) {
3079   default:
3080     return false;
3081   case CallingConv::X86_StdCall:
3082     return !is64Bit;
3083   case CallingConv::X86_FastCall:
3084     return !is64Bit;
3085   case CallingConv::X86_ThisCall:
3086     return !is64Bit;
3087   case CallingConv::Fast:
3088     return TailCallOpt;
3089   case CallingConv::GHC:
3090     return TailCallOpt;
3091   }
3092 }
3093
3094 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3095 /// specific condition code, returning the condition code and the LHS/RHS of the
3096 /// comparison to make.
3097 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3098                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3099   if (!isFP) {
3100     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3101       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3102         // X > -1   -> X == 0, jump !sign.
3103         RHS = DAG.getConstant(0, RHS.getValueType());
3104         return X86::COND_NS;
3105       }
3106       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3107         // X < 0   -> X == 0, jump on sign.
3108         return X86::COND_S;
3109       }
3110       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3111         // X < 1   -> X <= 0
3112         RHS = DAG.getConstant(0, RHS.getValueType());
3113         return X86::COND_LE;
3114       }
3115     }
3116
3117     switch (SetCCOpcode) {
3118     default: llvm_unreachable("Invalid integer condition!");
3119     case ISD::SETEQ:  return X86::COND_E;
3120     case ISD::SETGT:  return X86::COND_G;
3121     case ISD::SETGE:  return X86::COND_GE;
3122     case ISD::SETLT:  return X86::COND_L;
3123     case ISD::SETLE:  return X86::COND_LE;
3124     case ISD::SETNE:  return X86::COND_NE;
3125     case ISD::SETULT: return X86::COND_B;
3126     case ISD::SETUGT: return X86::COND_A;
3127     case ISD::SETULE: return X86::COND_BE;
3128     case ISD::SETUGE: return X86::COND_AE;
3129     }
3130   }
3131
3132   // First determine if it is required or is profitable to flip the operands.
3133
3134   // If LHS is a foldable load, but RHS is not, flip the condition.
3135   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3136       !ISD::isNON_EXTLoad(RHS.getNode())) {
3137     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3138     std::swap(LHS, RHS);
3139   }
3140
3141   switch (SetCCOpcode) {
3142   default: break;
3143   case ISD::SETOLT:
3144   case ISD::SETOLE:
3145   case ISD::SETUGT:
3146   case ISD::SETUGE:
3147     std::swap(LHS, RHS);
3148     break;
3149   }
3150
3151   // On a floating point condition, the flags are set as follows:
3152   // ZF  PF  CF   op
3153   //  0 | 0 | 0 | X > Y
3154   //  0 | 0 | 1 | X < Y
3155   //  1 | 0 | 0 | X == Y
3156   //  1 | 1 | 1 | unordered
3157   switch (SetCCOpcode) {
3158   default: llvm_unreachable("Condcode should be pre-legalized away");
3159   case ISD::SETUEQ:
3160   case ISD::SETEQ:   return X86::COND_E;
3161   case ISD::SETOLT:              // flipped
3162   case ISD::SETOGT:
3163   case ISD::SETGT:   return X86::COND_A;
3164   case ISD::SETOLE:              // flipped
3165   case ISD::SETOGE:
3166   case ISD::SETGE:   return X86::COND_AE;
3167   case ISD::SETUGT:              // flipped
3168   case ISD::SETULT:
3169   case ISD::SETLT:   return X86::COND_B;
3170   case ISD::SETUGE:              // flipped
3171   case ISD::SETULE:
3172   case ISD::SETLE:   return X86::COND_BE;
3173   case ISD::SETONE:
3174   case ISD::SETNE:   return X86::COND_NE;
3175   case ISD::SETUO:   return X86::COND_P;
3176   case ISD::SETO:    return X86::COND_NP;
3177   case ISD::SETOEQ:
3178   case ISD::SETUNE:  return X86::COND_INVALID;
3179   }
3180 }
3181
3182 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3183 /// code. Current x86 isa includes the following FP cmov instructions:
3184 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3185 static bool hasFPCMov(unsigned X86CC) {
3186   switch (X86CC) {
3187   default:
3188     return false;
3189   case X86::COND_B:
3190   case X86::COND_BE:
3191   case X86::COND_E:
3192   case X86::COND_P:
3193   case X86::COND_A:
3194   case X86::COND_AE:
3195   case X86::COND_NE:
3196   case X86::COND_NP:
3197     return true;
3198   }
3199 }
3200
3201 /// isFPImmLegal - Returns true if the target can instruction select the
3202 /// specified FP immediate natively. If false, the legalizer will
3203 /// materialize the FP immediate as a load from a constant pool.
3204 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3205   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3206     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3207       return true;
3208   }
3209   return false;
3210 }
3211
3212 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3213 /// the specified range (L, H].
3214 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3215   return (Val < 0) || (Val >= Low && Val < Hi);
3216 }
3217
3218 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3219 /// specified value.
3220 static bool isUndefOrEqual(int Val, int CmpVal) {
3221   if (Val < 0 || Val == CmpVal)
3222     return true;
3223   return false;
3224 }
3225
3226 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3227 /// from position Pos and ending in Pos+Size, falls within the specified
3228 /// sequential range (L, L+Pos]. or is undef.
3229 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3230                                        unsigned Pos, unsigned Size, int Low) {
3231   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3232     if (!isUndefOrEqual(Mask[i], Low))
3233       return false;
3234   return true;
3235 }
3236
3237 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3238 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3239 /// the second operand.
3240 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3241   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3242     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3243   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3244     return (Mask[0] < 2 && Mask[1] < 2);
3245   return false;
3246 }
3247
3248 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3249 /// is suitable for input to PSHUFHW.
3250 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3251   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3252     return false;
3253
3254   // Lower quadword copied in order or undef.
3255   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3256     return false;
3257
3258   // Upper quadword shuffled.
3259   for (unsigned i = 4; i != 8; ++i)
3260     if (!isUndefOrInRange(Mask[i], 4, 8))
3261       return false;
3262
3263   if (VT == MVT::v16i16) {
3264     // Lower quadword copied in order or undef.
3265     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3266       return false;
3267
3268     // Upper quadword shuffled.
3269     for (unsigned i = 12; i != 16; ++i)
3270       if (!isUndefOrInRange(Mask[i], 12, 16))
3271         return false;
3272   }
3273
3274   return true;
3275 }
3276
3277 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3278 /// is suitable for input to PSHUFLW.
3279 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3280   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3281     return false;
3282
3283   // Upper quadword copied in order.
3284   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3285     return false;
3286
3287   // Lower quadword shuffled.
3288   for (unsigned i = 0; i != 4; ++i)
3289     if (!isUndefOrInRange(Mask[i], 0, 4))
3290       return false;
3291
3292   if (VT == MVT::v16i16) {
3293     // Upper quadword copied in order.
3294     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3295       return false;
3296
3297     // Lower quadword shuffled.
3298     for (unsigned i = 8; i != 12; ++i)
3299       if (!isUndefOrInRange(Mask[i], 8, 12))
3300         return false;
3301   }
3302
3303   return true;
3304 }
3305
3306 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3307 /// is suitable for input to PALIGNR.
3308 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3309                           const X86Subtarget *Subtarget) {
3310   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3311       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3312     return false;
3313
3314   unsigned NumElts = VT.getVectorNumElements();
3315   unsigned NumLanes = VT.getSizeInBits()/128;
3316   unsigned NumLaneElts = NumElts/NumLanes;
3317
3318   // Do not handle 64-bit element shuffles with palignr.
3319   if (NumLaneElts == 2)
3320     return false;
3321
3322   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3323     unsigned i;
3324     for (i = 0; i != NumLaneElts; ++i) {
3325       if (Mask[i+l] >= 0)
3326         break;
3327     }
3328
3329     // Lane is all undef, go to next lane
3330     if (i == NumLaneElts)
3331       continue;
3332
3333     int Start = Mask[i+l];
3334
3335     // Make sure its in this lane in one of the sources
3336     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3337         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3338       return false;
3339
3340     // If not lane 0, then we must match lane 0
3341     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3342       return false;
3343
3344     // Correct second source to be contiguous with first source
3345     if (Start >= (int)NumElts)
3346       Start -= NumElts - NumLaneElts;
3347
3348     // Make sure we're shifting in the right direction.
3349     if (Start <= (int)(i+l))
3350       return false;
3351
3352     Start -= i;
3353
3354     // Check the rest of the elements to see if they are consecutive.
3355     for (++i; i != NumLaneElts; ++i) {
3356       int Idx = Mask[i+l];
3357
3358       // Make sure its in this lane
3359       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3360           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3361         return false;
3362
3363       // If not lane 0, then we must match lane 0
3364       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3365         return false;
3366
3367       if (Idx >= (int)NumElts)
3368         Idx -= NumElts - NumLaneElts;
3369
3370       if (!isUndefOrEqual(Idx, Start+i))
3371         return false;
3372
3373     }
3374   }
3375
3376   return true;
3377 }
3378
3379 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3380 /// the two vector operands have swapped position.
3381 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3382                                      unsigned NumElems) {
3383   for (unsigned i = 0; i != NumElems; ++i) {
3384     int idx = Mask[i];
3385     if (idx < 0)
3386       continue;
3387     else if (idx < (int)NumElems)
3388       Mask[i] = idx + NumElems;
3389     else
3390       Mask[i] = idx - NumElems;
3391   }
3392 }
3393
3394 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3395 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3396 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3397 /// reverse of what x86 shuffles want.
3398 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3399                         bool Commuted = false) {
3400   if (!HasAVX && VT.getSizeInBits() == 256)
3401     return false;
3402
3403   unsigned NumElems = VT.getVectorNumElements();
3404   unsigned NumLanes = VT.getSizeInBits()/128;
3405   unsigned NumLaneElems = NumElems/NumLanes;
3406
3407   if (NumLaneElems != 2 && NumLaneElems != 4)
3408     return false;
3409
3410   // VSHUFPSY divides the resulting vector into 4 chunks.
3411   // The sources are also splitted into 4 chunks, and each destination
3412   // chunk must come from a different source chunk.
3413   //
3414   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3415   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3416   //
3417   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3418   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3419   //
3420   // VSHUFPDY 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 =>      X3       X2       X1       X0
3425   //  SRC2 =>      Y3       Y2       Y1       Y0
3426   //
3427   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3428   //
3429   unsigned HalfLaneElems = NumLaneElems/2;
3430   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3431     for (unsigned i = 0; i != NumLaneElems; ++i) {
3432       int Idx = Mask[i+l];
3433       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3434       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3435         return false;
3436       // For VSHUFPSY, the mask of the second half must be the same as the
3437       // first but with the appropriate offsets. This works in the same way as
3438       // VPERMILPS works with masks.
3439       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3440         continue;
3441       if (!isUndefOrEqual(Idx, Mask[i]+l))
3442         return false;
3443     }
3444   }
3445
3446   return true;
3447 }
3448
3449 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3450 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3451 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3452   if (!VT.is128BitVector())
3453     return false;
3454
3455   unsigned NumElems = VT.getVectorNumElements();
3456
3457   if (NumElems != 4)
3458     return false;
3459
3460   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3461   return isUndefOrEqual(Mask[0], 6) &&
3462          isUndefOrEqual(Mask[1], 7) &&
3463          isUndefOrEqual(Mask[2], 2) &&
3464          isUndefOrEqual(Mask[3], 3);
3465 }
3466
3467 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3468 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3469 /// <2, 3, 2, 3>
3470 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3471   if (!VT.is128BitVector())
3472     return false;
3473
3474   unsigned NumElems = VT.getVectorNumElements();
3475
3476   if (NumElems != 4)
3477     return false;
3478
3479   return isUndefOrEqual(Mask[0], 2) &&
3480          isUndefOrEqual(Mask[1], 3) &&
3481          isUndefOrEqual(Mask[2], 2) &&
3482          isUndefOrEqual(Mask[3], 3);
3483 }
3484
3485 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3486 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3487 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3488   if (!VT.is128BitVector())
3489     return false;
3490
3491   unsigned NumElems = VT.getVectorNumElements();
3492
3493   if (NumElems != 2 && NumElems != 4)
3494     return false;
3495
3496   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3497     if (!isUndefOrEqual(Mask[i], i + NumElems))
3498       return false;
3499
3500   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3501     if (!isUndefOrEqual(Mask[i], i))
3502       return false;
3503
3504   return true;
3505 }
3506
3507 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3508 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3509 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3510   if (!VT.is128BitVector())
3511     return false;
3512
3513   unsigned NumElems = VT.getVectorNumElements();
3514
3515   if (NumElems != 2 && NumElems != 4)
3516     return false;
3517
3518   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3519     if (!isUndefOrEqual(Mask[i], i))
3520       return false;
3521
3522   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3523     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3524       return false;
3525
3526   return true;
3527 }
3528
3529 //
3530 // Some special combinations that can be optimized.
3531 //
3532 static
3533 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3534                                SelectionDAG &DAG) {
3535   EVT VT = SVOp->getValueType(0);
3536   DebugLoc dl = SVOp->getDebugLoc();
3537
3538   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3539     return SDValue();
3540
3541   ArrayRef<int> Mask = SVOp->getMask();
3542
3543   // These are the special masks that may be optimized.
3544   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3545   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3546   bool MatchEvenMask = true;
3547   bool MatchOddMask  = true;
3548   for (int i=0; i<8; ++i) {
3549     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3550       MatchEvenMask = false;
3551     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3552       MatchOddMask = false;
3553   }
3554
3555   if (!MatchEvenMask && !MatchOddMask)
3556     return SDValue();
3557
3558   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3559
3560   SDValue Op0 = SVOp->getOperand(0);
3561   SDValue Op1 = SVOp->getOperand(1);
3562
3563   if (MatchEvenMask) {
3564     // Shift the second operand right to 32 bits.
3565     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3566     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3567   } else {
3568     // Shift the first operand left to 32 bits.
3569     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3570     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3571   }
3572   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3573   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3574 }
3575
3576 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3577 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3578 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3579                          bool HasAVX2, bool V2IsSplat = false) {
3580   unsigned NumElts = VT.getVectorNumElements();
3581
3582   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3583          "Unsupported vector type for unpckh");
3584
3585   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3586       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3587     return false;
3588
3589   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3590   // independently on 128-bit lanes.
3591   unsigned NumLanes = VT.getSizeInBits()/128;
3592   unsigned NumLaneElts = NumElts/NumLanes;
3593
3594   for (unsigned l = 0; l != NumLanes; ++l) {
3595     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3596          i != (l+1)*NumLaneElts;
3597          i += 2, ++j) {
3598       int BitI  = Mask[i];
3599       int BitI1 = Mask[i+1];
3600       if (!isUndefOrEqual(BitI, j))
3601         return false;
3602       if (V2IsSplat) {
3603         if (!isUndefOrEqual(BitI1, NumElts))
3604           return false;
3605       } else {
3606         if (!isUndefOrEqual(BitI1, j + NumElts))
3607           return false;
3608       }
3609     }
3610   }
3611
3612   return true;
3613 }
3614
3615 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3616 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3617 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3618                          bool HasAVX2, bool V2IsSplat = false) {
3619   unsigned NumElts = VT.getVectorNumElements();
3620
3621   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3622          "Unsupported vector type for unpckh");
3623
3624   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3625       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3626     return false;
3627
3628   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3629   // independently on 128-bit lanes.
3630   unsigned NumLanes = VT.getSizeInBits()/128;
3631   unsigned NumLaneElts = NumElts/NumLanes;
3632
3633   for (unsigned l = 0; l != NumLanes; ++l) {
3634     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3635          i != (l+1)*NumLaneElts; i += 2, ++j) {
3636       int BitI  = Mask[i];
3637       int BitI1 = Mask[i+1];
3638       if (!isUndefOrEqual(BitI, j))
3639         return false;
3640       if (V2IsSplat) {
3641         if (isUndefOrEqual(BitI1, NumElts))
3642           return false;
3643       } else {
3644         if (!isUndefOrEqual(BitI1, j+NumElts))
3645           return false;
3646       }
3647     }
3648   }
3649   return true;
3650 }
3651
3652 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3653 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3654 /// <0, 0, 1, 1>
3655 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3656                                   bool HasAVX2) {
3657   unsigned NumElts = VT.getVectorNumElements();
3658
3659   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3660          "Unsupported vector type for unpckh");
3661
3662   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3663       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3664     return false;
3665
3666   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3667   // FIXME: Need a better way to get rid of this, there's no latency difference
3668   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3669   // the former later. We should also remove the "_undef" special mask.
3670   if (NumElts == 4 && VT.getSizeInBits() == 256)
3671     return false;
3672
3673   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3674   // independently on 128-bit lanes.
3675   unsigned NumLanes = VT.getSizeInBits()/128;
3676   unsigned NumLaneElts = NumElts/NumLanes;
3677
3678   for (unsigned l = 0; l != NumLanes; ++l) {
3679     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3680          i != (l+1)*NumLaneElts;
3681          i += 2, ++j) {
3682       int BitI  = Mask[i];
3683       int BitI1 = Mask[i+1];
3684
3685       if (!isUndefOrEqual(BitI, j))
3686         return false;
3687       if (!isUndefOrEqual(BitI1, j))
3688         return false;
3689     }
3690   }
3691
3692   return true;
3693 }
3694
3695 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3696 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3697 /// <2, 2, 3, 3>
3698 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3699   unsigned NumElts = VT.getVectorNumElements();
3700
3701   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3702          "Unsupported vector type for unpckh");
3703
3704   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3705       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3706     return false;
3707
3708   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3709   // independently on 128-bit lanes.
3710   unsigned NumLanes = VT.getSizeInBits()/128;
3711   unsigned NumLaneElts = NumElts/NumLanes;
3712
3713   for (unsigned l = 0; l != NumLanes; ++l) {
3714     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3715          i != (l+1)*NumLaneElts; i += 2, ++j) {
3716       int BitI  = Mask[i];
3717       int BitI1 = Mask[i+1];
3718       if (!isUndefOrEqual(BitI, j))
3719         return false;
3720       if (!isUndefOrEqual(BitI1, j))
3721         return false;
3722     }
3723   }
3724   return true;
3725 }
3726
3727 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3728 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3729 /// MOVSD, and MOVD, i.e. setting the lowest element.
3730 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3731   if (VT.getVectorElementType().getSizeInBits() < 32)
3732     return false;
3733   if (!VT.is128BitVector())
3734     return false;
3735
3736   unsigned NumElts = VT.getVectorNumElements();
3737
3738   if (!isUndefOrEqual(Mask[0], NumElts))
3739     return false;
3740
3741   for (unsigned i = 1; i != NumElts; ++i)
3742     if (!isUndefOrEqual(Mask[i], i))
3743       return false;
3744
3745   return true;
3746 }
3747
3748 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3749 /// as permutations between 128-bit chunks or halves. As an example: this
3750 /// shuffle bellow:
3751 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3752 /// The first half comes from the second half of V1 and the second half from the
3753 /// the second half of V2.
3754 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3755   if (!HasAVX || !VT.is256BitVector())
3756     return false;
3757
3758   // The shuffle result is divided into half A and half B. In total the two
3759   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3760   // B must come from C, D, E or F.
3761   unsigned HalfSize = VT.getVectorNumElements()/2;
3762   bool MatchA = false, MatchB = false;
3763
3764   // Check if A comes from one of C, D, E, F.
3765   for (unsigned Half = 0; Half != 4; ++Half) {
3766     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3767       MatchA = true;
3768       break;
3769     }
3770   }
3771
3772   // Check if B comes from one of C, D, E, F.
3773   for (unsigned Half = 0; Half != 4; ++Half) {
3774     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3775       MatchB = true;
3776       break;
3777     }
3778   }
3779
3780   return MatchA && MatchB;
3781 }
3782
3783 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3784 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3785 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3786   EVT VT = SVOp->getValueType(0);
3787
3788   unsigned HalfSize = VT.getVectorNumElements()/2;
3789
3790   unsigned FstHalf = 0, SndHalf = 0;
3791   for (unsigned i = 0; i < HalfSize; ++i) {
3792     if (SVOp->getMaskElt(i) > 0) {
3793       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3794       break;
3795     }
3796   }
3797   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3798     if (SVOp->getMaskElt(i) > 0) {
3799       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3800       break;
3801     }
3802   }
3803
3804   return (FstHalf | (SndHalf << 4));
3805 }
3806
3807 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3809 /// Note that VPERMIL mask matching is different depending whether theunderlying
3810 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3811 /// to the same elements of the low, but to the higher half of the source.
3812 /// In VPERMILPD the two lanes could be shuffled independently of each other
3813 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3814 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3815   if (!HasAVX)
3816     return false;
3817
3818   unsigned NumElts = VT.getVectorNumElements();
3819   // Only match 256-bit with 32/64-bit types
3820   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3821     return false;
3822
3823   unsigned NumLanes = VT.getSizeInBits()/128;
3824   unsigned LaneSize = NumElts/NumLanes;
3825   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3826     for (unsigned i = 0; i != LaneSize; ++i) {
3827       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3828         return false;
3829       if (NumElts != 8 || l == 0)
3830         continue;
3831       // VPERMILPS handling
3832       if (Mask[i] < 0)
3833         continue;
3834       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3835         return false;
3836     }
3837   }
3838
3839   return true;
3840 }
3841
3842 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3843 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3844 /// element of vector 2 and the other elements to come from vector 1 in order.
3845 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3846                                bool V2IsSplat = false, bool V2IsUndef = false) {
3847   if (!VT.is128BitVector())
3848     return false;
3849
3850   unsigned NumOps = VT.getVectorNumElements();
3851   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3852     return false;
3853
3854   if (!isUndefOrEqual(Mask[0], 0))
3855     return false;
3856
3857   for (unsigned i = 1; i != NumOps; ++i)
3858     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3859           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3860           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3861       return false;
3862
3863   return true;
3864 }
3865
3866 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3868 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3869 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3870                            const X86Subtarget *Subtarget) {
3871   if (!Subtarget->hasSSE3())
3872     return false;
3873
3874   unsigned NumElems = VT.getVectorNumElements();
3875
3876   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3877       (VT.getSizeInBits() == 256 && NumElems != 8))
3878     return false;
3879
3880   // "i+1" is the value the indexed mask element must have
3881   for (unsigned i = 0; i != NumElems; i += 2)
3882     if (!isUndefOrEqual(Mask[i], i+1) ||
3883         !isUndefOrEqual(Mask[i+1], i+1))
3884       return false;
3885
3886   return true;
3887 }
3888
3889 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3890 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3891 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3892 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3893                            const X86Subtarget *Subtarget) {
3894   if (!Subtarget->hasSSE3())
3895     return false;
3896
3897   unsigned NumElems = VT.getVectorNumElements();
3898
3899   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3900       (VT.getSizeInBits() == 256 && NumElems != 8))
3901     return false;
3902
3903   // "i" is the value the indexed mask element must have
3904   for (unsigned i = 0; i != NumElems; i += 2)
3905     if (!isUndefOrEqual(Mask[i], i) ||
3906         !isUndefOrEqual(Mask[i+1], i))
3907       return false;
3908
3909   return true;
3910 }
3911
3912 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to 256-bit
3914 /// version of MOVDDUP.
3915 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3916   if (!HasAVX || !VT.is256BitVector())
3917     return false;
3918
3919   unsigned NumElts = VT.getVectorNumElements();
3920   if (NumElts != 4)
3921     return false;
3922
3923   for (unsigned i = 0; i != NumElts/2; ++i)
3924     if (!isUndefOrEqual(Mask[i], 0))
3925       return false;
3926   for (unsigned i = NumElts/2; i != NumElts; ++i)
3927     if (!isUndefOrEqual(Mask[i], NumElts/2))
3928       return false;
3929   return true;
3930 }
3931
3932 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to 128-bit
3934 /// version of MOVDDUP.
3935 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3936   if (!VT.is128BitVector())
3937     return false;
3938
3939   unsigned e = VT.getVectorNumElements() / 2;
3940   for (unsigned i = 0; i != e; ++i)
3941     if (!isUndefOrEqual(Mask[i], i))
3942       return false;
3943   for (unsigned i = 0; i != e; ++i)
3944     if (!isUndefOrEqual(Mask[e+i], i))
3945       return false;
3946   return true;
3947 }
3948
3949 /// isVEXTRACTF128Index - Return true if the specified
3950 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3951 /// suitable for input to VEXTRACTF128.
3952 bool X86::isVEXTRACTF128Index(SDNode *N) {
3953   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3954     return false;
3955
3956   // The index should be aligned on a 128-bit boundary.
3957   uint64_t Index =
3958     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3959
3960   unsigned VL = N->getValueType(0).getVectorNumElements();
3961   unsigned VBits = N->getValueType(0).getSizeInBits();
3962   unsigned ElSize = VBits / VL;
3963   bool Result = (Index * ElSize) % 128 == 0;
3964
3965   return Result;
3966 }
3967
3968 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3969 /// operand specifies a subvector insert that is suitable for input to
3970 /// VINSERTF128.
3971 bool X86::isVINSERTF128Index(SDNode *N) {
3972   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3973     return false;
3974
3975   // The index should be aligned on a 128-bit boundary.
3976   uint64_t Index =
3977     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3978
3979   unsigned VL = N->getValueType(0).getVectorNumElements();
3980   unsigned VBits = N->getValueType(0).getSizeInBits();
3981   unsigned ElSize = VBits / VL;
3982   bool Result = (Index * ElSize) % 128 == 0;
3983
3984   return Result;
3985 }
3986
3987 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3988 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3989 /// Handles 128-bit and 256-bit.
3990 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3991   EVT VT = N->getValueType(0);
3992
3993   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3994          "Unsupported vector type for PSHUF/SHUFP");
3995
3996   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3997   // independently on 128-bit lanes.
3998   unsigned NumElts = VT.getVectorNumElements();
3999   unsigned NumLanes = VT.getSizeInBits()/128;
4000   unsigned NumLaneElts = NumElts/NumLanes;
4001
4002   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4003          "Only supports 2 or 4 elements per lane");
4004
4005   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4006   unsigned Mask = 0;
4007   for (unsigned i = 0; i != NumElts; ++i) {
4008     int Elt = N->getMaskElt(i);
4009     if (Elt < 0) continue;
4010     Elt &= NumLaneElts - 1;
4011     unsigned ShAmt = (i << Shift) % 8;
4012     Mask |= Elt << ShAmt;
4013   }
4014
4015   return Mask;
4016 }
4017
4018 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4019 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4020 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4021   EVT VT = N->getValueType(0);
4022
4023   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4024          "Unsupported vector type for PSHUFHW");
4025
4026   unsigned NumElts = VT.getVectorNumElements();
4027
4028   unsigned Mask = 0;
4029   for (unsigned l = 0; l != NumElts; l += 8) {
4030     // 8 nodes per lane, but we only care about the last 4.
4031     for (unsigned i = 0; i < 4; ++i) {
4032       int Elt = N->getMaskElt(l+i+4);
4033       if (Elt < 0) continue;
4034       Elt &= 0x3; // only 2-bits.
4035       Mask |= Elt << (i * 2);
4036     }
4037   }
4038
4039   return Mask;
4040 }
4041
4042 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4043 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4044 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4045   EVT VT = N->getValueType(0);
4046
4047   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4048          "Unsupported vector type for PSHUFHW");
4049
4050   unsigned NumElts = VT.getVectorNumElements();
4051
4052   unsigned Mask = 0;
4053   for (unsigned l = 0; l != NumElts; l += 8) {
4054     // 8 nodes per lane, but we only care about the first 4.
4055     for (unsigned i = 0; i < 4; ++i) {
4056       int Elt = N->getMaskElt(l+i);
4057       if (Elt < 0) continue;
4058       Elt &= 0x3; // only 2-bits
4059       Mask |= Elt << (i * 2);
4060     }
4061   }
4062
4063   return Mask;
4064 }
4065
4066 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4067 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4068 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4069   EVT VT = SVOp->getValueType(0);
4070   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4071
4072   unsigned NumElts = VT.getVectorNumElements();
4073   unsigned NumLanes = VT.getSizeInBits()/128;
4074   unsigned NumLaneElts = NumElts/NumLanes;
4075
4076   int Val = 0;
4077   unsigned i;
4078   for (i = 0; i != NumElts; ++i) {
4079     Val = SVOp->getMaskElt(i);
4080     if (Val >= 0)
4081       break;
4082   }
4083   if (Val >= (int)NumElts)
4084     Val -= NumElts - NumLaneElts;
4085
4086   assert(Val - i > 0 && "PALIGNR imm should be positive");
4087   return (Val - i) * EltSize;
4088 }
4089
4090 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4091 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4092 /// instructions.
4093 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4094   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4095     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4096
4097   uint64_t Index =
4098     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4099
4100   EVT VecVT = N->getOperand(0).getValueType();
4101   EVT ElVT = VecVT.getVectorElementType();
4102
4103   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4104   return Index / NumElemsPerChunk;
4105 }
4106
4107 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4108 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4109 /// instructions.
4110 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4111   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4112     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4113
4114   uint64_t Index =
4115     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4116
4117   EVT VecVT = N->getValueType(0);
4118   EVT ElVT = VecVT.getVectorElementType();
4119
4120   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4121   return Index / NumElemsPerChunk;
4122 }
4123
4124 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4125 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4126 /// Handles 256-bit.
4127 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4128   EVT VT = N->getValueType(0);
4129
4130   unsigned NumElts = VT.getVectorNumElements();
4131
4132   assert((VT.is256BitVector() && NumElts == 4) &&
4133          "Unsupported vector type for VPERMQ/VPERMPD");
4134
4135   unsigned Mask = 0;
4136   for (unsigned i = 0; i != NumElts; ++i) {
4137     int Elt = N->getMaskElt(i);
4138     if (Elt < 0)
4139       continue;
4140     Mask |= Elt << (i*2);
4141   }
4142
4143   return Mask;
4144 }
4145 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4146 /// constant +0.0.
4147 bool X86::isZeroNode(SDValue Elt) {
4148   return ((isa<ConstantSDNode>(Elt) &&
4149            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4150           (isa<ConstantFPSDNode>(Elt) &&
4151            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4152 }
4153
4154 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4155 /// their permute mask.
4156 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4157                                     SelectionDAG &DAG) {
4158   EVT VT = SVOp->getValueType(0);
4159   unsigned NumElems = VT.getVectorNumElements();
4160   SmallVector<int, 8> MaskVec;
4161
4162   for (unsigned i = 0; i != NumElems; ++i) {
4163     int Idx = SVOp->getMaskElt(i);
4164     if (Idx >= 0) {
4165       if (Idx < (int)NumElems)
4166         Idx += NumElems;
4167       else
4168         Idx -= NumElems;
4169     }
4170     MaskVec.push_back(Idx);
4171   }
4172   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4173                               SVOp->getOperand(0), &MaskVec[0]);
4174 }
4175
4176 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4177 /// match movhlps. The lower half elements should come from upper half of
4178 /// V1 (and in order), and the upper half elements should come from the upper
4179 /// half of V2 (and in order).
4180 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4181   if (!VT.is128BitVector())
4182     return false;
4183   if (VT.getVectorNumElements() != 4)
4184     return false;
4185   for (unsigned i = 0, e = 2; i != e; ++i)
4186     if (!isUndefOrEqual(Mask[i], i+2))
4187       return false;
4188   for (unsigned i = 2; i != 4; ++i)
4189     if (!isUndefOrEqual(Mask[i], i+4))
4190       return false;
4191   return true;
4192 }
4193
4194 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4195 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4196 /// required.
4197 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4198   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4199     return false;
4200   N = N->getOperand(0).getNode();
4201   if (!ISD::isNON_EXTLoad(N))
4202     return false;
4203   if (LD)
4204     *LD = cast<LoadSDNode>(N);
4205   return true;
4206 }
4207
4208 // Test whether the given value is a vector value which will be legalized
4209 // into a load.
4210 static bool WillBeConstantPoolLoad(SDNode *N) {
4211   if (N->getOpcode() != ISD::BUILD_VECTOR)
4212     return false;
4213
4214   // Check for any non-constant elements.
4215   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4216     switch (N->getOperand(i).getNode()->getOpcode()) {
4217     case ISD::UNDEF:
4218     case ISD::ConstantFP:
4219     case ISD::Constant:
4220       break;
4221     default:
4222       return false;
4223     }
4224
4225   // Vectors of all-zeros and all-ones are materialized with special
4226   // instructions rather than being loaded.
4227   return !ISD::isBuildVectorAllZeros(N) &&
4228          !ISD::isBuildVectorAllOnes(N);
4229 }
4230
4231 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4232 /// match movlp{s|d}. The lower half elements should come from lower half of
4233 /// V1 (and in order), and the upper half elements should come from the upper
4234 /// half of V2 (and in order). And since V1 will become the source of the
4235 /// MOVLP, it must be either a vector load or a scalar load to vector.
4236 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4237                                ArrayRef<int> Mask, EVT VT) {
4238   if (!VT.is128BitVector())
4239     return false;
4240
4241   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4242     return false;
4243   // Is V2 is a vector load, don't do this transformation. We will try to use
4244   // load folding shufps op.
4245   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4246     return false;
4247
4248   unsigned NumElems = VT.getVectorNumElements();
4249
4250   if (NumElems != 2 && NumElems != 4)
4251     return false;
4252   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4253     if (!isUndefOrEqual(Mask[i], i))
4254       return false;
4255   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4256     if (!isUndefOrEqual(Mask[i], i+NumElems))
4257       return false;
4258   return true;
4259 }
4260
4261 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4262 /// all the same.
4263 static bool isSplatVector(SDNode *N) {
4264   if (N->getOpcode() != ISD::BUILD_VECTOR)
4265     return false;
4266
4267   SDValue SplatValue = N->getOperand(0);
4268   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4269     if (N->getOperand(i) != SplatValue)
4270       return false;
4271   return true;
4272 }
4273
4274 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4275 /// to an zero vector.
4276 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4277 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4278   SDValue V1 = N->getOperand(0);
4279   SDValue V2 = N->getOperand(1);
4280   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4281   for (unsigned i = 0; i != NumElems; ++i) {
4282     int Idx = N->getMaskElt(i);
4283     if (Idx >= (int)NumElems) {
4284       unsigned Opc = V2.getOpcode();
4285       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4286         continue;
4287       if (Opc != ISD::BUILD_VECTOR ||
4288           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4289         return false;
4290     } else if (Idx >= 0) {
4291       unsigned Opc = V1.getOpcode();
4292       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4293         continue;
4294       if (Opc != ISD::BUILD_VECTOR ||
4295           !X86::isZeroNode(V1.getOperand(Idx)))
4296         return false;
4297     }
4298   }
4299   return true;
4300 }
4301
4302 /// getZeroVector - Returns a vector of specified type with all zero elements.
4303 ///
4304 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4305                              SelectionDAG &DAG, DebugLoc dl) {
4306   assert(VT.isVector() && "Expected a vector type");
4307   unsigned Size = VT.getSizeInBits();
4308
4309   // Always build SSE zero vectors as <4 x i32> bitcasted
4310   // to their dest type. This ensures they get CSE'd.
4311   SDValue Vec;
4312   if (Size == 128) {  // SSE
4313     if (Subtarget->hasSSE2()) {  // SSE2
4314       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4315       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4316     } else { // SSE1
4317       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4318       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4319     }
4320   } else if (Size == 256) { // AVX
4321     if (Subtarget->hasAVX2()) { // AVX2
4322       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4323       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4324       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4325     } else {
4326       // 256-bit logic and arithmetic instructions in AVX are all
4327       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4328       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4329       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4330       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4331     }
4332   } else
4333     llvm_unreachable("Unexpected vector type");
4334
4335   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4336 }
4337
4338 /// getOnesVector - Returns a vector of specified type with all bits set.
4339 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4340 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4341 /// Then bitcast to their original type, ensuring they get CSE'd.
4342 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4343                              DebugLoc dl) {
4344   assert(VT.isVector() && "Expected a vector type");
4345   unsigned Size = VT.getSizeInBits();
4346
4347   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4348   SDValue Vec;
4349   if (Size == 256) {
4350     if (HasAVX2) { // AVX2
4351       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4352       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4353     } else { // AVX
4354       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4355       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4356     }
4357   } else if (Size == 128) {
4358     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4359   } else
4360     llvm_unreachable("Unexpected vector type");
4361
4362   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4363 }
4364
4365 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4366 /// that point to V2 points to its first element.
4367 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4368   for (unsigned i = 0; i != NumElems; ++i) {
4369     if (Mask[i] > (int)NumElems) {
4370       Mask[i] = NumElems;
4371     }
4372   }
4373 }
4374
4375 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4376 /// operation of specified width.
4377 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4378                        SDValue V2) {
4379   unsigned NumElems = VT.getVectorNumElements();
4380   SmallVector<int, 8> Mask;
4381   Mask.push_back(NumElems);
4382   for (unsigned i = 1; i != NumElems; ++i)
4383     Mask.push_back(i);
4384   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4385 }
4386
4387 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4388 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4389                           SDValue V2) {
4390   unsigned NumElems = VT.getVectorNumElements();
4391   SmallVector<int, 8> Mask;
4392   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4393     Mask.push_back(i);
4394     Mask.push_back(i + NumElems);
4395   }
4396   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4397 }
4398
4399 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4400 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4401                           SDValue V2) {
4402   unsigned NumElems = VT.getVectorNumElements();
4403   SmallVector<int, 8> Mask;
4404   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4405     Mask.push_back(i + Half);
4406     Mask.push_back(i + NumElems + Half);
4407   }
4408   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4409 }
4410
4411 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4412 // a generic shuffle instruction because the target has no such instructions.
4413 // Generate shuffles which repeat i16 and i8 several times until they can be
4414 // represented by v4f32 and then be manipulated by target suported shuffles.
4415 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4416   EVT VT = V.getValueType();
4417   int NumElems = VT.getVectorNumElements();
4418   DebugLoc dl = V.getDebugLoc();
4419
4420   while (NumElems > 4) {
4421     if (EltNo < NumElems/2) {
4422       V = getUnpackl(DAG, dl, VT, V, V);
4423     } else {
4424       V = getUnpackh(DAG, dl, VT, V, V);
4425       EltNo -= NumElems/2;
4426     }
4427     NumElems >>= 1;
4428   }
4429   return V;
4430 }
4431
4432 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4433 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4434   EVT VT = V.getValueType();
4435   DebugLoc dl = V.getDebugLoc();
4436   unsigned Size = VT.getSizeInBits();
4437
4438   if (Size == 128) {
4439     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4440     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4441     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4442                              &SplatMask[0]);
4443   } else if (Size == 256) {
4444     // To use VPERMILPS to splat scalars, the second half of indicies must
4445     // refer to the higher part, which is a duplication of the lower one,
4446     // because VPERMILPS can only handle in-lane permutations.
4447     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4448                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4449
4450     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4451     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4452                              &SplatMask[0]);
4453   } else
4454     llvm_unreachable("Vector size not supported");
4455
4456   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4457 }
4458
4459 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4460 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4461   EVT SrcVT = SV->getValueType(0);
4462   SDValue V1 = SV->getOperand(0);
4463   DebugLoc dl = SV->getDebugLoc();
4464
4465   int EltNo = SV->getSplatIndex();
4466   int NumElems = SrcVT.getVectorNumElements();
4467   unsigned Size = SrcVT.getSizeInBits();
4468
4469   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4470           "Unknown how to promote splat for type");
4471
4472   // Extract the 128-bit part containing the splat element and update
4473   // the splat element index when it refers to the higher register.
4474   if (Size == 256) {
4475     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4476     if (EltNo >= NumElems/2)
4477       EltNo -= NumElems/2;
4478   }
4479
4480   // All i16 and i8 vector types can't be used directly by a generic shuffle
4481   // instruction because the target has no such instruction. Generate shuffles
4482   // which repeat i16 and i8 several times until they fit in i32, and then can
4483   // be manipulated by target suported shuffles.
4484   EVT EltVT = SrcVT.getVectorElementType();
4485   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4486     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4487
4488   // Recreate the 256-bit vector and place the same 128-bit vector
4489   // into the low and high part. This is necessary because we want
4490   // to use VPERM* to shuffle the vectors
4491   if (Size == 256) {
4492     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4493   }
4494
4495   return getLegalSplat(DAG, V1, EltNo);
4496 }
4497
4498 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4499 /// vector of zero or undef vector.  This produces a shuffle where the low
4500 /// element of V2 is swizzled into the zero/undef vector, landing at element
4501 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4502 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4503                                            bool IsZero,
4504                                            const X86Subtarget *Subtarget,
4505                                            SelectionDAG &DAG) {
4506   EVT VT = V2.getValueType();
4507   SDValue V1 = IsZero
4508     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4509   unsigned NumElems = VT.getVectorNumElements();
4510   SmallVector<int, 16> MaskVec;
4511   for (unsigned i = 0; i != NumElems; ++i)
4512     // If this is the insertion idx, put the low elt of V2 here.
4513     MaskVec.push_back(i == Idx ? NumElems : i);
4514   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4515 }
4516
4517 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4518 /// target specific opcode. Returns true if the Mask could be calculated.
4519 /// Sets IsUnary to true if only uses one source.
4520 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4521                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4522   unsigned NumElems = VT.getVectorNumElements();
4523   SDValue ImmN;
4524
4525   IsUnary = false;
4526   switch(N->getOpcode()) {
4527   case X86ISD::SHUFP:
4528     ImmN = N->getOperand(N->getNumOperands()-1);
4529     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4530     break;
4531   case X86ISD::UNPCKH:
4532     DecodeUNPCKHMask(VT, Mask);
4533     break;
4534   case X86ISD::UNPCKL:
4535     DecodeUNPCKLMask(VT, Mask);
4536     break;
4537   case X86ISD::MOVHLPS:
4538     DecodeMOVHLPSMask(NumElems, Mask);
4539     break;
4540   case X86ISD::MOVLHPS:
4541     DecodeMOVLHPSMask(NumElems, Mask);
4542     break;
4543   case X86ISD::PSHUFD:
4544   case X86ISD::VPERMILP:
4545     ImmN = N->getOperand(N->getNumOperands()-1);
4546     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4547     IsUnary = true;
4548     break;
4549   case X86ISD::PSHUFHW:
4550     ImmN = N->getOperand(N->getNumOperands()-1);
4551     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4552     IsUnary = true;
4553     break;
4554   case X86ISD::PSHUFLW:
4555     ImmN = N->getOperand(N->getNumOperands()-1);
4556     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4557     IsUnary = true;
4558     break;
4559   case X86ISD::VPERMI:
4560     ImmN = N->getOperand(N->getNumOperands()-1);
4561     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4562     IsUnary = true;
4563     break;
4564   case X86ISD::MOVSS:
4565   case X86ISD::MOVSD: {
4566     // The index 0 always comes from the first element of the second source,
4567     // this is why MOVSS and MOVSD are used in the first place. The other
4568     // elements come from the other positions of the first source vector
4569     Mask.push_back(NumElems);
4570     for (unsigned i = 1; i != NumElems; ++i) {
4571       Mask.push_back(i);
4572     }
4573     break;
4574   }
4575   case X86ISD::VPERM2X128:
4576     ImmN = N->getOperand(N->getNumOperands()-1);
4577     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4578     if (Mask.empty()) return false;
4579     break;
4580   case X86ISD::MOVDDUP:
4581   case X86ISD::MOVLHPD:
4582   case X86ISD::MOVLPD:
4583   case X86ISD::MOVLPS:
4584   case X86ISD::MOVSHDUP:
4585   case X86ISD::MOVSLDUP:
4586   case X86ISD::PALIGN:
4587     // Not yet implemented
4588     return false;
4589   default: llvm_unreachable("unknown target shuffle node");
4590   }
4591
4592   return true;
4593 }
4594
4595 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4596 /// element of the result of the vector shuffle.
4597 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4598                                    unsigned Depth) {
4599   if (Depth == 6)
4600     return SDValue();  // Limit search depth.
4601
4602   SDValue V = SDValue(N, 0);
4603   EVT VT = V.getValueType();
4604   unsigned Opcode = V.getOpcode();
4605
4606   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4607   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4608     int Elt = SV->getMaskElt(Index);
4609
4610     if (Elt < 0)
4611       return DAG.getUNDEF(VT.getVectorElementType());
4612
4613     unsigned NumElems = VT.getVectorNumElements();
4614     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4615                                          : SV->getOperand(1);
4616     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4617   }
4618
4619   // Recurse into target specific vector shuffles to find scalars.
4620   if (isTargetShuffle(Opcode)) {
4621     MVT ShufVT = V.getValueType().getSimpleVT();
4622     unsigned NumElems = ShufVT.getVectorNumElements();
4623     SmallVector<int, 16> ShuffleMask;
4624     SDValue ImmN;
4625     bool IsUnary;
4626
4627     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4628       return SDValue();
4629
4630     int Elt = ShuffleMask[Index];
4631     if (Elt < 0)
4632       return DAG.getUNDEF(ShufVT.getVectorElementType());
4633
4634     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4635                                          : N->getOperand(1);
4636     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4637                                Depth+1);
4638   }
4639
4640   // Actual nodes that may contain scalar elements
4641   if (Opcode == ISD::BITCAST) {
4642     V = V.getOperand(0);
4643     EVT SrcVT = V.getValueType();
4644     unsigned NumElems = VT.getVectorNumElements();
4645
4646     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4647       return SDValue();
4648   }
4649
4650   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4651     return (Index == 0) ? V.getOperand(0)
4652                         : DAG.getUNDEF(VT.getVectorElementType());
4653
4654   if (V.getOpcode() == ISD::BUILD_VECTOR)
4655     return V.getOperand(Index);
4656
4657   return SDValue();
4658 }
4659
4660 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4661 /// shuffle operation which come from a consecutively from a zero. The
4662 /// search can start in two different directions, from left or right.
4663 static
4664 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4665                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4666   unsigned i;
4667   for (i = 0; i != NumElems; ++i) {
4668     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4669     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4670     if (!(Elt.getNode() &&
4671          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4672       break;
4673   }
4674
4675   return i;
4676 }
4677
4678 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4679 /// correspond consecutively to elements from one of the vector operands,
4680 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4681 static
4682 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4683                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4684                               unsigned NumElems, unsigned &OpNum) {
4685   bool SeenV1 = false;
4686   bool SeenV2 = false;
4687
4688   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4689     int Idx = SVOp->getMaskElt(i);
4690     // Ignore undef indicies
4691     if (Idx < 0)
4692       continue;
4693
4694     if (Idx < (int)NumElems)
4695       SeenV1 = true;
4696     else
4697       SeenV2 = true;
4698
4699     // Only accept consecutive elements from the same vector
4700     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4701       return false;
4702   }
4703
4704   OpNum = SeenV1 ? 0 : 1;
4705   return true;
4706 }
4707
4708 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4709 /// logical left shift of a vector.
4710 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4711                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4712   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4713   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4714               false /* check zeros from right */, DAG);
4715   unsigned OpSrc;
4716
4717   if (!NumZeros)
4718     return false;
4719
4720   // Considering the elements in the mask that are not consecutive zeros,
4721   // check if they consecutively come from only one of the source vectors.
4722   //
4723   //               V1 = {X, A, B, C}     0
4724   //                         \  \  \    /
4725   //   vector_shuffle V1, V2 <1, 2, 3, X>
4726   //
4727   if (!isShuffleMaskConsecutive(SVOp,
4728             0,                   // Mask Start Index
4729             NumElems-NumZeros,   // Mask End Index(exclusive)
4730             NumZeros,            // Where to start looking in the src vector
4731             NumElems,            // Number of elements in vector
4732             OpSrc))              // Which source operand ?
4733     return false;
4734
4735   isLeft = false;
4736   ShAmt = NumZeros;
4737   ShVal = SVOp->getOperand(OpSrc);
4738   return true;
4739 }
4740
4741 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4742 /// logical left shift of a vector.
4743 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4744                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4745   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4746   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4747               true /* check zeros from left */, DAG);
4748   unsigned OpSrc;
4749
4750   if (!NumZeros)
4751     return false;
4752
4753   // Considering the elements in the mask that are not consecutive zeros,
4754   // check if they consecutively come from only one of the source vectors.
4755   //
4756   //                           0    { A, B, X, X } = V2
4757   //                          / \    /  /
4758   //   vector_shuffle V1, V2 <X, X, 4, 5>
4759   //
4760   if (!isShuffleMaskConsecutive(SVOp,
4761             NumZeros,     // Mask Start Index
4762             NumElems,     // Mask End Index(exclusive)
4763             0,            // Where to start looking in the src vector
4764             NumElems,     // Number of elements in vector
4765             OpSrc))       // Which source operand ?
4766     return false;
4767
4768   isLeft = true;
4769   ShAmt = NumZeros;
4770   ShVal = SVOp->getOperand(OpSrc);
4771   return true;
4772 }
4773
4774 /// isVectorShift - Returns true if the shuffle can be implemented as a
4775 /// logical left or right shift of a vector.
4776 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4777                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4778   // Although the logic below support any bitwidth size, there are no
4779   // shift instructions which handle more than 128-bit vectors.
4780   if (!SVOp->getValueType(0).is128BitVector())
4781     return false;
4782
4783   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4784       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4785     return true;
4786
4787   return false;
4788 }
4789
4790 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4791 ///
4792 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4793                                        unsigned NumNonZero, unsigned NumZero,
4794                                        SelectionDAG &DAG,
4795                                        const X86Subtarget* Subtarget,
4796                                        const TargetLowering &TLI) {
4797   if (NumNonZero > 8)
4798     return SDValue();
4799
4800   DebugLoc dl = Op.getDebugLoc();
4801   SDValue V(0, 0);
4802   bool First = true;
4803   for (unsigned i = 0; i < 16; ++i) {
4804     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4805     if (ThisIsNonZero && First) {
4806       if (NumZero)
4807         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4808       else
4809         V = DAG.getUNDEF(MVT::v8i16);
4810       First = false;
4811     }
4812
4813     if ((i & 1) != 0) {
4814       SDValue ThisElt(0, 0), LastElt(0, 0);
4815       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4816       if (LastIsNonZero) {
4817         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4818                               MVT::i16, Op.getOperand(i-1));
4819       }
4820       if (ThisIsNonZero) {
4821         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4822         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4823                               ThisElt, DAG.getConstant(8, MVT::i8));
4824         if (LastIsNonZero)
4825           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4826       } else
4827         ThisElt = LastElt;
4828
4829       if (ThisElt.getNode())
4830         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4831                         DAG.getIntPtrConstant(i/2));
4832     }
4833   }
4834
4835   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4836 }
4837
4838 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4839 ///
4840 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4841                                      unsigned NumNonZero, unsigned NumZero,
4842                                      SelectionDAG &DAG,
4843                                      const X86Subtarget* Subtarget,
4844                                      const TargetLowering &TLI) {
4845   if (NumNonZero > 4)
4846     return SDValue();
4847
4848   DebugLoc dl = Op.getDebugLoc();
4849   SDValue V(0, 0);
4850   bool First = true;
4851   for (unsigned i = 0; i < 8; ++i) {
4852     bool isNonZero = (NonZeros & (1 << i)) != 0;
4853     if (isNonZero) {
4854       if (First) {
4855         if (NumZero)
4856           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4857         else
4858           V = DAG.getUNDEF(MVT::v8i16);
4859         First = false;
4860       }
4861       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4862                       MVT::v8i16, V, Op.getOperand(i),
4863                       DAG.getIntPtrConstant(i));
4864     }
4865   }
4866
4867   return V;
4868 }
4869
4870 /// getVShift - Return a vector logical shift node.
4871 ///
4872 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4873                          unsigned NumBits, SelectionDAG &DAG,
4874                          const TargetLowering &TLI, DebugLoc dl) {
4875   assert(VT.is128BitVector() && "Unknown type for VShift");
4876   EVT ShVT = MVT::v2i64;
4877   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4878   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4879   return DAG.getNode(ISD::BITCAST, dl, VT,
4880                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4881                              DAG.getConstant(NumBits,
4882                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4883 }
4884
4885 SDValue
4886 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4887                                           SelectionDAG &DAG) const {
4888
4889   // Check if the scalar load can be widened into a vector load. And if
4890   // the address is "base + cst" see if the cst can be "absorbed" into
4891   // the shuffle mask.
4892   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4893     SDValue Ptr = LD->getBasePtr();
4894     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4895       return SDValue();
4896     EVT PVT = LD->getValueType(0);
4897     if (PVT != MVT::i32 && PVT != MVT::f32)
4898       return SDValue();
4899
4900     int FI = -1;
4901     int64_t Offset = 0;
4902     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4903       FI = FINode->getIndex();
4904       Offset = 0;
4905     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4906                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4907       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4908       Offset = Ptr.getConstantOperandVal(1);
4909       Ptr = Ptr.getOperand(0);
4910     } else {
4911       return SDValue();
4912     }
4913
4914     // FIXME: 256-bit vector instructions don't require a strict alignment,
4915     // improve this code to support it better.
4916     unsigned RequiredAlign = VT.getSizeInBits()/8;
4917     SDValue Chain = LD->getChain();
4918     // Make sure the stack object alignment is at least 16 or 32.
4919     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4920     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4921       if (MFI->isFixedObjectIndex(FI)) {
4922         // Can't change the alignment. FIXME: It's possible to compute
4923         // the exact stack offset and reference FI + adjust offset instead.
4924         // If someone *really* cares about this. That's the way to implement it.
4925         return SDValue();
4926       } else {
4927         MFI->setObjectAlignment(FI, RequiredAlign);
4928       }
4929     }
4930
4931     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4932     // Ptr + (Offset & ~15).
4933     if (Offset < 0)
4934       return SDValue();
4935     if ((Offset % RequiredAlign) & 3)
4936       return SDValue();
4937     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4938     if (StartOffset)
4939       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4940                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4941
4942     int EltNo = (Offset - StartOffset) >> 2;
4943     unsigned NumElems = VT.getVectorNumElements();
4944
4945     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4946     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4947                              LD->getPointerInfo().getWithOffset(StartOffset),
4948                              false, false, false, 0);
4949
4950     SmallVector<int, 8> Mask;
4951     for (unsigned i = 0; i != NumElems; ++i)
4952       Mask.push_back(EltNo);
4953
4954     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4955   }
4956
4957   return SDValue();
4958 }
4959
4960 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4961 /// vector of type 'VT', see if the elements can be replaced by a single large
4962 /// load which has the same value as a build_vector whose operands are 'elts'.
4963 ///
4964 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4965 ///
4966 /// FIXME: we'd also like to handle the case where the last elements are zero
4967 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4968 /// There's even a handy isZeroNode for that purpose.
4969 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4970                                         DebugLoc &DL, SelectionDAG &DAG) {
4971   EVT EltVT = VT.getVectorElementType();
4972   unsigned NumElems = Elts.size();
4973
4974   LoadSDNode *LDBase = NULL;
4975   unsigned LastLoadedElt = -1U;
4976
4977   // For each element in the initializer, see if we've found a load or an undef.
4978   // If we don't find an initial load element, or later load elements are
4979   // non-consecutive, bail out.
4980   for (unsigned i = 0; i < NumElems; ++i) {
4981     SDValue Elt = Elts[i];
4982
4983     if (!Elt.getNode() ||
4984         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4985       return SDValue();
4986     if (!LDBase) {
4987       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4988         return SDValue();
4989       LDBase = cast<LoadSDNode>(Elt.getNode());
4990       LastLoadedElt = i;
4991       continue;
4992     }
4993     if (Elt.getOpcode() == ISD::UNDEF)
4994       continue;
4995
4996     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4997     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4998       return SDValue();
4999     LastLoadedElt = i;
5000   }
5001
5002   // If we have found an entire vector of loads and undefs, then return a large
5003   // load of the entire vector width starting at the base pointer.  If we found
5004   // consecutive loads for the low half, generate a vzext_load node.
5005   if (LastLoadedElt == NumElems - 1) {
5006     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5007       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5008                          LDBase->getPointerInfo(),
5009                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5010                          LDBase->isInvariant(), 0);
5011     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5012                        LDBase->getPointerInfo(),
5013                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5014                        LDBase->isInvariant(), LDBase->getAlignment());
5015   }
5016   if (NumElems == 4 && LastLoadedElt == 1 &&
5017       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5018     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5019     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5020     SDValue ResNode =
5021         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5022                                 LDBase->getPointerInfo(),
5023                                 LDBase->getAlignment(),
5024                                 false/*isVolatile*/, true/*ReadMem*/,
5025                                 false/*WriteMem*/);
5026
5027     // Make sure the newly-created LOAD is in the same position as LDBase in
5028     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5029     // update uses of LDBase's output chain to use the TokenFactor.
5030     if (LDBase->hasAnyUseOfValue(1)) {
5031       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5032                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5033       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5034       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5035                              SDValue(ResNode.getNode(), 1));
5036     }
5037
5038     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5039   }
5040   return SDValue();
5041 }
5042
5043 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5044 /// to generate a splat value for the following cases:
5045 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5046 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5047 /// a scalar load, or a constant.
5048 /// The VBROADCAST node is returned when a pattern is found,
5049 /// or SDValue() otherwise.
5050 SDValue
5051 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5052   if (!Subtarget->hasAVX())
5053     return SDValue();
5054
5055   EVT VT = Op.getValueType();
5056   DebugLoc dl = Op.getDebugLoc();
5057
5058   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5059          "Unsupported vector type for broadcast.");
5060
5061   SDValue Ld;
5062   bool ConstSplatVal;
5063
5064   switch (Op.getOpcode()) {
5065     default:
5066       // Unknown pattern found.
5067       return SDValue();
5068
5069     case ISD::BUILD_VECTOR: {
5070       // The BUILD_VECTOR node must be a splat.
5071       if (!isSplatVector(Op.getNode()))
5072         return SDValue();
5073
5074       Ld = Op.getOperand(0);
5075       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5076                      Ld.getOpcode() == ISD::ConstantFP);
5077
5078       // The suspected load node has several users. Make sure that all
5079       // of its users are from the BUILD_VECTOR node.
5080       // Constants may have multiple users.
5081       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5082         return SDValue();
5083       break;
5084     }
5085
5086     case ISD::VECTOR_SHUFFLE: {
5087       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5088
5089       // Shuffles must have a splat mask where the first element is
5090       // broadcasted.
5091       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5092         return SDValue();
5093
5094       SDValue Sc = Op.getOperand(0);
5095       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5096           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5097
5098         if (!Subtarget->hasAVX2())
5099           return SDValue();
5100
5101         // Use the register form of the broadcast instruction available on AVX2.
5102         if (VT.is256BitVector())
5103           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5104         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5105       }
5106
5107       Ld = Sc.getOperand(0);
5108       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5109                        Ld.getOpcode() == ISD::ConstantFP);
5110
5111       // The scalar_to_vector node and the suspected
5112       // load node must have exactly one user.
5113       // Constants may have multiple users.
5114       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5115         return SDValue();
5116       break;
5117     }
5118   }
5119
5120   bool Is256 = VT.is256BitVector();
5121
5122   // Handle the broadcasting a single constant scalar from the constant pool
5123   // into a vector. On Sandybridge it is still better to load a constant vector
5124   // from the constant pool and not to broadcast it from a scalar.
5125   if (ConstSplatVal && Subtarget->hasAVX2()) {
5126     EVT CVT = Ld.getValueType();
5127     assert(!CVT.isVector() && "Must not broadcast a vector type");
5128     unsigned ScalarSize = CVT.getSizeInBits();
5129
5130     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5131       const Constant *C = 0;
5132       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5133         C = CI->getConstantIntValue();
5134       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5135         C = CF->getConstantFPValue();
5136
5137       assert(C && "Invalid constant type");
5138
5139       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5140       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5141       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5142                        MachinePointerInfo::getConstantPool(),
5143                        false, false, false, Alignment);
5144
5145       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5146     }
5147   }
5148
5149   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5150   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5151
5152   // Handle AVX2 in-register broadcasts.
5153   if (!IsLoad && Subtarget->hasAVX2() &&
5154       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5155     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5156
5157   // The scalar source must be a normal load.
5158   if (!IsLoad)
5159     return SDValue();
5160
5161   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5162     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5163
5164   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5165   // double since there is no vbroadcastsd xmm
5166   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5167     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5168       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5169   }
5170
5171   // Unsupported broadcast.
5172   return SDValue();
5173 }
5174
5175 SDValue
5176 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5177   DebugLoc dl = Op.getDebugLoc();
5178
5179   EVT VT = Op.getValueType();
5180   EVT ExtVT = VT.getVectorElementType();
5181   unsigned NumElems = Op.getNumOperands();
5182
5183   // Vectors containing all zeros can be matched by pxor and xorps later
5184   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5185     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5186     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5187     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5188       return Op;
5189
5190     return getZeroVector(VT, Subtarget, DAG, dl);
5191   }
5192
5193   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5194   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5195   // vpcmpeqd on 256-bit vectors.
5196   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5197     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5198       return Op;
5199
5200     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5201   }
5202
5203   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5204   if (Broadcast.getNode())
5205     return Broadcast;
5206
5207   unsigned EVTBits = ExtVT.getSizeInBits();
5208
5209   unsigned NumZero  = 0;
5210   unsigned NumNonZero = 0;
5211   unsigned NonZeros = 0;
5212   bool IsAllConstants = true;
5213   SmallSet<SDValue, 8> Values;
5214   for (unsigned i = 0; i < NumElems; ++i) {
5215     SDValue Elt = Op.getOperand(i);
5216     if (Elt.getOpcode() == ISD::UNDEF)
5217       continue;
5218     Values.insert(Elt);
5219     if (Elt.getOpcode() != ISD::Constant &&
5220         Elt.getOpcode() != ISD::ConstantFP)
5221       IsAllConstants = false;
5222     if (X86::isZeroNode(Elt))
5223       NumZero++;
5224     else {
5225       NonZeros |= (1 << i);
5226       NumNonZero++;
5227     }
5228   }
5229
5230   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5231   if (NumNonZero == 0)
5232     return DAG.getUNDEF(VT);
5233
5234   // Special case for single non-zero, non-undef, element.
5235   if (NumNonZero == 1) {
5236     unsigned Idx = CountTrailingZeros_32(NonZeros);
5237     SDValue Item = Op.getOperand(Idx);
5238
5239     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5240     // the value are obviously zero, truncate the value to i32 and do the
5241     // insertion that way.  Only do this if the value is non-constant or if the
5242     // value is a constant being inserted into element 0.  It is cheaper to do
5243     // a constant pool load than it is to do a movd + shuffle.
5244     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5245         (!IsAllConstants || Idx == 0)) {
5246       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5247         // Handle SSE only.
5248         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5249         EVT VecVT = MVT::v4i32;
5250         unsigned VecElts = 4;
5251
5252         // Truncate the value (which may itself be a constant) to i32, and
5253         // convert it to a vector with movd (S2V+shuffle to zero extend).
5254         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5255         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5256         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5257
5258         // Now we have our 32-bit value zero extended in the low element of
5259         // a vector.  If Idx != 0, swizzle it into place.
5260         if (Idx != 0) {
5261           SmallVector<int, 4> Mask;
5262           Mask.push_back(Idx);
5263           for (unsigned i = 1; i != VecElts; ++i)
5264             Mask.push_back(i);
5265           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5266                                       &Mask[0]);
5267         }
5268         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5269       }
5270     }
5271
5272     // If we have a constant or non-constant insertion into the low element of
5273     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5274     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5275     // depending on what the source datatype is.
5276     if (Idx == 0) {
5277       if (NumZero == 0)
5278         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5279
5280       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5281           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5282         if (VT.is256BitVector()) {
5283           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5284           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5285                              Item, DAG.getIntPtrConstant(0));
5286         }
5287         assert(VT.is128BitVector() && "Expected an SSE value type!");
5288         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5289         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5290         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5291       }
5292
5293       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5294         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5295         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5296         if (VT.is256BitVector()) {
5297           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5298           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5299         } else {
5300           assert(VT.is128BitVector() && "Expected an SSE value type!");
5301           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5302         }
5303         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5304       }
5305     }
5306
5307     // Is it a vector logical left shift?
5308     if (NumElems == 2 && Idx == 1 &&
5309         X86::isZeroNode(Op.getOperand(0)) &&
5310         !X86::isZeroNode(Op.getOperand(1))) {
5311       unsigned NumBits = VT.getSizeInBits();
5312       return getVShift(true, VT,
5313                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5314                                    VT, Op.getOperand(1)),
5315                        NumBits/2, DAG, *this, dl);
5316     }
5317
5318     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5319       return SDValue();
5320
5321     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5322     // is a non-constant being inserted into an element other than the low one,
5323     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5324     // movd/movss) to move this into the low element, then shuffle it into
5325     // place.
5326     if (EVTBits == 32) {
5327       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5328
5329       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5330       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5331       SmallVector<int, 8> MaskVec;
5332       for (unsigned i = 0; i != NumElems; ++i)
5333         MaskVec.push_back(i == Idx ? 0 : 1);
5334       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5335     }
5336   }
5337
5338   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5339   if (Values.size() == 1) {
5340     if (EVTBits == 32) {
5341       // Instead of a shuffle like this:
5342       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5343       // Check if it's possible to issue this instead.
5344       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5345       unsigned Idx = CountTrailingZeros_32(NonZeros);
5346       SDValue Item = Op.getOperand(Idx);
5347       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5348         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5349     }
5350     return SDValue();
5351   }
5352
5353   // A vector full of immediates; various special cases are already
5354   // handled, so this is best done with a single constant-pool load.
5355   if (IsAllConstants)
5356     return SDValue();
5357
5358   // For AVX-length vectors, build the individual 128-bit pieces and use
5359   // shuffles to put them in place.
5360   if (VT.is256BitVector()) {
5361     SmallVector<SDValue, 32> V;
5362     for (unsigned i = 0; i != NumElems; ++i)
5363       V.push_back(Op.getOperand(i));
5364
5365     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5366
5367     // Build both the lower and upper subvector.
5368     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5369     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5370                                 NumElems/2);
5371
5372     // Recreate the wider vector with the lower and upper part.
5373     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5374   }
5375
5376   // Let legalizer expand 2-wide build_vectors.
5377   if (EVTBits == 64) {
5378     if (NumNonZero == 1) {
5379       // One half is zero or undef.
5380       unsigned Idx = CountTrailingZeros_32(NonZeros);
5381       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5382                                  Op.getOperand(Idx));
5383       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5384     }
5385     return SDValue();
5386   }
5387
5388   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5389   if (EVTBits == 8 && NumElems == 16) {
5390     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5391                                         Subtarget, *this);
5392     if (V.getNode()) return V;
5393   }
5394
5395   if (EVTBits == 16 && NumElems == 8) {
5396     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5397                                       Subtarget, *this);
5398     if (V.getNode()) return V;
5399   }
5400
5401   // If element VT is == 32 bits, turn it into a number of shuffles.
5402   SmallVector<SDValue, 8> V(NumElems);
5403   if (NumElems == 4 && NumZero > 0) {
5404     for (unsigned i = 0; i < 4; ++i) {
5405       bool isZero = !(NonZeros & (1 << i));
5406       if (isZero)
5407         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5408       else
5409         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5410     }
5411
5412     for (unsigned i = 0; i < 2; ++i) {
5413       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5414         default: break;
5415         case 0:
5416           V[i] = V[i*2];  // Must be a zero vector.
5417           break;
5418         case 1:
5419           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5420           break;
5421         case 2:
5422           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5423           break;
5424         case 3:
5425           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5426           break;
5427       }
5428     }
5429
5430     bool Reverse1 = (NonZeros & 0x3) == 2;
5431     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5432     int MaskVec[] = {
5433       Reverse1 ? 1 : 0,
5434       Reverse1 ? 0 : 1,
5435       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5436       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5437     };
5438     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5439   }
5440
5441   if (Values.size() > 1 && VT.is128BitVector()) {
5442     // Check for a build vector of consecutive loads.
5443     for (unsigned i = 0; i < NumElems; ++i)
5444       V[i] = Op.getOperand(i);
5445
5446     // Check for elements which are consecutive loads.
5447     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5448     if (LD.getNode())
5449       return LD;
5450
5451     // For SSE 4.1, use insertps to put the high elements into the low element.
5452     if (getSubtarget()->hasSSE41()) {
5453       SDValue Result;
5454       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5455         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5456       else
5457         Result = DAG.getUNDEF(VT);
5458
5459       for (unsigned i = 1; i < NumElems; ++i) {
5460         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5461         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5462                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5463       }
5464       return Result;
5465     }
5466
5467     // Otherwise, expand into a number of unpckl*, start by extending each of
5468     // our (non-undef) elements to the full vector width with the element in the
5469     // bottom slot of the vector (which generates no code for SSE).
5470     for (unsigned i = 0; i < NumElems; ++i) {
5471       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5472         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5473       else
5474         V[i] = DAG.getUNDEF(VT);
5475     }
5476
5477     // Next, we iteratively mix elements, e.g. for v4f32:
5478     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5479     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5480     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5481     unsigned EltStride = NumElems >> 1;
5482     while (EltStride != 0) {
5483       for (unsigned i = 0; i < EltStride; ++i) {
5484         // If V[i+EltStride] is undef and this is the first round of mixing,
5485         // then it is safe to just drop this shuffle: V[i] is already in the
5486         // right place, the one element (since it's the first round) being
5487         // inserted as undef can be dropped.  This isn't safe for successive
5488         // rounds because they will permute elements within both vectors.
5489         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5490             EltStride == NumElems/2)
5491           continue;
5492
5493         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5494       }
5495       EltStride >>= 1;
5496     }
5497     return V[0];
5498   }
5499   return SDValue();
5500 }
5501
5502 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5503 // to create 256-bit vectors from two other 128-bit ones.
5504 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5505   DebugLoc dl = Op.getDebugLoc();
5506   EVT ResVT = Op.getValueType();
5507
5508   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5509
5510   SDValue V1 = Op.getOperand(0);
5511   SDValue V2 = Op.getOperand(1);
5512   unsigned NumElems = ResVT.getVectorNumElements();
5513
5514   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5515 }
5516
5517 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5518   assert(Op.getNumOperands() == 2);
5519
5520   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5521   // from two other 128-bit ones.
5522   return LowerAVXCONCAT_VECTORS(Op, DAG);
5523 }
5524
5525 // Try to lower a shuffle node into a simple blend instruction.
5526 static SDValue
5527 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5528                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5529   SDValue V1 = SVOp->getOperand(0);
5530   SDValue V2 = SVOp->getOperand(1);
5531   DebugLoc dl = SVOp->getDebugLoc();
5532   MVT VT = SVOp->getValueType(0).getSimpleVT();
5533   unsigned NumElems = VT.getVectorNumElements();
5534
5535   if (!Subtarget->hasSSE41())
5536     return SDValue();
5537
5538   unsigned ISDNo = 0;
5539   MVT OpTy;
5540
5541   switch (VT.SimpleTy) {
5542   default: return SDValue();
5543   case MVT::v8i16:
5544     ISDNo = X86ISD::BLENDPW;
5545     OpTy = MVT::v8i16;
5546     break;
5547   case MVT::v4i32:
5548   case MVT::v4f32:
5549     ISDNo = X86ISD::BLENDPS;
5550     OpTy = MVT::v4f32;
5551     break;
5552   case MVT::v2i64:
5553   case MVT::v2f64:
5554     ISDNo = X86ISD::BLENDPD;
5555     OpTy = MVT::v2f64;
5556     break;
5557   case MVT::v8i32:
5558   case MVT::v8f32:
5559     if (!Subtarget->hasAVX())
5560       return SDValue();
5561     ISDNo = X86ISD::BLENDPS;
5562     OpTy = MVT::v8f32;
5563     break;
5564   case MVT::v4i64:
5565   case MVT::v4f64:
5566     if (!Subtarget->hasAVX())
5567       return SDValue();
5568     ISDNo = X86ISD::BLENDPD;
5569     OpTy = MVT::v4f64;
5570     break;
5571   }
5572   assert(ISDNo && "Invalid Op Number");
5573
5574   unsigned MaskVals = 0;
5575
5576   for (unsigned i = 0; i != NumElems; ++i) {
5577     int EltIdx = SVOp->getMaskElt(i);
5578     if (EltIdx == (int)i || EltIdx < 0)
5579       MaskVals |= (1<<i);
5580     else if (EltIdx == (int)(i + NumElems))
5581       continue; // Bit is set to zero;
5582     else
5583       return SDValue();
5584   }
5585
5586   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5587   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5588   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5589                              DAG.getConstant(MaskVals, MVT::i32));
5590   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5591 }
5592
5593 // v8i16 shuffles - Prefer shuffles in the following order:
5594 // 1. [all]   pshuflw, pshufhw, optional move
5595 // 2. [ssse3] 1 x pshufb
5596 // 3. [ssse3] 2 x pshufb + 1 x por
5597 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5598 static SDValue
5599 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5600                          SelectionDAG &DAG) {
5601   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5602   SDValue V1 = SVOp->getOperand(0);
5603   SDValue V2 = SVOp->getOperand(1);
5604   DebugLoc dl = SVOp->getDebugLoc();
5605   SmallVector<int, 8> MaskVals;
5606
5607   // Determine if more than 1 of the words in each of the low and high quadwords
5608   // of the result come from the same quadword of one of the two inputs.  Undef
5609   // mask values count as coming from any quadword, for better codegen.
5610   unsigned LoQuad[] = { 0, 0, 0, 0 };
5611   unsigned HiQuad[] = { 0, 0, 0, 0 };
5612   std::bitset<4> InputQuads;
5613   for (unsigned i = 0; i < 8; ++i) {
5614     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5615     int EltIdx = SVOp->getMaskElt(i);
5616     MaskVals.push_back(EltIdx);
5617     if (EltIdx < 0) {
5618       ++Quad[0];
5619       ++Quad[1];
5620       ++Quad[2];
5621       ++Quad[3];
5622       continue;
5623     }
5624     ++Quad[EltIdx / 4];
5625     InputQuads.set(EltIdx / 4);
5626   }
5627
5628   int BestLoQuad = -1;
5629   unsigned MaxQuad = 1;
5630   for (unsigned i = 0; i < 4; ++i) {
5631     if (LoQuad[i] > MaxQuad) {
5632       BestLoQuad = i;
5633       MaxQuad = LoQuad[i];
5634     }
5635   }
5636
5637   int BestHiQuad = -1;
5638   MaxQuad = 1;
5639   for (unsigned i = 0; i < 4; ++i) {
5640     if (HiQuad[i] > MaxQuad) {
5641       BestHiQuad = i;
5642       MaxQuad = HiQuad[i];
5643     }
5644   }
5645
5646   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5647   // of the two input vectors, shuffle them into one input vector so only a
5648   // single pshufb instruction is necessary. If There are more than 2 input
5649   // quads, disable the next transformation since it does not help SSSE3.
5650   bool V1Used = InputQuads[0] || InputQuads[1];
5651   bool V2Used = InputQuads[2] || InputQuads[3];
5652   if (Subtarget->hasSSSE3()) {
5653     if (InputQuads.count() == 2 && V1Used && V2Used) {
5654       BestLoQuad = InputQuads[0] ? 0 : 1;
5655       BestHiQuad = InputQuads[2] ? 2 : 3;
5656     }
5657     if (InputQuads.count() > 2) {
5658       BestLoQuad = -1;
5659       BestHiQuad = -1;
5660     }
5661   }
5662
5663   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5664   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5665   // words from all 4 input quadwords.
5666   SDValue NewV;
5667   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5668     int MaskV[] = {
5669       BestLoQuad < 0 ? 0 : BestLoQuad,
5670       BestHiQuad < 0 ? 1 : BestHiQuad
5671     };
5672     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5673                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5674                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5675     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5676
5677     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5678     // source words for the shuffle, to aid later transformations.
5679     bool AllWordsInNewV = true;
5680     bool InOrder[2] = { true, true };
5681     for (unsigned i = 0; i != 8; ++i) {
5682       int idx = MaskVals[i];
5683       if (idx != (int)i)
5684         InOrder[i/4] = false;
5685       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5686         continue;
5687       AllWordsInNewV = false;
5688       break;
5689     }
5690
5691     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5692     if (AllWordsInNewV) {
5693       for (int i = 0; i != 8; ++i) {
5694         int idx = MaskVals[i];
5695         if (idx < 0)
5696           continue;
5697         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5698         if ((idx != i) && idx < 4)
5699           pshufhw = false;
5700         if ((idx != i) && idx > 3)
5701           pshuflw = false;
5702       }
5703       V1 = NewV;
5704       V2Used = false;
5705       BestLoQuad = 0;
5706       BestHiQuad = 1;
5707     }
5708
5709     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5710     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5711     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5712       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5713       unsigned TargetMask = 0;
5714       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5715                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5716       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5717       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5718                              getShufflePSHUFLWImmediate(SVOp);
5719       V1 = NewV.getOperand(0);
5720       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5721     }
5722   }
5723
5724   // If we have SSSE3, and all words of the result are from 1 input vector,
5725   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5726   // is present, fall back to case 4.
5727   if (Subtarget->hasSSSE3()) {
5728     SmallVector<SDValue,16> pshufbMask;
5729
5730     // If we have elements from both input vectors, set the high bit of the
5731     // shuffle mask element to zero out elements that come from V2 in the V1
5732     // mask, and elements that come from V1 in the V2 mask, so that the two
5733     // results can be OR'd together.
5734     bool TwoInputs = V1Used && V2Used;
5735     for (unsigned i = 0; i != 8; ++i) {
5736       int EltIdx = MaskVals[i] * 2;
5737       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5738       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5739       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5740       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5741     }
5742     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5743     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5744                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5745                                  MVT::v16i8, &pshufbMask[0], 16));
5746     if (!TwoInputs)
5747       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5748
5749     // Calculate the shuffle mask for the second input, shuffle it, and
5750     // OR it with the first shuffled input.
5751     pshufbMask.clear();
5752     for (unsigned i = 0; i != 8; ++i) {
5753       int EltIdx = MaskVals[i] * 2;
5754       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5755       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5756       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5757       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5758     }
5759     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5760     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5761                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5762                                  MVT::v16i8, &pshufbMask[0], 16));
5763     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5764     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5765   }
5766
5767   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5768   // and update MaskVals with new element order.
5769   std::bitset<8> InOrder;
5770   if (BestLoQuad >= 0) {
5771     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5772     for (int i = 0; i != 4; ++i) {
5773       int idx = MaskVals[i];
5774       if (idx < 0) {
5775         InOrder.set(i);
5776       } else if ((idx / 4) == BestLoQuad) {
5777         MaskV[i] = idx & 3;
5778         InOrder.set(i);
5779       }
5780     }
5781     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5782                                 &MaskV[0]);
5783
5784     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5785       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5786       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5787                                   NewV.getOperand(0),
5788                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5789     }
5790   }
5791
5792   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5793   // and update MaskVals with the new element order.
5794   if (BestHiQuad >= 0) {
5795     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5796     for (unsigned i = 4; i != 8; ++i) {
5797       int idx = MaskVals[i];
5798       if (idx < 0) {
5799         InOrder.set(i);
5800       } else if ((idx / 4) == BestHiQuad) {
5801         MaskV[i] = (idx & 3) + 4;
5802         InOrder.set(i);
5803       }
5804     }
5805     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5806                                 &MaskV[0]);
5807
5808     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5809       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5810       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5811                                   NewV.getOperand(0),
5812                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5813     }
5814   }
5815
5816   // In case BestHi & BestLo were both -1, which means each quadword has a word
5817   // from each of the four input quadwords, calculate the InOrder bitvector now
5818   // before falling through to the insert/extract cleanup.
5819   if (BestLoQuad == -1 && BestHiQuad == -1) {
5820     NewV = V1;
5821     for (int i = 0; i != 8; ++i)
5822       if (MaskVals[i] < 0 || MaskVals[i] == i)
5823         InOrder.set(i);
5824   }
5825
5826   // The other elements are put in the right place using pextrw and pinsrw.
5827   for (unsigned i = 0; i != 8; ++i) {
5828     if (InOrder[i])
5829       continue;
5830     int EltIdx = MaskVals[i];
5831     if (EltIdx < 0)
5832       continue;
5833     SDValue ExtOp = (EltIdx < 8) ?
5834       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5835                   DAG.getIntPtrConstant(EltIdx)) :
5836       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5837                   DAG.getIntPtrConstant(EltIdx - 8));
5838     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5839                        DAG.getIntPtrConstant(i));
5840   }
5841   return NewV;
5842 }
5843
5844 // v16i8 shuffles - Prefer shuffles in the following order:
5845 // 1. [ssse3] 1 x pshufb
5846 // 2. [ssse3] 2 x pshufb + 1 x por
5847 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5848 static
5849 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5850                                  SelectionDAG &DAG,
5851                                  const X86TargetLowering &TLI) {
5852   SDValue V1 = SVOp->getOperand(0);
5853   SDValue V2 = SVOp->getOperand(1);
5854   DebugLoc dl = SVOp->getDebugLoc();
5855   ArrayRef<int> MaskVals = SVOp->getMask();
5856
5857   // If we have SSSE3, case 1 is generated when all result bytes come from
5858   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5859   // present, fall back to case 3.
5860
5861   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5862   if (TLI.getSubtarget()->hasSSSE3()) {
5863     SmallVector<SDValue,16> pshufbMask;
5864
5865     // If all result elements are from one input vector, then only translate
5866     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5867     //
5868     // Otherwise, we have elements from both input vectors, and must zero out
5869     // elements that come from V2 in the first mask, and V1 in the second mask
5870     // so that we can OR them together.
5871     for (unsigned i = 0; i != 16; ++i) {
5872       int EltIdx = MaskVals[i];
5873       if (EltIdx < 0 || EltIdx >= 16)
5874         EltIdx = 0x80;
5875       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5876     }
5877     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5878                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5879                                  MVT::v16i8, &pshufbMask[0], 16));
5880
5881     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5882     // the 2nd operand if it's undefined or zero.
5883     if (V2.getOpcode() == ISD::UNDEF ||
5884         ISD::isBuildVectorAllZeros(V2.getNode()))
5885       return V1;
5886
5887     // Calculate the shuffle mask for the second input, shuffle it, and
5888     // OR it with the first shuffled input.
5889     pshufbMask.clear();
5890     for (unsigned i = 0; i != 16; ++i) {
5891       int EltIdx = MaskVals[i];
5892       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5893       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5894     }
5895     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5896                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5897                                  MVT::v16i8, &pshufbMask[0], 16));
5898     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5899   }
5900
5901   // No SSSE3 - Calculate in place words and then fix all out of place words
5902   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5903   // the 16 different words that comprise the two doublequadword input vectors.
5904   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5905   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5906   SDValue NewV = V1;
5907   for (int i = 0; i != 8; ++i) {
5908     int Elt0 = MaskVals[i*2];
5909     int Elt1 = MaskVals[i*2+1];
5910
5911     // This word of the result is all undef, skip it.
5912     if (Elt0 < 0 && Elt1 < 0)
5913       continue;
5914
5915     // This word of the result is already in the correct place, skip it.
5916     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5917       continue;
5918
5919     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5920     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5921     SDValue InsElt;
5922
5923     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5924     // using a single extract together, load it and store it.
5925     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5926       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5927                            DAG.getIntPtrConstant(Elt1 / 2));
5928       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5929                         DAG.getIntPtrConstant(i));
5930       continue;
5931     }
5932
5933     // If Elt1 is defined, extract it from the appropriate source.  If the
5934     // source byte is not also odd, shift the extracted word left 8 bits
5935     // otherwise clear the bottom 8 bits if we need to do an or.
5936     if (Elt1 >= 0) {
5937       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5938                            DAG.getIntPtrConstant(Elt1 / 2));
5939       if ((Elt1 & 1) == 0)
5940         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5941                              DAG.getConstant(8,
5942                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5943       else if (Elt0 >= 0)
5944         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5945                              DAG.getConstant(0xFF00, MVT::i16));
5946     }
5947     // If Elt0 is defined, extract it from the appropriate source.  If the
5948     // source byte is not also even, shift the extracted word right 8 bits. If
5949     // Elt1 was also defined, OR the extracted values together before
5950     // inserting them in the result.
5951     if (Elt0 >= 0) {
5952       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5953                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5954       if ((Elt0 & 1) != 0)
5955         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5956                               DAG.getConstant(8,
5957                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5958       else if (Elt1 >= 0)
5959         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5960                              DAG.getConstant(0x00FF, MVT::i16));
5961       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5962                          : InsElt0;
5963     }
5964     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5965                        DAG.getIntPtrConstant(i));
5966   }
5967   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5968 }
5969
5970 // v32i8 shuffles - Translate to VPSHUFB if possible.
5971 static
5972 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
5973                                  const X86Subtarget *Subtarget,
5974                                  SelectionDAG &DAG) {
5975   EVT VT = SVOp->getValueType(0);
5976   SDValue V1 = SVOp->getOperand(0);
5977   SDValue V2 = SVOp->getOperand(1);
5978   DebugLoc dl = SVOp->getDebugLoc();
5979   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
5980
5981   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5982   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
5983   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
5984
5985   // VPSHUFB may be generated if
5986   // (1) one of input vector is undefined or zeroinitializer.
5987   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
5988   // And (2) the mask indexes don't cross the 128-bit lane.
5989   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
5990       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
5991     return SDValue();
5992
5993   if (V1IsAllZero && !V2IsAllZero) {
5994     CommuteVectorShuffleMask(MaskVals, 32);
5995     V1 = V2;
5996   }
5997   SmallVector<SDValue, 32> pshufbMask;
5998   for (unsigned i = 0; i != 32; i++) {
5999     int EltIdx = MaskVals[i];
6000     if (EltIdx < 0 || EltIdx >= 32)
6001       EltIdx = 0x80;
6002     else {
6003       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6004         // Cross lane is not allowed.
6005         return SDValue();
6006       EltIdx &= 0xf;
6007     }
6008     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6009   }
6010   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6011                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6012                                   MVT::v32i8, &pshufbMask[0], 32));
6013 }
6014
6015 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6016 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6017 /// done when every pair / quad of shuffle mask elements point to elements in
6018 /// the right sequence. e.g.
6019 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6020 static
6021 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6022                                  SelectionDAG &DAG, DebugLoc dl) {
6023   MVT VT = SVOp->getValueType(0).getSimpleVT();
6024   unsigned NumElems = VT.getVectorNumElements();
6025   MVT NewVT;
6026   unsigned Scale;
6027   switch (VT.SimpleTy) {
6028   default: llvm_unreachable("Unexpected!");
6029   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6030   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6031   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6032   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6033   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6034   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6035   }
6036
6037   SmallVector<int, 8> MaskVec;
6038   for (unsigned i = 0; i != NumElems; i += Scale) {
6039     int StartIdx = -1;
6040     for (unsigned j = 0; j != Scale; ++j) {
6041       int EltIdx = SVOp->getMaskElt(i+j);
6042       if (EltIdx < 0)
6043         continue;
6044       if (StartIdx < 0)
6045         StartIdx = (EltIdx / Scale);
6046       if (EltIdx != (int)(StartIdx*Scale + j))
6047         return SDValue();
6048     }
6049     MaskVec.push_back(StartIdx);
6050   }
6051
6052   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6053   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6054   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6055 }
6056
6057 /// getVZextMovL - Return a zero-extending vector move low node.
6058 ///
6059 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6060                             SDValue SrcOp, SelectionDAG &DAG,
6061                             const X86Subtarget *Subtarget, DebugLoc dl) {
6062   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6063     LoadSDNode *LD = NULL;
6064     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6065       LD = dyn_cast<LoadSDNode>(SrcOp);
6066     if (!LD) {
6067       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6068       // instead.
6069       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6070       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6071           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6072           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6073           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6074         // PR2108
6075         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6076         return DAG.getNode(ISD::BITCAST, dl, VT,
6077                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6078                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6079                                                    OpVT,
6080                                                    SrcOp.getOperand(0)
6081                                                           .getOperand(0))));
6082       }
6083     }
6084   }
6085
6086   return DAG.getNode(ISD::BITCAST, dl, VT,
6087                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6088                                  DAG.getNode(ISD::BITCAST, dl,
6089                                              OpVT, SrcOp)));
6090 }
6091
6092 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6093 /// which could not be matched by any known target speficic shuffle
6094 static SDValue
6095 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6096
6097   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6098   if (NewOp.getNode())
6099     return NewOp;
6100
6101   EVT VT = SVOp->getValueType(0);
6102
6103   unsigned NumElems = VT.getVectorNumElements();
6104   unsigned NumLaneElems = NumElems / 2;
6105
6106   DebugLoc dl = SVOp->getDebugLoc();
6107   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6108   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6109   SDValue Output[2];
6110
6111   SmallVector<int, 16> Mask;
6112   for (unsigned l = 0; l < 2; ++l) {
6113     // Build a shuffle mask for the output, discovering on the fly which
6114     // input vectors to use as shuffle operands (recorded in InputUsed).
6115     // If building a suitable shuffle vector proves too hard, then bail
6116     // out with UseBuildVector set.
6117     bool UseBuildVector = false;
6118     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6119     unsigned LaneStart = l * NumLaneElems;
6120     for (unsigned i = 0; i != NumLaneElems; ++i) {
6121       // The mask element.  This indexes into the input.
6122       int Idx = SVOp->getMaskElt(i+LaneStart);
6123       if (Idx < 0) {
6124         // the mask element does not index into any input vector.
6125         Mask.push_back(-1);
6126         continue;
6127       }
6128
6129       // The input vector this mask element indexes into.
6130       int Input = Idx / NumLaneElems;
6131
6132       // Turn the index into an offset from the start of the input vector.
6133       Idx -= Input * NumLaneElems;
6134
6135       // Find or create a shuffle vector operand to hold this input.
6136       unsigned OpNo;
6137       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6138         if (InputUsed[OpNo] == Input)
6139           // This input vector is already an operand.
6140           break;
6141         if (InputUsed[OpNo] < 0) {
6142           // Create a new operand for this input vector.
6143           InputUsed[OpNo] = Input;
6144           break;
6145         }
6146       }
6147
6148       if (OpNo >= array_lengthof(InputUsed)) {
6149         // More than two input vectors used!  Give up on trying to create a
6150         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6151         UseBuildVector = true;
6152         break;
6153       }
6154
6155       // Add the mask index for the new shuffle vector.
6156       Mask.push_back(Idx + OpNo * NumLaneElems);
6157     }
6158
6159     if (UseBuildVector) {
6160       SmallVector<SDValue, 16> SVOps;
6161       for (unsigned i = 0; i != NumLaneElems; ++i) {
6162         // The mask element.  This indexes into the input.
6163         int Idx = SVOp->getMaskElt(i+LaneStart);
6164         if (Idx < 0) {
6165           SVOps.push_back(DAG.getUNDEF(EltVT));
6166           continue;
6167         }
6168
6169         // The input vector this mask element indexes into.
6170         int Input = Idx / NumElems;
6171
6172         // Turn the index into an offset from the start of the input vector.
6173         Idx -= Input * NumElems;
6174
6175         // Extract the vector element by hand.
6176         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6177                                     SVOp->getOperand(Input),
6178                                     DAG.getIntPtrConstant(Idx)));
6179       }
6180
6181       // Construct the output using a BUILD_VECTOR.
6182       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6183                               SVOps.size());
6184     } else if (InputUsed[0] < 0) {
6185       // No input vectors were used! The result is undefined.
6186       Output[l] = DAG.getUNDEF(NVT);
6187     } else {
6188       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6189                                         (InputUsed[0] % 2) * NumLaneElems,
6190                                         DAG, dl);
6191       // If only one input was used, use an undefined vector for the other.
6192       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6193         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6194                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6195       // At least one input vector was used. Create a new shuffle vector.
6196       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6197     }
6198
6199     Mask.clear();
6200   }
6201
6202   // Concatenate the result back
6203   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6204 }
6205
6206 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6207 /// 4 elements, and match them with several different shuffle types.
6208 static SDValue
6209 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6210   SDValue V1 = SVOp->getOperand(0);
6211   SDValue V2 = SVOp->getOperand(1);
6212   DebugLoc dl = SVOp->getDebugLoc();
6213   EVT VT = SVOp->getValueType(0);
6214
6215   assert(VT.is128BitVector() && "Unsupported vector size");
6216
6217   std::pair<int, int> Locs[4];
6218   int Mask1[] = { -1, -1, -1, -1 };
6219   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6220
6221   unsigned NumHi = 0;
6222   unsigned NumLo = 0;
6223   for (unsigned i = 0; i != 4; ++i) {
6224     int Idx = PermMask[i];
6225     if (Idx < 0) {
6226       Locs[i] = std::make_pair(-1, -1);
6227     } else {
6228       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6229       if (Idx < 4) {
6230         Locs[i] = std::make_pair(0, NumLo);
6231         Mask1[NumLo] = Idx;
6232         NumLo++;
6233       } else {
6234         Locs[i] = std::make_pair(1, NumHi);
6235         if (2+NumHi < 4)
6236           Mask1[2+NumHi] = Idx;
6237         NumHi++;
6238       }
6239     }
6240   }
6241
6242   if (NumLo <= 2 && NumHi <= 2) {
6243     // If no more than two elements come from either vector. This can be
6244     // implemented with two shuffles. First shuffle gather the elements.
6245     // The second shuffle, which takes the first shuffle as both of its
6246     // vector operands, put the elements into the right order.
6247     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6248
6249     int Mask2[] = { -1, -1, -1, -1 };
6250
6251     for (unsigned i = 0; i != 4; ++i)
6252       if (Locs[i].first != -1) {
6253         unsigned Idx = (i < 2) ? 0 : 4;
6254         Idx += Locs[i].first * 2 + Locs[i].second;
6255         Mask2[i] = Idx;
6256       }
6257
6258     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6259   }
6260
6261   if (NumLo == 3 || NumHi == 3) {
6262     // Otherwise, we must have three elements from one vector, call it X, and
6263     // one element from the other, call it Y.  First, use a shufps to build an
6264     // intermediate vector with the one element from Y and the element from X
6265     // that will be in the same half in the final destination (the indexes don't
6266     // matter). Then, use a shufps to build the final vector, taking the half
6267     // containing the element from Y from the intermediate, and the other half
6268     // from X.
6269     if (NumHi == 3) {
6270       // Normalize it so the 3 elements come from V1.
6271       CommuteVectorShuffleMask(PermMask, 4);
6272       std::swap(V1, V2);
6273     }
6274
6275     // Find the element from V2.
6276     unsigned HiIndex;
6277     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6278       int Val = PermMask[HiIndex];
6279       if (Val < 0)
6280         continue;
6281       if (Val >= 4)
6282         break;
6283     }
6284
6285     Mask1[0] = PermMask[HiIndex];
6286     Mask1[1] = -1;
6287     Mask1[2] = PermMask[HiIndex^1];
6288     Mask1[3] = -1;
6289     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6290
6291     if (HiIndex >= 2) {
6292       Mask1[0] = PermMask[0];
6293       Mask1[1] = PermMask[1];
6294       Mask1[2] = HiIndex & 1 ? 6 : 4;
6295       Mask1[3] = HiIndex & 1 ? 4 : 6;
6296       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6297     }
6298
6299     Mask1[0] = HiIndex & 1 ? 2 : 0;
6300     Mask1[1] = HiIndex & 1 ? 0 : 2;
6301     Mask1[2] = PermMask[2];
6302     Mask1[3] = PermMask[3];
6303     if (Mask1[2] >= 0)
6304       Mask1[2] += 4;
6305     if (Mask1[3] >= 0)
6306       Mask1[3] += 4;
6307     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6308   }
6309
6310   // Break it into (shuffle shuffle_hi, shuffle_lo).
6311   int LoMask[] = { -1, -1, -1, -1 };
6312   int HiMask[] = { -1, -1, -1, -1 };
6313
6314   int *MaskPtr = LoMask;
6315   unsigned MaskIdx = 0;
6316   unsigned LoIdx = 0;
6317   unsigned HiIdx = 2;
6318   for (unsigned i = 0; i != 4; ++i) {
6319     if (i == 2) {
6320       MaskPtr = HiMask;
6321       MaskIdx = 1;
6322       LoIdx = 0;
6323       HiIdx = 2;
6324     }
6325     int Idx = PermMask[i];
6326     if (Idx < 0) {
6327       Locs[i] = std::make_pair(-1, -1);
6328     } else if (Idx < 4) {
6329       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6330       MaskPtr[LoIdx] = Idx;
6331       LoIdx++;
6332     } else {
6333       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6334       MaskPtr[HiIdx] = Idx;
6335       HiIdx++;
6336     }
6337   }
6338
6339   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6340   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6341   int MaskOps[] = { -1, -1, -1, -1 };
6342   for (unsigned i = 0; i != 4; ++i)
6343     if (Locs[i].first != -1)
6344       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6345   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6346 }
6347
6348 static bool MayFoldVectorLoad(SDValue V) {
6349   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6350     V = V.getOperand(0);
6351   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6352     V = V.getOperand(0);
6353   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6354       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6355     // BUILD_VECTOR (load), undef
6356     V = V.getOperand(0);
6357   if (MayFoldLoad(V))
6358     return true;
6359   return false;
6360 }
6361
6362 // FIXME: the version above should always be used. Since there's
6363 // a bug where several vector shuffles can't be folded because the
6364 // DAG is not updated during lowering and a node claims to have two
6365 // uses while it only has one, use this version, and let isel match
6366 // another instruction if the load really happens to have more than
6367 // one use. Remove this version after this bug get fixed.
6368 // rdar://8434668, PR8156
6369 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6370   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6371     V = V.getOperand(0);
6372   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6373     V = V.getOperand(0);
6374   if (ISD::isNormalLoad(V.getNode()))
6375     return true;
6376   return false;
6377 }
6378
6379 static
6380 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6381   EVT VT = Op.getValueType();
6382
6383   // Canonizalize to v2f64.
6384   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6385   return DAG.getNode(ISD::BITCAST, dl, VT,
6386                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6387                                           V1, DAG));
6388 }
6389
6390 static
6391 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6392                         bool HasSSE2) {
6393   SDValue V1 = Op.getOperand(0);
6394   SDValue V2 = Op.getOperand(1);
6395   EVT VT = Op.getValueType();
6396
6397   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6398
6399   if (HasSSE2 && VT == MVT::v2f64)
6400     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6401
6402   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6403   return DAG.getNode(ISD::BITCAST, dl, VT,
6404                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6405                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6406                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6407 }
6408
6409 static
6410 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6411   SDValue V1 = Op.getOperand(0);
6412   SDValue V2 = Op.getOperand(1);
6413   EVT VT = Op.getValueType();
6414
6415   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6416          "unsupported shuffle type");
6417
6418   if (V2.getOpcode() == ISD::UNDEF)
6419     V2 = V1;
6420
6421   // v4i32 or v4f32
6422   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6423 }
6424
6425 static
6426 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6427   SDValue V1 = Op.getOperand(0);
6428   SDValue V2 = Op.getOperand(1);
6429   EVT VT = Op.getValueType();
6430   unsigned NumElems = VT.getVectorNumElements();
6431
6432   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6433   // operand of these instructions is only memory, so check if there's a
6434   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6435   // same masks.
6436   bool CanFoldLoad = false;
6437
6438   // Trivial case, when V2 comes from a load.
6439   if (MayFoldVectorLoad(V2))
6440     CanFoldLoad = true;
6441
6442   // When V1 is a load, it can be folded later into a store in isel, example:
6443   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6444   //    turns into:
6445   //  (MOVLPSmr addr:$src1, VR128:$src2)
6446   // So, recognize this potential and also use MOVLPS or MOVLPD
6447   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6448     CanFoldLoad = true;
6449
6450   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6451   if (CanFoldLoad) {
6452     if (HasSSE2 && NumElems == 2)
6453       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6454
6455     if (NumElems == 4)
6456       // If we don't care about the second element, proceed to use movss.
6457       if (SVOp->getMaskElt(1) != -1)
6458         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6459   }
6460
6461   // movl and movlp will both match v2i64, but v2i64 is never matched by
6462   // movl earlier because we make it strict to avoid messing with the movlp load
6463   // folding logic (see the code above getMOVLP call). Match it here then,
6464   // this is horrible, but will stay like this until we move all shuffle
6465   // matching to x86 specific nodes. Note that for the 1st condition all
6466   // types are matched with movsd.
6467   if (HasSSE2) {
6468     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6469     // as to remove this logic from here, as much as possible
6470     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6471       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6472     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6473   }
6474
6475   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6476
6477   // Invert the operand order and use SHUFPS to match it.
6478   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6479                               getShuffleSHUFImmediate(SVOp), DAG);
6480 }
6481
6482 SDValue
6483 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6485   EVT VT = Op.getValueType();
6486   DebugLoc dl = Op.getDebugLoc();
6487   SDValue V1 = Op.getOperand(0);
6488   SDValue V2 = Op.getOperand(1);
6489
6490   if (isZeroShuffle(SVOp))
6491     return getZeroVector(VT, Subtarget, DAG, dl);
6492
6493   // Handle splat operations
6494   if (SVOp->isSplat()) {
6495     unsigned NumElem = VT.getVectorNumElements();
6496     int Size = VT.getSizeInBits();
6497
6498     // Use vbroadcast whenever the splat comes from a foldable load
6499     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6500     if (Broadcast.getNode())
6501       return Broadcast;
6502
6503     // Handle splats by matching through known shuffle masks
6504     if ((Size == 128 && NumElem <= 4) ||
6505         (Size == 256 && NumElem < 8))
6506       return SDValue();
6507
6508     // All remaning splats are promoted to target supported vector shuffles.
6509     return PromoteSplat(SVOp, DAG);
6510   }
6511
6512   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6513   // do it!
6514   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6515       VT == MVT::v16i16 || VT == MVT::v32i8) {
6516     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6517     if (NewOp.getNode())
6518       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6519   } else if ((VT == MVT::v4i32 ||
6520              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6521     // FIXME: Figure out a cleaner way to do this.
6522     // Try to make use of movq to zero out the top part.
6523     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6524       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6525       if (NewOp.getNode()) {
6526         EVT NewVT = NewOp.getValueType();
6527         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6528                                NewVT, true, false))
6529           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6530                               DAG, Subtarget, dl);
6531       }
6532     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6533       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6534       if (NewOp.getNode()) {
6535         EVT NewVT = NewOp.getValueType();
6536         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6537           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6538                               DAG, Subtarget, dl);
6539       }
6540     }
6541   }
6542   return SDValue();
6543 }
6544
6545 SDValue
6546 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6547   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6548   SDValue V1 = Op.getOperand(0);
6549   SDValue V2 = Op.getOperand(1);
6550   EVT VT = Op.getValueType();
6551   DebugLoc dl = Op.getDebugLoc();
6552   unsigned NumElems = VT.getVectorNumElements();
6553   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6554   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6555   bool V1IsSplat = false;
6556   bool V2IsSplat = false;
6557   bool HasSSE2 = Subtarget->hasSSE2();
6558   bool HasAVX    = Subtarget->hasAVX();
6559   bool HasAVX2   = Subtarget->hasAVX2();
6560   MachineFunction &MF = DAG.getMachineFunction();
6561   bool OptForSize = MF.getFunction()->getFnAttributes().
6562     hasAttribute(Attributes::OptimizeForSize);
6563
6564   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6565
6566   if (V1IsUndef && V2IsUndef)
6567     return DAG.getUNDEF(VT);
6568
6569   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6570
6571   // Vector shuffle lowering takes 3 steps:
6572   //
6573   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6574   //    narrowing and commutation of operands should be handled.
6575   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6576   //    shuffle nodes.
6577   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6578   //    so the shuffle can be broken into other shuffles and the legalizer can
6579   //    try the lowering again.
6580   //
6581   // The general idea is that no vector_shuffle operation should be left to
6582   // be matched during isel, all of them must be converted to a target specific
6583   // node here.
6584
6585   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6586   // narrowing and commutation of operands should be handled. The actual code
6587   // doesn't include all of those, work in progress...
6588   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6589   if (NewOp.getNode())
6590     return NewOp;
6591
6592   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6593
6594   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6595   // unpckh_undef). Only use pshufd if speed is more important than size.
6596   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6597     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6598   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6599     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6600
6601   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6602       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6603     return getMOVDDup(Op, dl, V1, DAG);
6604
6605   if (isMOVHLPS_v_undef_Mask(M, VT))
6606     return getMOVHighToLow(Op, dl, DAG);
6607
6608   // Use to match splats
6609   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6610       (VT == MVT::v2f64 || VT == MVT::v2i64))
6611     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6612
6613   if (isPSHUFDMask(M, VT)) {
6614     // The actual implementation will match the mask in the if above and then
6615     // during isel it can match several different instructions, not only pshufd
6616     // as its name says, sad but true, emulate the behavior for now...
6617     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6618       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6619
6620     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6621
6622     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6623       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6624
6625     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6626       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6627
6628     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6629                                 TargetMask, DAG);
6630   }
6631
6632   // Check if this can be converted into a logical shift.
6633   bool isLeft = false;
6634   unsigned ShAmt = 0;
6635   SDValue ShVal;
6636   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6637   if (isShift && ShVal.hasOneUse()) {
6638     // If the shifted value has multiple uses, it may be cheaper to use
6639     // v_set0 + movlhps or movhlps, etc.
6640     EVT EltVT = VT.getVectorElementType();
6641     ShAmt *= EltVT.getSizeInBits();
6642     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6643   }
6644
6645   if (isMOVLMask(M, VT)) {
6646     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6647       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6648     if (!isMOVLPMask(M, VT)) {
6649       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6650         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6651
6652       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6653         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6654     }
6655   }
6656
6657   // FIXME: fold these into legal mask.
6658   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6659     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6660
6661   if (isMOVHLPSMask(M, VT))
6662     return getMOVHighToLow(Op, dl, DAG);
6663
6664   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6665     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6666
6667   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6668     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6669
6670   if (isMOVLPMask(M, VT))
6671     return getMOVLP(Op, dl, DAG, HasSSE2);
6672
6673   if (ShouldXformToMOVHLPS(M, VT) ||
6674       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6675     return CommuteVectorShuffle(SVOp, DAG);
6676
6677   if (isShift) {
6678     // No better options. Use a vshldq / vsrldq.
6679     EVT EltVT = VT.getVectorElementType();
6680     ShAmt *= EltVT.getSizeInBits();
6681     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6682   }
6683
6684   bool Commuted = false;
6685   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6686   // 1,1,1,1 -> v8i16 though.
6687   V1IsSplat = isSplatVector(V1.getNode());
6688   V2IsSplat = isSplatVector(V2.getNode());
6689
6690   // Canonicalize the splat or undef, if present, to be on the RHS.
6691   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6692     CommuteVectorShuffleMask(M, NumElems);
6693     std::swap(V1, V2);
6694     std::swap(V1IsSplat, V2IsSplat);
6695     Commuted = true;
6696   }
6697
6698   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6699     // Shuffling low element of v1 into undef, just return v1.
6700     if (V2IsUndef)
6701       return V1;
6702     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6703     // the instruction selector will not match, so get a canonical MOVL with
6704     // swapped operands to undo the commute.
6705     return getMOVL(DAG, dl, VT, V2, V1);
6706   }
6707
6708   if (isUNPCKLMask(M, VT, HasAVX2))
6709     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6710
6711   if (isUNPCKHMask(M, VT, HasAVX2))
6712     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6713
6714   if (V2IsSplat) {
6715     // Normalize mask so all entries that point to V2 points to its first
6716     // element then try to match unpck{h|l} again. If match, return a
6717     // new vector_shuffle with the corrected mask.p
6718     SmallVector<int, 8> NewMask(M.begin(), M.end());
6719     NormalizeMask(NewMask, NumElems);
6720     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6721       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6722     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6723       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6724   }
6725
6726   if (Commuted) {
6727     // Commute is back and try unpck* again.
6728     // FIXME: this seems wrong.
6729     CommuteVectorShuffleMask(M, NumElems);
6730     std::swap(V1, V2);
6731     std::swap(V1IsSplat, V2IsSplat);
6732     Commuted = false;
6733
6734     if (isUNPCKLMask(M, VT, HasAVX2))
6735       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6736
6737     if (isUNPCKHMask(M, VT, HasAVX2))
6738       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6739   }
6740
6741   // Normalize the node to match x86 shuffle ops if needed
6742   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6743     return CommuteVectorShuffle(SVOp, DAG);
6744
6745   // The checks below are all present in isShuffleMaskLegal, but they are
6746   // inlined here right now to enable us to directly emit target specific
6747   // nodes, and remove one by one until they don't return Op anymore.
6748
6749   if (isPALIGNRMask(M, VT, Subtarget))
6750     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6751                                 getShufflePALIGNRImmediate(SVOp),
6752                                 DAG);
6753
6754   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6755       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6756     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6757       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6758   }
6759
6760   if (isPSHUFHWMask(M, VT, HasAVX2))
6761     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6762                                 getShufflePSHUFHWImmediate(SVOp),
6763                                 DAG);
6764
6765   if (isPSHUFLWMask(M, VT, HasAVX2))
6766     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6767                                 getShufflePSHUFLWImmediate(SVOp),
6768                                 DAG);
6769
6770   if (isSHUFPMask(M, VT, HasAVX))
6771     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6772                                 getShuffleSHUFImmediate(SVOp), DAG);
6773
6774   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6775     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6776   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6777     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6778
6779   //===--------------------------------------------------------------------===//
6780   // Generate target specific nodes for 128 or 256-bit shuffles only
6781   // supported in the AVX instruction set.
6782   //
6783
6784   // Handle VMOVDDUPY permutations
6785   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6786     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6787
6788   // Handle VPERMILPS/D* permutations
6789   if (isVPERMILPMask(M, VT, HasAVX)) {
6790     if (HasAVX2 && VT == MVT::v8i32)
6791       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6792                                   getShuffleSHUFImmediate(SVOp), DAG);
6793     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6794                                 getShuffleSHUFImmediate(SVOp), DAG);
6795   }
6796
6797   // Handle VPERM2F128/VPERM2I128 permutations
6798   if (isVPERM2X128Mask(M, VT, HasAVX))
6799     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6800                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6801
6802   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6803   if (BlendOp.getNode())
6804     return BlendOp;
6805
6806   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6807     SmallVector<SDValue, 8> permclMask;
6808     for (unsigned i = 0; i != 8; ++i) {
6809       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6810     }
6811     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6812                                &permclMask[0], 8);
6813     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6814     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6815                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6816   }
6817
6818   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6819     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6820                                 getShuffleCLImmediate(SVOp), DAG);
6821
6822
6823   //===--------------------------------------------------------------------===//
6824   // Since no target specific shuffle was selected for this generic one,
6825   // lower it into other known shuffles. FIXME: this isn't true yet, but
6826   // this is the plan.
6827   //
6828
6829   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6830   if (VT == MVT::v8i16) {
6831     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6832     if (NewOp.getNode())
6833       return NewOp;
6834   }
6835
6836   if (VT == MVT::v16i8) {
6837     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6838     if (NewOp.getNode())
6839       return NewOp;
6840   }
6841
6842   if (VT == MVT::v32i8) {
6843     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6844     if (NewOp.getNode())
6845       return NewOp;
6846   }
6847
6848   // Handle all 128-bit wide vectors with 4 elements, and match them with
6849   // several different shuffle types.
6850   if (NumElems == 4 && VT.is128BitVector())
6851     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6852
6853   // Handle general 256-bit shuffles
6854   if (VT.is256BitVector())
6855     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6856
6857   return SDValue();
6858 }
6859
6860 SDValue
6861 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6862                                                 SelectionDAG &DAG) const {
6863   EVT VT = Op.getValueType();
6864   DebugLoc dl = Op.getDebugLoc();
6865
6866   if (!Op.getOperand(0).getValueType().is128BitVector())
6867     return SDValue();
6868
6869   if (VT.getSizeInBits() == 8) {
6870     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6871                                   Op.getOperand(0), Op.getOperand(1));
6872     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6873                                   DAG.getValueType(VT));
6874     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6875   }
6876
6877   if (VT.getSizeInBits() == 16) {
6878     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6879     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6880     if (Idx == 0)
6881       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6882                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6883                                      DAG.getNode(ISD::BITCAST, dl,
6884                                                  MVT::v4i32,
6885                                                  Op.getOperand(0)),
6886                                      Op.getOperand(1)));
6887     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6888                                   Op.getOperand(0), Op.getOperand(1));
6889     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6890                                   DAG.getValueType(VT));
6891     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6892   }
6893
6894   if (VT == MVT::f32) {
6895     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6896     // the result back to FR32 register. It's only worth matching if the
6897     // result has a single use which is a store or a bitcast to i32.  And in
6898     // the case of a store, it's not worth it if the index is a constant 0,
6899     // because a MOVSSmr can be used instead, which is smaller and faster.
6900     if (!Op.hasOneUse())
6901       return SDValue();
6902     SDNode *User = *Op.getNode()->use_begin();
6903     if ((User->getOpcode() != ISD::STORE ||
6904          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6905           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6906         (User->getOpcode() != ISD::BITCAST ||
6907          User->getValueType(0) != MVT::i32))
6908       return SDValue();
6909     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6910                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6911                                               Op.getOperand(0)),
6912                                               Op.getOperand(1));
6913     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6914   }
6915
6916   if (VT == MVT::i32 || VT == MVT::i64) {
6917     // ExtractPS/pextrq works with constant index.
6918     if (isa<ConstantSDNode>(Op.getOperand(1)))
6919       return Op;
6920   }
6921   return SDValue();
6922 }
6923
6924
6925 SDValue
6926 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6927                                            SelectionDAG &DAG) const {
6928   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6929     return SDValue();
6930
6931   SDValue Vec = Op.getOperand(0);
6932   EVT VecVT = Vec.getValueType();
6933
6934   // If this is a 256-bit vector result, first extract the 128-bit vector and
6935   // then extract the element from the 128-bit vector.
6936   if (VecVT.is256BitVector()) {
6937     DebugLoc dl = Op.getNode()->getDebugLoc();
6938     unsigned NumElems = VecVT.getVectorNumElements();
6939     SDValue Idx = Op.getOperand(1);
6940     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6941
6942     // Get the 128-bit vector.
6943     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6944
6945     if (IdxVal >= NumElems/2)
6946       IdxVal -= NumElems/2;
6947     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6948                        DAG.getConstant(IdxVal, MVT::i32));
6949   }
6950
6951   assert(VecVT.is128BitVector() && "Unexpected vector length");
6952
6953   if (Subtarget->hasSSE41()) {
6954     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6955     if (Res.getNode())
6956       return Res;
6957   }
6958
6959   EVT VT = Op.getValueType();
6960   DebugLoc dl = Op.getDebugLoc();
6961   // TODO: handle v16i8.
6962   if (VT.getSizeInBits() == 16) {
6963     SDValue Vec = Op.getOperand(0);
6964     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6965     if (Idx == 0)
6966       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6967                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6968                                      DAG.getNode(ISD::BITCAST, dl,
6969                                                  MVT::v4i32, Vec),
6970                                      Op.getOperand(1)));
6971     // Transform it so it match pextrw which produces a 32-bit result.
6972     EVT EltVT = MVT::i32;
6973     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6974                                   Op.getOperand(0), Op.getOperand(1));
6975     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6976                                   DAG.getValueType(VT));
6977     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6978   }
6979
6980   if (VT.getSizeInBits() == 32) {
6981     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6982     if (Idx == 0)
6983       return Op;
6984
6985     // SHUFPS the element to the lowest double word, then movss.
6986     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6987     EVT VVT = Op.getOperand(0).getValueType();
6988     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6989                                        DAG.getUNDEF(VVT), Mask);
6990     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6991                        DAG.getIntPtrConstant(0));
6992   }
6993
6994   if (VT.getSizeInBits() == 64) {
6995     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6996     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6997     //        to match extract_elt for f64.
6998     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6999     if (Idx == 0)
7000       return Op;
7001
7002     // UNPCKHPD the element to the lowest double word, then movsd.
7003     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7004     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7005     int Mask[2] = { 1, -1 };
7006     EVT VVT = Op.getOperand(0).getValueType();
7007     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7008                                        DAG.getUNDEF(VVT), Mask);
7009     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7010                        DAG.getIntPtrConstant(0));
7011   }
7012
7013   return SDValue();
7014 }
7015
7016 SDValue
7017 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7018                                                SelectionDAG &DAG) const {
7019   EVT VT = Op.getValueType();
7020   EVT EltVT = VT.getVectorElementType();
7021   DebugLoc dl = Op.getDebugLoc();
7022
7023   SDValue N0 = Op.getOperand(0);
7024   SDValue N1 = Op.getOperand(1);
7025   SDValue N2 = Op.getOperand(2);
7026
7027   if (!VT.is128BitVector())
7028     return SDValue();
7029
7030   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7031       isa<ConstantSDNode>(N2)) {
7032     unsigned Opc;
7033     if (VT == MVT::v8i16)
7034       Opc = X86ISD::PINSRW;
7035     else if (VT == MVT::v16i8)
7036       Opc = X86ISD::PINSRB;
7037     else
7038       Opc = X86ISD::PINSRB;
7039
7040     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7041     // argument.
7042     if (N1.getValueType() != MVT::i32)
7043       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7044     if (N2.getValueType() != MVT::i32)
7045       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7046     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7047   }
7048
7049   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7050     // Bits [7:6] of the constant are the source select.  This will always be
7051     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7052     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7053     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7054     // Bits [5:4] of the constant are the destination select.  This is the
7055     //  value of the incoming immediate.
7056     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7057     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7058     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7059     // Create this as a scalar to vector..
7060     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7061     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7062   }
7063
7064   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7065     // PINSR* works with constant index.
7066     return Op;
7067   }
7068   return SDValue();
7069 }
7070
7071 SDValue
7072 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7073   EVT VT = Op.getValueType();
7074   EVT EltVT = VT.getVectorElementType();
7075
7076   DebugLoc dl = Op.getDebugLoc();
7077   SDValue N0 = Op.getOperand(0);
7078   SDValue N1 = Op.getOperand(1);
7079   SDValue N2 = Op.getOperand(2);
7080
7081   // If this is a 256-bit vector result, first extract the 128-bit vector,
7082   // insert the element into the extracted half and then place it back.
7083   if (VT.is256BitVector()) {
7084     if (!isa<ConstantSDNode>(N2))
7085       return SDValue();
7086
7087     // Get the desired 128-bit vector half.
7088     unsigned NumElems = VT.getVectorNumElements();
7089     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7090     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7091
7092     // Insert the element into the desired half.
7093     bool Upper = IdxVal >= NumElems/2;
7094     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7095                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7096
7097     // Insert the changed part back to the 256-bit vector
7098     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7099   }
7100
7101   if (Subtarget->hasSSE41())
7102     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7103
7104   if (EltVT == MVT::i8)
7105     return SDValue();
7106
7107   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7108     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7109     // as its second argument.
7110     if (N1.getValueType() != MVT::i32)
7111       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7112     if (N2.getValueType() != MVT::i32)
7113       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7114     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7115   }
7116   return SDValue();
7117 }
7118
7119 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7120   LLVMContext *Context = DAG.getContext();
7121   DebugLoc dl = Op.getDebugLoc();
7122   EVT OpVT = Op.getValueType();
7123
7124   // If this is a 256-bit vector result, first insert into a 128-bit
7125   // vector and then insert into the 256-bit vector.
7126   if (!OpVT.is128BitVector()) {
7127     // Insert into a 128-bit vector.
7128     EVT VT128 = EVT::getVectorVT(*Context,
7129                                  OpVT.getVectorElementType(),
7130                                  OpVT.getVectorNumElements() / 2);
7131
7132     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7133
7134     // Insert the 128-bit vector.
7135     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7136   }
7137
7138   if (OpVT == MVT::v1i64 &&
7139       Op.getOperand(0).getValueType() == MVT::i64)
7140     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7141
7142   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7143   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7144   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7145                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7146 }
7147
7148 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7149 // a simple subregister reference or explicit instructions to grab
7150 // upper bits of a vector.
7151 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7152                                       SelectionDAG &DAG) {
7153   if (Subtarget->hasAVX()) {
7154     DebugLoc dl = Op.getNode()->getDebugLoc();
7155     SDValue Vec = Op.getNode()->getOperand(0);
7156     SDValue Idx = Op.getNode()->getOperand(1);
7157
7158     if (Op.getNode()->getValueType(0).is128BitVector() &&
7159         Vec.getNode()->getValueType(0).is256BitVector() &&
7160         isa<ConstantSDNode>(Idx)) {
7161       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7162       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7163     }
7164   }
7165   return SDValue();
7166 }
7167
7168 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7169 // simple superregister reference or explicit instructions to insert
7170 // the upper bits of a vector.
7171 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7172                                      SelectionDAG &DAG) {
7173   if (Subtarget->hasAVX()) {
7174     DebugLoc dl = Op.getNode()->getDebugLoc();
7175     SDValue Vec = Op.getNode()->getOperand(0);
7176     SDValue SubVec = Op.getNode()->getOperand(1);
7177     SDValue Idx = Op.getNode()->getOperand(2);
7178
7179     if (Op.getNode()->getValueType(0).is256BitVector() &&
7180         SubVec.getNode()->getValueType(0).is128BitVector() &&
7181         isa<ConstantSDNode>(Idx)) {
7182       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7183       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7184     }
7185   }
7186   return SDValue();
7187 }
7188
7189 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7190 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7191 // one of the above mentioned nodes. It has to be wrapped because otherwise
7192 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7193 // be used to form addressing mode. These wrapped nodes will be selected
7194 // into MOV32ri.
7195 SDValue
7196 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7197   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7198
7199   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7200   // global base reg.
7201   unsigned char OpFlag = 0;
7202   unsigned WrapperKind = X86ISD::Wrapper;
7203   CodeModel::Model M = getTargetMachine().getCodeModel();
7204
7205   if (Subtarget->isPICStyleRIPRel() &&
7206       (M == CodeModel::Small || M == CodeModel::Kernel))
7207     WrapperKind = X86ISD::WrapperRIP;
7208   else if (Subtarget->isPICStyleGOT())
7209     OpFlag = X86II::MO_GOTOFF;
7210   else if (Subtarget->isPICStyleStubPIC())
7211     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7212
7213   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7214                                              CP->getAlignment(),
7215                                              CP->getOffset(), OpFlag);
7216   DebugLoc DL = CP->getDebugLoc();
7217   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7218   // With PIC, the address is actually $g + Offset.
7219   if (OpFlag) {
7220     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7221                          DAG.getNode(X86ISD::GlobalBaseReg,
7222                                      DebugLoc(), getPointerTy()),
7223                          Result);
7224   }
7225
7226   return Result;
7227 }
7228
7229 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7230   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7231
7232   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7233   // global base reg.
7234   unsigned char OpFlag = 0;
7235   unsigned WrapperKind = X86ISD::Wrapper;
7236   CodeModel::Model M = getTargetMachine().getCodeModel();
7237
7238   if (Subtarget->isPICStyleRIPRel() &&
7239       (M == CodeModel::Small || M == CodeModel::Kernel))
7240     WrapperKind = X86ISD::WrapperRIP;
7241   else if (Subtarget->isPICStyleGOT())
7242     OpFlag = X86II::MO_GOTOFF;
7243   else if (Subtarget->isPICStyleStubPIC())
7244     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7245
7246   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7247                                           OpFlag);
7248   DebugLoc DL = JT->getDebugLoc();
7249   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7250
7251   // With PIC, the address is actually $g + Offset.
7252   if (OpFlag)
7253     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7254                          DAG.getNode(X86ISD::GlobalBaseReg,
7255                                      DebugLoc(), getPointerTy()),
7256                          Result);
7257
7258   return Result;
7259 }
7260
7261 SDValue
7262 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7263   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7264
7265   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7266   // global base reg.
7267   unsigned char OpFlag = 0;
7268   unsigned WrapperKind = X86ISD::Wrapper;
7269   CodeModel::Model M = getTargetMachine().getCodeModel();
7270
7271   if (Subtarget->isPICStyleRIPRel() &&
7272       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7273     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7274       OpFlag = X86II::MO_GOTPCREL;
7275     WrapperKind = X86ISD::WrapperRIP;
7276   } else if (Subtarget->isPICStyleGOT()) {
7277     OpFlag = X86II::MO_GOT;
7278   } else if (Subtarget->isPICStyleStubPIC()) {
7279     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7280   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7281     OpFlag = X86II::MO_DARWIN_NONLAZY;
7282   }
7283
7284   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7285
7286   DebugLoc DL = Op.getDebugLoc();
7287   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7288
7289
7290   // With PIC, the address is actually $g + Offset.
7291   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7292       !Subtarget->is64Bit()) {
7293     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7294                          DAG.getNode(X86ISD::GlobalBaseReg,
7295                                      DebugLoc(), getPointerTy()),
7296                          Result);
7297   }
7298
7299   // For symbols that require a load from a stub to get the address, emit the
7300   // load.
7301   if (isGlobalStubReference(OpFlag))
7302     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7303                          MachinePointerInfo::getGOT(), false, false, false, 0);
7304
7305   return Result;
7306 }
7307
7308 SDValue
7309 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7310   // Create the TargetBlockAddressAddress node.
7311   unsigned char OpFlags =
7312     Subtarget->ClassifyBlockAddressReference();
7313   CodeModel::Model M = getTargetMachine().getCodeModel();
7314   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7315   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7316   DebugLoc dl = Op.getDebugLoc();
7317   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7318                                              OpFlags);
7319
7320   if (Subtarget->isPICStyleRIPRel() &&
7321       (M == CodeModel::Small || M == CodeModel::Kernel))
7322     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7323   else
7324     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7325
7326   // With PIC, the address is actually $g + Offset.
7327   if (isGlobalRelativeToPICBase(OpFlags)) {
7328     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7329                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7330                          Result);
7331   }
7332
7333   return Result;
7334 }
7335
7336 SDValue
7337 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7338                                       int64_t Offset,
7339                                       SelectionDAG &DAG) const {
7340   // Create the TargetGlobalAddress node, folding in the constant
7341   // offset if it is legal.
7342   unsigned char OpFlags =
7343     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7344   CodeModel::Model M = getTargetMachine().getCodeModel();
7345   SDValue Result;
7346   if (OpFlags == X86II::MO_NO_FLAG &&
7347       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7348     // A direct static reference to a global.
7349     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7350     Offset = 0;
7351   } else {
7352     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7353   }
7354
7355   if (Subtarget->isPICStyleRIPRel() &&
7356       (M == CodeModel::Small || M == CodeModel::Kernel))
7357     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7358   else
7359     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7360
7361   // With PIC, the address is actually $g + Offset.
7362   if (isGlobalRelativeToPICBase(OpFlags)) {
7363     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7364                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7365                          Result);
7366   }
7367
7368   // For globals that require a load from a stub to get the address, emit the
7369   // load.
7370   if (isGlobalStubReference(OpFlags))
7371     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7372                          MachinePointerInfo::getGOT(), false, false, false, 0);
7373
7374   // If there was a non-zero offset that we didn't fold, create an explicit
7375   // addition for it.
7376   if (Offset != 0)
7377     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7378                          DAG.getConstant(Offset, getPointerTy()));
7379
7380   return Result;
7381 }
7382
7383 SDValue
7384 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7385   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7386   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7387   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7388 }
7389
7390 static SDValue
7391 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7392            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7393            unsigned char OperandFlags, bool LocalDynamic = false) {
7394   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7395   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7396   DebugLoc dl = GA->getDebugLoc();
7397   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7398                                            GA->getValueType(0),
7399                                            GA->getOffset(),
7400                                            OperandFlags);
7401
7402   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7403                                            : X86ISD::TLSADDR;
7404
7405   if (InFlag) {
7406     SDValue Ops[] = { Chain,  TGA, *InFlag };
7407     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7408   } else {
7409     SDValue Ops[]  = { Chain, TGA };
7410     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7411   }
7412
7413   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7414   MFI->setAdjustsStack(true);
7415
7416   SDValue Flag = Chain.getValue(1);
7417   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7418 }
7419
7420 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7421 static SDValue
7422 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7423                                 const EVT PtrVT) {
7424   SDValue InFlag;
7425   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7426   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7427                                    DAG.getNode(X86ISD::GlobalBaseReg,
7428                                                DebugLoc(), PtrVT), InFlag);
7429   InFlag = Chain.getValue(1);
7430
7431   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7432 }
7433
7434 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7435 static SDValue
7436 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7437                                 const EVT PtrVT) {
7438   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7439                     X86::RAX, X86II::MO_TLSGD);
7440 }
7441
7442 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7443                                            SelectionDAG &DAG,
7444                                            const EVT PtrVT,
7445                                            bool is64Bit) {
7446   DebugLoc dl = GA->getDebugLoc();
7447
7448   // Get the start address of the TLS block for this module.
7449   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7450       .getInfo<X86MachineFunctionInfo>();
7451   MFI->incNumLocalDynamicTLSAccesses();
7452
7453   SDValue Base;
7454   if (is64Bit) {
7455     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7456                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7457   } else {
7458     SDValue InFlag;
7459     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7460         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7461     InFlag = Chain.getValue(1);
7462     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7463                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7464   }
7465
7466   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7467   // of Base.
7468
7469   // Build x@dtpoff.
7470   unsigned char OperandFlags = X86II::MO_DTPOFF;
7471   unsigned WrapperKind = X86ISD::Wrapper;
7472   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7473                                            GA->getValueType(0),
7474                                            GA->getOffset(), OperandFlags);
7475   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7476
7477   // Add x@dtpoff with the base.
7478   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7479 }
7480
7481 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7482 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7483                                    const EVT PtrVT, TLSModel::Model model,
7484                                    bool is64Bit, bool isPIC) {
7485   DebugLoc dl = GA->getDebugLoc();
7486
7487   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7488   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7489                                                          is64Bit ? 257 : 256));
7490
7491   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7492                                       DAG.getIntPtrConstant(0),
7493                                       MachinePointerInfo(Ptr),
7494                                       false, false, false, 0);
7495
7496   unsigned char OperandFlags = 0;
7497   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7498   // initialexec.
7499   unsigned WrapperKind = X86ISD::Wrapper;
7500   if (model == TLSModel::LocalExec) {
7501     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7502   } else if (model == TLSModel::InitialExec) {
7503     if (is64Bit) {
7504       OperandFlags = X86II::MO_GOTTPOFF;
7505       WrapperKind = X86ISD::WrapperRIP;
7506     } else {
7507       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7508     }
7509   } else {
7510     llvm_unreachable("Unexpected model");
7511   }
7512
7513   // emit "addl x@ntpoff,%eax" (local exec)
7514   // or "addl x@indntpoff,%eax" (initial exec)
7515   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7516   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7517                                            GA->getValueType(0),
7518                                            GA->getOffset(), OperandFlags);
7519   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7520
7521   if (model == TLSModel::InitialExec) {
7522     if (isPIC && !is64Bit) {
7523       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7524                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7525                            Offset);
7526     }
7527
7528     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7529                          MachinePointerInfo::getGOT(), false, false, false,
7530                          0);
7531   }
7532
7533   // The address of the thread local variable is the add of the thread
7534   // pointer with the offset of the variable.
7535   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7536 }
7537
7538 SDValue
7539 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7540
7541   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7542   const GlobalValue *GV = GA->getGlobal();
7543
7544   if (Subtarget->isTargetELF()) {
7545     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7546
7547     switch (model) {
7548       case TLSModel::GeneralDynamic:
7549         if (Subtarget->is64Bit())
7550           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7551         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7552       case TLSModel::LocalDynamic:
7553         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7554                                            Subtarget->is64Bit());
7555       case TLSModel::InitialExec:
7556       case TLSModel::LocalExec:
7557         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7558                                    Subtarget->is64Bit(),
7559                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7560     }
7561     llvm_unreachable("Unknown TLS model.");
7562   }
7563
7564   if (Subtarget->isTargetDarwin()) {
7565     // Darwin only has one model of TLS.  Lower to that.
7566     unsigned char OpFlag = 0;
7567     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7568                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7569
7570     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7571     // global base reg.
7572     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7573                   !Subtarget->is64Bit();
7574     if (PIC32)
7575       OpFlag = X86II::MO_TLVP_PIC_BASE;
7576     else
7577       OpFlag = X86II::MO_TLVP;
7578     DebugLoc DL = Op.getDebugLoc();
7579     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7580                                                 GA->getValueType(0),
7581                                                 GA->getOffset(), OpFlag);
7582     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7583
7584     // With PIC32, the address is actually $g + Offset.
7585     if (PIC32)
7586       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7587                            DAG.getNode(X86ISD::GlobalBaseReg,
7588                                        DebugLoc(), getPointerTy()),
7589                            Offset);
7590
7591     // Lowering the machine isd will make sure everything is in the right
7592     // location.
7593     SDValue Chain = DAG.getEntryNode();
7594     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7595     SDValue Args[] = { Chain, Offset };
7596     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7597
7598     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7599     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7600     MFI->setAdjustsStack(true);
7601
7602     // And our return value (tls address) is in the standard call return value
7603     // location.
7604     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7605     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7606                               Chain.getValue(1));
7607   }
7608
7609   if (Subtarget->isTargetWindows()) {
7610     // Just use the implicit TLS architecture
7611     // Need to generate someting similar to:
7612     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7613     //                                  ; from TEB
7614     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7615     //   mov     rcx, qword [rdx+rcx*8]
7616     //   mov     eax, .tls$:tlsvar
7617     //   [rax+rcx] contains the address
7618     // Windows 64bit: gs:0x58
7619     // Windows 32bit: fs:__tls_array
7620
7621     // If GV is an alias then use the aliasee for determining
7622     // thread-localness.
7623     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7624       GV = GA->resolveAliasedGlobal(false);
7625     DebugLoc dl = GA->getDebugLoc();
7626     SDValue Chain = DAG.getEntryNode();
7627
7628     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7629     // %gs:0x58 (64-bit).
7630     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7631                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7632                                                              256)
7633                                         : Type::getInt32PtrTy(*DAG.getContext(),
7634                                                               257));
7635
7636     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7637                                         Subtarget->is64Bit()
7638                                         ? DAG.getIntPtrConstant(0x58)
7639                                         : DAG.getExternalSymbol("_tls_array",
7640                                                                 getPointerTy()),
7641                                         MachinePointerInfo(Ptr),
7642                                         false, false, false, 0);
7643
7644     // Load the _tls_index variable
7645     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7646     if (Subtarget->is64Bit())
7647       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7648                            IDX, MachinePointerInfo(), MVT::i32,
7649                            false, false, 0);
7650     else
7651       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7652                         false, false, false, 0);
7653
7654     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7655                                     getPointerTy());
7656     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7657
7658     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7659     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7660                       false, false, false, 0);
7661
7662     // Get the offset of start of .tls section
7663     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7664                                              GA->getValueType(0),
7665                                              GA->getOffset(), X86II::MO_SECREL);
7666     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7667
7668     // The address of the thread local variable is the add of the thread
7669     // pointer with the offset of the variable.
7670     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7671   }
7672
7673   llvm_unreachable("TLS not implemented for this target.");
7674 }
7675
7676
7677 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7678 /// and take a 2 x i32 value to shift plus a shift amount.
7679 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7680   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7681   EVT VT = Op.getValueType();
7682   unsigned VTBits = VT.getSizeInBits();
7683   DebugLoc dl = Op.getDebugLoc();
7684   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7685   SDValue ShOpLo = Op.getOperand(0);
7686   SDValue ShOpHi = Op.getOperand(1);
7687   SDValue ShAmt  = Op.getOperand(2);
7688   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7689                                      DAG.getConstant(VTBits - 1, MVT::i8))
7690                        : DAG.getConstant(0, VT);
7691
7692   SDValue Tmp2, Tmp3;
7693   if (Op.getOpcode() == ISD::SHL_PARTS) {
7694     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7695     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7696   } else {
7697     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7698     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7699   }
7700
7701   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7702                                 DAG.getConstant(VTBits, MVT::i8));
7703   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7704                              AndNode, DAG.getConstant(0, MVT::i8));
7705
7706   SDValue Hi, Lo;
7707   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7708   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7709   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7710
7711   if (Op.getOpcode() == ISD::SHL_PARTS) {
7712     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7713     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7714   } else {
7715     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7716     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7717   }
7718
7719   SDValue Ops[2] = { Lo, Hi };
7720   return DAG.getMergeValues(Ops, 2, dl);
7721 }
7722
7723 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7724                                            SelectionDAG &DAG) const {
7725   EVT SrcVT = Op.getOperand(0).getValueType();
7726
7727   if (SrcVT.isVector())
7728     return SDValue();
7729
7730   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7731          "Unknown SINT_TO_FP to lower!");
7732
7733   // These are really Legal; return the operand so the caller accepts it as
7734   // Legal.
7735   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7736     return Op;
7737   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7738       Subtarget->is64Bit()) {
7739     return Op;
7740   }
7741
7742   DebugLoc dl = Op.getDebugLoc();
7743   unsigned Size = SrcVT.getSizeInBits()/8;
7744   MachineFunction &MF = DAG.getMachineFunction();
7745   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7746   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7747   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7748                                StackSlot,
7749                                MachinePointerInfo::getFixedStack(SSFI),
7750                                false, false, 0);
7751   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7752 }
7753
7754 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7755                                      SDValue StackSlot,
7756                                      SelectionDAG &DAG) const {
7757   // Build the FILD
7758   DebugLoc DL = Op.getDebugLoc();
7759   SDVTList Tys;
7760   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7761   if (useSSE)
7762     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7763   else
7764     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7765
7766   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7767
7768   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7769   MachineMemOperand *MMO;
7770   if (FI) {
7771     int SSFI = FI->getIndex();
7772     MMO =
7773       DAG.getMachineFunction()
7774       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7775                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7776   } else {
7777     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7778     StackSlot = StackSlot.getOperand(1);
7779   }
7780   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7781   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7782                                            X86ISD::FILD, DL,
7783                                            Tys, Ops, array_lengthof(Ops),
7784                                            SrcVT, MMO);
7785
7786   if (useSSE) {
7787     Chain = Result.getValue(1);
7788     SDValue InFlag = Result.getValue(2);
7789
7790     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7791     // shouldn't be necessary except that RFP cannot be live across
7792     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7793     MachineFunction &MF = DAG.getMachineFunction();
7794     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7795     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7796     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7797     Tys = DAG.getVTList(MVT::Other);
7798     SDValue Ops[] = {
7799       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7800     };
7801     MachineMemOperand *MMO =
7802       DAG.getMachineFunction()
7803       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7804                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7805
7806     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7807                                     Ops, array_lengthof(Ops),
7808                                     Op.getValueType(), MMO);
7809     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7810                          MachinePointerInfo::getFixedStack(SSFI),
7811                          false, false, false, 0);
7812   }
7813
7814   return Result;
7815 }
7816
7817 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7818 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7819                                                SelectionDAG &DAG) const {
7820   // This algorithm is not obvious. Here it is what we're trying to output:
7821   /*
7822      movq       %rax,  %xmm0
7823      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7824      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7825      #ifdef __SSE3__
7826        haddpd   %xmm0, %xmm0
7827      #else
7828        pshufd   $0x4e, %xmm0, %xmm1
7829        addpd    %xmm1, %xmm0
7830      #endif
7831   */
7832
7833   DebugLoc dl = Op.getDebugLoc();
7834   LLVMContext *Context = DAG.getContext();
7835
7836   // Build some magic constants.
7837   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7838   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7839   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7840
7841   SmallVector<Constant*,2> CV1;
7842   CV1.push_back(
7843         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7844   CV1.push_back(
7845         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7846   Constant *C1 = ConstantVector::get(CV1);
7847   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7848
7849   // Load the 64-bit value into an XMM register.
7850   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7851                             Op.getOperand(0));
7852   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7853                               MachinePointerInfo::getConstantPool(),
7854                               false, false, false, 16);
7855   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7856                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7857                               CLod0);
7858
7859   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7860                               MachinePointerInfo::getConstantPool(),
7861                               false, false, false, 16);
7862   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7863   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7864   SDValue Result;
7865
7866   if (Subtarget->hasSSE3()) {
7867     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7868     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7869   } else {
7870     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7871     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7872                                            S2F, 0x4E, DAG);
7873     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7874                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7875                          Sub);
7876   }
7877
7878   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7879                      DAG.getIntPtrConstant(0));
7880 }
7881
7882 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7883 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7884                                                SelectionDAG &DAG) const {
7885   DebugLoc dl = Op.getDebugLoc();
7886   // FP constant to bias correct the final result.
7887   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7888                                    MVT::f64);
7889
7890   // Load the 32-bit value into an XMM register.
7891   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7892                              Op.getOperand(0));
7893
7894   // Zero out the upper parts of the register.
7895   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7896
7897   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7898                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7899                      DAG.getIntPtrConstant(0));
7900
7901   // Or the load with the bias.
7902   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7903                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7904                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7905                                                    MVT::v2f64, Load)),
7906                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7907                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7908                                                    MVT::v2f64, Bias)));
7909   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7910                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7911                    DAG.getIntPtrConstant(0));
7912
7913   // Subtract the bias.
7914   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7915
7916   // Handle final rounding.
7917   EVT DestVT = Op.getValueType();
7918
7919   if (DestVT.bitsLT(MVT::f64))
7920     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7921                        DAG.getIntPtrConstant(0));
7922   if (DestVT.bitsGT(MVT::f64))
7923     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7924
7925   // Handle final rounding.
7926   return Sub;
7927 }
7928
7929 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7930                                            SelectionDAG &DAG) const {
7931   SDValue N0 = Op.getOperand(0);
7932   DebugLoc dl = Op.getDebugLoc();
7933
7934   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7935   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7936   // the optimization here.
7937   if (DAG.SignBitIsZero(N0))
7938     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7939
7940   EVT SrcVT = N0.getValueType();
7941   EVT DstVT = Op.getValueType();
7942   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7943     return LowerUINT_TO_FP_i64(Op, DAG);
7944   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7945     return LowerUINT_TO_FP_i32(Op, DAG);
7946   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7947     return SDValue();
7948
7949   // Make a 64-bit buffer, and use it to build an FILD.
7950   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7951   if (SrcVT == MVT::i32) {
7952     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7953     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7954                                      getPointerTy(), StackSlot, WordOff);
7955     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7956                                   StackSlot, MachinePointerInfo(),
7957                                   false, false, 0);
7958     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7959                                   OffsetSlot, MachinePointerInfo(),
7960                                   false, false, 0);
7961     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7962     return Fild;
7963   }
7964
7965   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7966   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7967                                StackSlot, MachinePointerInfo(),
7968                                false, false, 0);
7969   // For i64 source, we need to add the appropriate power of 2 if the input
7970   // was negative.  This is the same as the optimization in
7971   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7972   // we must be careful to do the computation in x87 extended precision, not
7973   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7974   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7975   MachineMemOperand *MMO =
7976     DAG.getMachineFunction()
7977     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7978                           MachineMemOperand::MOLoad, 8, 8);
7979
7980   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7981   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7982   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7983                                          MVT::i64, MMO);
7984
7985   APInt FF(32, 0x5F800000ULL);
7986
7987   // Check whether the sign bit is set.
7988   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7989                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7990                                  ISD::SETLT);
7991
7992   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7993   SDValue FudgePtr = DAG.getConstantPool(
7994                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7995                                          getPointerTy());
7996
7997   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7998   SDValue Zero = DAG.getIntPtrConstant(0);
7999   SDValue Four = DAG.getIntPtrConstant(4);
8000   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8001                                Zero, Four);
8002   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8003
8004   // Load the value out, extending it from f32 to f80.
8005   // FIXME: Avoid the extend by constructing the right constant pool?
8006   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8007                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8008                                  MVT::f32, false, false, 4);
8009   // Extend everything to 80 bits to force it to be done on x87.
8010   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8011   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8012 }
8013
8014 std::pair<SDValue,SDValue> X86TargetLowering::
8015 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8016   DebugLoc DL = Op.getDebugLoc();
8017
8018   EVT DstTy = Op.getValueType();
8019
8020   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8021     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8022     DstTy = MVT::i64;
8023   }
8024
8025   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8026          DstTy.getSimpleVT() >= MVT::i16 &&
8027          "Unknown FP_TO_INT to lower!");
8028
8029   // These are really Legal.
8030   if (DstTy == MVT::i32 &&
8031       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8032     return std::make_pair(SDValue(), SDValue());
8033   if (Subtarget->is64Bit() &&
8034       DstTy == MVT::i64 &&
8035       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8036     return std::make_pair(SDValue(), SDValue());
8037
8038   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8039   // stack slot, or into the FTOL runtime function.
8040   MachineFunction &MF = DAG.getMachineFunction();
8041   unsigned MemSize = DstTy.getSizeInBits()/8;
8042   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8043   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8044
8045   unsigned Opc;
8046   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8047     Opc = X86ISD::WIN_FTOL;
8048   else
8049     switch (DstTy.getSimpleVT().SimpleTy) {
8050     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8051     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8052     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8053     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8054     }
8055
8056   SDValue Chain = DAG.getEntryNode();
8057   SDValue Value = Op.getOperand(0);
8058   EVT TheVT = Op.getOperand(0).getValueType();
8059   // FIXME This causes a redundant load/store if the SSE-class value is already
8060   // in memory, such as if it is on the callstack.
8061   if (isScalarFPTypeInSSEReg(TheVT)) {
8062     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8063     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8064                          MachinePointerInfo::getFixedStack(SSFI),
8065                          false, false, 0);
8066     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8067     SDValue Ops[] = {
8068       Chain, StackSlot, DAG.getValueType(TheVT)
8069     };
8070
8071     MachineMemOperand *MMO =
8072       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8073                               MachineMemOperand::MOLoad, MemSize, MemSize);
8074     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8075                                     DstTy, MMO);
8076     Chain = Value.getValue(1);
8077     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8078     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8079   }
8080
8081   MachineMemOperand *MMO =
8082     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8083                             MachineMemOperand::MOStore, MemSize, MemSize);
8084
8085   if (Opc != X86ISD::WIN_FTOL) {
8086     // Build the FP_TO_INT*_IN_MEM
8087     SDValue Ops[] = { Chain, Value, StackSlot };
8088     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8089                                            Ops, 3, DstTy, MMO);
8090     return std::make_pair(FIST, StackSlot);
8091   } else {
8092     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8093       DAG.getVTList(MVT::Other, MVT::Glue),
8094       Chain, Value);
8095     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8096       MVT::i32, ftol.getValue(1));
8097     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8098       MVT::i32, eax.getValue(2));
8099     SDValue Ops[] = { eax, edx };
8100     SDValue pair = IsReplace
8101       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8102       : DAG.getMergeValues(Ops, 2, DL);
8103     return std::make_pair(pair, SDValue());
8104   }
8105 }
8106
8107 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8108                                            SelectionDAG &DAG) const {
8109   if (Op.getValueType().isVector())
8110     return SDValue();
8111
8112   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8113     /*IsSigned=*/ true, /*IsReplace=*/ false);
8114   SDValue FIST = Vals.first, StackSlot = Vals.second;
8115   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8116   if (FIST.getNode() == 0) return Op;
8117
8118   if (StackSlot.getNode())
8119     // Load the result.
8120     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8121                        FIST, StackSlot, MachinePointerInfo(),
8122                        false, false, false, 0);
8123
8124   // The node is the result.
8125   return FIST;
8126 }
8127
8128 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8129                                            SelectionDAG &DAG) const {
8130   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8131     /*IsSigned=*/ false, /*IsReplace=*/ false);
8132   SDValue FIST = Vals.first, StackSlot = Vals.second;
8133   assert(FIST.getNode() && "Unexpected failure");
8134
8135   if (StackSlot.getNode())
8136     // Load the result.
8137     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8138                        FIST, StackSlot, MachinePointerInfo(),
8139                        false, false, false, 0);
8140
8141   // The node is the result.
8142   return FIST;
8143 }
8144
8145 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8146                                           SelectionDAG &DAG) const {
8147   DebugLoc DL = Op.getDebugLoc();
8148   EVT VT = Op.getValueType();
8149   SDValue In = Op.getOperand(0);
8150   EVT SVT = In.getValueType();
8151
8152   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8153
8154   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8155                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8156                                  In, DAG.getUNDEF(SVT)));
8157 }
8158
8159 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8160   LLVMContext *Context = DAG.getContext();
8161   DebugLoc dl = Op.getDebugLoc();
8162   EVT VT = Op.getValueType();
8163   EVT EltVT = VT;
8164   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8165   if (VT.isVector()) {
8166     EltVT = VT.getVectorElementType();
8167     NumElts = VT.getVectorNumElements();
8168   }
8169   Constant *C;
8170   if (EltVT == MVT::f64)
8171     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8172   else
8173     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8174   C = ConstantVector::getSplat(NumElts, C);
8175   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8176   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8177   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8178                              MachinePointerInfo::getConstantPool(),
8179                              false, false, false, Alignment);
8180   if (VT.isVector()) {
8181     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8182     return DAG.getNode(ISD::BITCAST, dl, VT,
8183                        DAG.getNode(ISD::AND, dl, ANDVT,
8184                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8185                                                Op.getOperand(0)),
8186                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8187   }
8188   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8189 }
8190
8191 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8192   LLVMContext *Context = DAG.getContext();
8193   DebugLoc dl = Op.getDebugLoc();
8194   EVT VT = Op.getValueType();
8195   EVT EltVT = VT;
8196   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8197   if (VT.isVector()) {
8198     EltVT = VT.getVectorElementType();
8199     NumElts = VT.getVectorNumElements();
8200   }
8201   Constant *C;
8202   if (EltVT == MVT::f64)
8203     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8204   else
8205     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8206   C = ConstantVector::getSplat(NumElts, C);
8207   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8208   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8209   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8210                              MachinePointerInfo::getConstantPool(),
8211                              false, false, false, Alignment);
8212   if (VT.isVector()) {
8213     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8214     return DAG.getNode(ISD::BITCAST, dl, VT,
8215                        DAG.getNode(ISD::XOR, dl, XORVT,
8216                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8217                                                Op.getOperand(0)),
8218                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8219   }
8220
8221   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8222 }
8223
8224 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8225   LLVMContext *Context = DAG.getContext();
8226   SDValue Op0 = Op.getOperand(0);
8227   SDValue Op1 = Op.getOperand(1);
8228   DebugLoc dl = Op.getDebugLoc();
8229   EVT VT = Op.getValueType();
8230   EVT SrcVT = Op1.getValueType();
8231
8232   // If second operand is smaller, extend it first.
8233   if (SrcVT.bitsLT(VT)) {
8234     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8235     SrcVT = VT;
8236   }
8237   // And if it is bigger, shrink it first.
8238   if (SrcVT.bitsGT(VT)) {
8239     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8240     SrcVT = VT;
8241   }
8242
8243   // At this point the operands and the result should have the same
8244   // type, and that won't be f80 since that is not custom lowered.
8245
8246   // First get the sign bit of second operand.
8247   SmallVector<Constant*,4> CV;
8248   if (SrcVT == MVT::f64) {
8249     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8250     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8251   } else {
8252     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8253     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8254     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8255     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8256   }
8257   Constant *C = ConstantVector::get(CV);
8258   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8259   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8260                               MachinePointerInfo::getConstantPool(),
8261                               false, false, false, 16);
8262   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8263
8264   // Shift sign bit right or left if the two operands have different types.
8265   if (SrcVT.bitsGT(VT)) {
8266     // Op0 is MVT::f32, Op1 is MVT::f64.
8267     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8268     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8269                           DAG.getConstant(32, MVT::i32));
8270     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8271     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8272                           DAG.getIntPtrConstant(0));
8273   }
8274
8275   // Clear first operand sign bit.
8276   CV.clear();
8277   if (VT == MVT::f64) {
8278     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8279     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8280   } else {
8281     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8282     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8283     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8284     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8285   }
8286   C = ConstantVector::get(CV);
8287   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8288   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8289                               MachinePointerInfo::getConstantPool(),
8290                               false, false, false, 16);
8291   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8292
8293   // Or the value with the sign bit.
8294   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8295 }
8296
8297 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8298   SDValue N0 = Op.getOperand(0);
8299   DebugLoc dl = Op.getDebugLoc();
8300   EVT VT = Op.getValueType();
8301
8302   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8303   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8304                                   DAG.getConstant(1, VT));
8305   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8306 }
8307
8308 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8309 //
8310 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8311   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8312
8313   if (!Subtarget->hasSSE41())
8314     return SDValue();
8315
8316   if (!Op->hasOneUse())
8317     return SDValue();
8318
8319   SDNode *N = Op.getNode();
8320   DebugLoc DL = N->getDebugLoc();
8321
8322   SmallVector<SDValue, 8> Opnds;
8323   DenseMap<SDValue, unsigned> VecInMap;
8324   EVT VT = MVT::Other;
8325
8326   // Recognize a special case where a vector is casted into wide integer to
8327   // test all 0s.
8328   Opnds.push_back(N->getOperand(0));
8329   Opnds.push_back(N->getOperand(1));
8330
8331   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8332     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8333     // BFS traverse all OR'd operands.
8334     if (I->getOpcode() == ISD::OR) {
8335       Opnds.push_back(I->getOperand(0));
8336       Opnds.push_back(I->getOperand(1));
8337       // Re-evaluate the number of nodes to be traversed.
8338       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8339       continue;
8340     }
8341
8342     // Quit if a non-EXTRACT_VECTOR_ELT
8343     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8344       return SDValue();
8345
8346     // Quit if without a constant index.
8347     SDValue Idx = I->getOperand(1);
8348     if (!isa<ConstantSDNode>(Idx))
8349       return SDValue();
8350
8351     SDValue ExtractedFromVec = I->getOperand(0);
8352     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8353     if (M == VecInMap.end()) {
8354       VT = ExtractedFromVec.getValueType();
8355       // Quit if not 128/256-bit vector.
8356       if (!VT.is128BitVector() && !VT.is256BitVector())
8357         return SDValue();
8358       // Quit if not the same type.
8359       if (VecInMap.begin() != VecInMap.end() &&
8360           VT != VecInMap.begin()->first.getValueType())
8361         return SDValue();
8362       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8363     }
8364     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8365   }
8366
8367   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8368          "Not extracted from 128-/256-bit vector.");
8369
8370   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8371   SmallVector<SDValue, 8> VecIns;
8372
8373   for (DenseMap<SDValue, unsigned>::const_iterator
8374         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8375     // Quit if not all elements are used.
8376     if (I->second != FullMask)
8377       return SDValue();
8378     VecIns.push_back(I->first);
8379   }
8380
8381   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8382
8383   // Cast all vectors into TestVT for PTEST.
8384   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8385     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8386
8387   // If more than one full vectors are evaluated, OR them first before PTEST.
8388   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8389     // Each iteration will OR 2 nodes and append the result until there is only
8390     // 1 node left, i.e. the final OR'd value of all vectors.
8391     SDValue LHS = VecIns[Slot];
8392     SDValue RHS = VecIns[Slot + 1];
8393     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8394   }
8395
8396   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8397                      VecIns.back(), VecIns.back());
8398 }
8399
8400 /// Emit nodes that will be selected as "test Op0,Op0", or something
8401 /// equivalent.
8402 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8403                                     SelectionDAG &DAG) const {
8404   DebugLoc dl = Op.getDebugLoc();
8405
8406   // CF and OF aren't always set the way we want. Determine which
8407   // of these we need.
8408   bool NeedCF = false;
8409   bool NeedOF = false;
8410   switch (X86CC) {
8411   default: break;
8412   case X86::COND_A: case X86::COND_AE:
8413   case X86::COND_B: case X86::COND_BE:
8414     NeedCF = true;
8415     break;
8416   case X86::COND_G: case X86::COND_GE:
8417   case X86::COND_L: case X86::COND_LE:
8418   case X86::COND_O: case X86::COND_NO:
8419     NeedOF = true;
8420     break;
8421   }
8422
8423   // See if we can use the EFLAGS value from the operand instead of
8424   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8425   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8426   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8427     // Emit a CMP with 0, which is the TEST pattern.
8428     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8429                        DAG.getConstant(0, Op.getValueType()));
8430
8431   unsigned Opcode = 0;
8432   unsigned NumOperands = 0;
8433
8434   // Truncate operations may prevent the merge of the SETCC instruction
8435   // and the arithmetic intruction before it. Attempt to truncate the operands
8436   // of the arithmetic instruction and use a reduced bit-width instruction.
8437   bool NeedTruncation = false;
8438   SDValue ArithOp = Op;
8439   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8440     SDValue Arith = Op->getOperand(0);
8441     // Both the trunc and the arithmetic op need to have one user each.
8442     if (Arith->hasOneUse())
8443       switch (Arith.getOpcode()) {
8444         default: break;
8445         case ISD::ADD:
8446         case ISD::SUB:
8447         case ISD::AND:
8448         case ISD::OR:
8449         case ISD::XOR: {
8450           NeedTruncation = true;
8451           ArithOp = Arith;
8452         }
8453       }
8454   }
8455
8456   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8457   // which may be the result of a CAST.  We use the variable 'Op', which is the
8458   // non-casted variable when we check for possible users.
8459   switch (ArithOp.getOpcode()) {
8460   case ISD::ADD:
8461     // Due to an isel shortcoming, be conservative if this add is likely to be
8462     // selected as part of a load-modify-store instruction. When the root node
8463     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8464     // uses of other nodes in the match, such as the ADD in this case. This
8465     // leads to the ADD being left around and reselected, with the result being
8466     // two adds in the output.  Alas, even if none our users are stores, that
8467     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8468     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8469     // climbing the DAG back to the root, and it doesn't seem to be worth the
8470     // effort.
8471     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8472          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8473       if (UI->getOpcode() != ISD::CopyToReg &&
8474           UI->getOpcode() != ISD::SETCC &&
8475           UI->getOpcode() != ISD::STORE)
8476         goto default_case;
8477
8478     if (ConstantSDNode *C =
8479         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8480       // An add of one will be selected as an INC.
8481       if (C->getAPIntValue() == 1) {
8482         Opcode = X86ISD::INC;
8483         NumOperands = 1;
8484         break;
8485       }
8486
8487       // An add of negative one (subtract of one) will be selected as a DEC.
8488       if (C->getAPIntValue().isAllOnesValue()) {
8489         Opcode = X86ISD::DEC;
8490         NumOperands = 1;
8491         break;
8492       }
8493     }
8494
8495     // Otherwise use a regular EFLAGS-setting add.
8496     Opcode = X86ISD::ADD;
8497     NumOperands = 2;
8498     break;
8499   case ISD::AND: {
8500     // If the primary and result isn't used, don't bother using X86ISD::AND,
8501     // because a TEST instruction will be better.
8502     bool NonFlagUse = false;
8503     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8504            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8505       SDNode *User = *UI;
8506       unsigned UOpNo = UI.getOperandNo();
8507       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8508         // Look pass truncate.
8509         UOpNo = User->use_begin().getOperandNo();
8510         User = *User->use_begin();
8511       }
8512
8513       if (User->getOpcode() != ISD::BRCOND &&
8514           User->getOpcode() != ISD::SETCC &&
8515           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8516         NonFlagUse = true;
8517         break;
8518       }
8519     }
8520
8521     if (!NonFlagUse)
8522       break;
8523   }
8524     // FALL THROUGH
8525   case ISD::SUB:
8526   case ISD::OR:
8527   case ISD::XOR:
8528     // Due to the ISEL shortcoming noted above, be conservative if this op is
8529     // likely to be selected as part of a load-modify-store instruction.
8530     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8531            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8532       if (UI->getOpcode() == ISD::STORE)
8533         goto default_case;
8534
8535     // Otherwise use a regular EFLAGS-setting instruction.
8536     switch (ArithOp.getOpcode()) {
8537     default: llvm_unreachable("unexpected operator!");
8538     case ISD::SUB: Opcode = X86ISD::SUB; break;
8539     case ISD::XOR: Opcode = X86ISD::XOR; break;
8540     case ISD::AND: Opcode = X86ISD::AND; break;
8541     case ISD::OR: {
8542       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8543         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8544         if (EFLAGS.getNode())
8545           return EFLAGS;
8546       }
8547       Opcode = X86ISD::OR;
8548       break;
8549     }
8550     }
8551
8552     NumOperands = 2;
8553     break;
8554   case X86ISD::ADD:
8555   case X86ISD::SUB:
8556   case X86ISD::INC:
8557   case X86ISD::DEC:
8558   case X86ISD::OR:
8559   case X86ISD::XOR:
8560   case X86ISD::AND:
8561     return SDValue(Op.getNode(), 1);
8562   default:
8563   default_case:
8564     break;
8565   }
8566
8567   // If we found that truncation is beneficial, perform the truncation and
8568   // update 'Op'.
8569   if (NeedTruncation) {
8570     EVT VT = Op.getValueType();
8571     SDValue WideVal = Op->getOperand(0);
8572     EVT WideVT = WideVal.getValueType();
8573     unsigned ConvertedOp = 0;
8574     // Use a target machine opcode to prevent further DAGCombine
8575     // optimizations that may separate the arithmetic operations
8576     // from the setcc node.
8577     switch (WideVal.getOpcode()) {
8578       default: break;
8579       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8580       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8581       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8582       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8583       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8584     }
8585
8586     if (ConvertedOp) {
8587       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8588       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8589         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8590         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8591         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8592       }
8593     }
8594   }
8595
8596   if (Opcode == 0)
8597     // Emit a CMP with 0, which is the TEST pattern.
8598     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8599                        DAG.getConstant(0, Op.getValueType()));
8600
8601   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8602   SmallVector<SDValue, 4> Ops;
8603   for (unsigned i = 0; i != NumOperands; ++i)
8604     Ops.push_back(Op.getOperand(i));
8605
8606   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8607   DAG.ReplaceAllUsesWith(Op, New);
8608   return SDValue(New.getNode(), 1);
8609 }
8610
8611 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8612 /// equivalent.
8613 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8614                                    SelectionDAG &DAG) const {
8615   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8616     if (C->getAPIntValue() == 0)
8617       return EmitTest(Op0, X86CC, DAG);
8618
8619   DebugLoc dl = Op0.getDebugLoc();
8620   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8621        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8622     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8623     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8624     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8625                               Op0, Op1);
8626     return SDValue(Sub.getNode(), 1);
8627   }
8628   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8629 }
8630
8631 /// Convert a comparison if required by the subtarget.
8632 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8633                                                  SelectionDAG &DAG) const {
8634   // If the subtarget does not support the FUCOMI instruction, floating-point
8635   // comparisons have to be converted.
8636   if (Subtarget->hasCMov() ||
8637       Cmp.getOpcode() != X86ISD::CMP ||
8638       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8639       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8640     return Cmp;
8641
8642   // The instruction selector will select an FUCOM instruction instead of
8643   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8644   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8645   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8646   DebugLoc dl = Cmp.getDebugLoc();
8647   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8648   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8649   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8650                             DAG.getConstant(8, MVT::i8));
8651   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8652   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8653 }
8654
8655 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8656 /// if it's possible.
8657 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8658                                      DebugLoc dl, SelectionDAG &DAG) const {
8659   SDValue Op0 = And.getOperand(0);
8660   SDValue Op1 = And.getOperand(1);
8661   if (Op0.getOpcode() == ISD::TRUNCATE)
8662     Op0 = Op0.getOperand(0);
8663   if (Op1.getOpcode() == ISD::TRUNCATE)
8664     Op1 = Op1.getOperand(0);
8665
8666   SDValue LHS, RHS;
8667   if (Op1.getOpcode() == ISD::SHL)
8668     std::swap(Op0, Op1);
8669   if (Op0.getOpcode() == ISD::SHL) {
8670     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8671       if (And00C->getZExtValue() == 1) {
8672         // If we looked past a truncate, check that it's only truncating away
8673         // known zeros.
8674         unsigned BitWidth = Op0.getValueSizeInBits();
8675         unsigned AndBitWidth = And.getValueSizeInBits();
8676         if (BitWidth > AndBitWidth) {
8677           APInt Zeros, Ones;
8678           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8679           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8680             return SDValue();
8681         }
8682         LHS = Op1;
8683         RHS = Op0.getOperand(1);
8684       }
8685   } else if (Op1.getOpcode() == ISD::Constant) {
8686     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8687     uint64_t AndRHSVal = AndRHS->getZExtValue();
8688     SDValue AndLHS = Op0;
8689
8690     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8691       LHS = AndLHS.getOperand(0);
8692       RHS = AndLHS.getOperand(1);
8693     }
8694
8695     // Use BT if the immediate can't be encoded in a TEST instruction.
8696     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8697       LHS = AndLHS;
8698       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8699     }
8700   }
8701
8702   if (LHS.getNode()) {
8703     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8704     // instruction.  Since the shift amount is in-range-or-undefined, we know
8705     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8706     // the encoding for the i16 version is larger than the i32 version.
8707     // Also promote i16 to i32 for performance / code size reason.
8708     if (LHS.getValueType() == MVT::i8 ||
8709         LHS.getValueType() == MVT::i16)
8710       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8711
8712     // If the operand types disagree, extend the shift amount to match.  Since
8713     // BT ignores high bits (like shifts) we can use anyextend.
8714     if (LHS.getValueType() != RHS.getValueType())
8715       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8716
8717     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8718     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8719     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8720                        DAG.getConstant(Cond, MVT::i8), BT);
8721   }
8722
8723   return SDValue();
8724 }
8725
8726 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8727
8728   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8729
8730   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8731   SDValue Op0 = Op.getOperand(0);
8732   SDValue Op1 = Op.getOperand(1);
8733   DebugLoc dl = Op.getDebugLoc();
8734   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8735
8736   // Optimize to BT if possible.
8737   // Lower (X & (1 << N)) == 0 to BT(X, N).
8738   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8739   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8740   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8741       Op1.getOpcode() == ISD::Constant &&
8742       cast<ConstantSDNode>(Op1)->isNullValue() &&
8743       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8744     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8745     if (NewSetCC.getNode())
8746       return NewSetCC;
8747   }
8748
8749   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8750   // these.
8751   if (Op1.getOpcode() == ISD::Constant &&
8752       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8753        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8754       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8755
8756     // If the input is a setcc, then reuse the input setcc or use a new one with
8757     // the inverted condition.
8758     if (Op0.getOpcode() == X86ISD::SETCC) {
8759       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8760       bool Invert = (CC == ISD::SETNE) ^
8761         cast<ConstantSDNode>(Op1)->isNullValue();
8762       if (!Invert) return Op0;
8763
8764       CCode = X86::GetOppositeBranchCondition(CCode);
8765       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8766                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8767     }
8768   }
8769
8770   bool isFP = Op1.getValueType().isFloatingPoint();
8771   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8772   if (X86CC == X86::COND_INVALID)
8773     return SDValue();
8774
8775   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8776   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8777   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8778                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8779 }
8780
8781 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8782 // ones, and then concatenate the result back.
8783 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8784   EVT VT = Op.getValueType();
8785
8786   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8787          "Unsupported value type for operation");
8788
8789   unsigned NumElems = VT.getVectorNumElements();
8790   DebugLoc dl = Op.getDebugLoc();
8791   SDValue CC = Op.getOperand(2);
8792
8793   // Extract the LHS vectors
8794   SDValue LHS = Op.getOperand(0);
8795   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8796   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8797
8798   // Extract the RHS vectors
8799   SDValue RHS = Op.getOperand(1);
8800   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8801   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8802
8803   // Issue the operation on the smaller types and concatenate the result back
8804   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8805   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8806   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8807                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8808                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8809 }
8810
8811
8812 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8813   SDValue Cond;
8814   SDValue Op0 = Op.getOperand(0);
8815   SDValue Op1 = Op.getOperand(1);
8816   SDValue CC = Op.getOperand(2);
8817   EVT VT = Op.getValueType();
8818   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8819   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8820   DebugLoc dl = Op.getDebugLoc();
8821
8822   if (isFP) {
8823 #ifndef NDEBUG
8824     EVT EltVT = Op0.getValueType().getVectorElementType();
8825     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8826 #endif
8827
8828     unsigned SSECC;
8829     bool Swap = false;
8830
8831     // SSE Condition code mapping:
8832     //  0 - EQ
8833     //  1 - LT
8834     //  2 - LE
8835     //  3 - UNORD
8836     //  4 - NEQ
8837     //  5 - NLT
8838     //  6 - NLE
8839     //  7 - ORD
8840     switch (SetCCOpcode) {
8841     default: llvm_unreachable("Unexpected SETCC condition");
8842     case ISD::SETOEQ:
8843     case ISD::SETEQ:  SSECC = 0; break;
8844     case ISD::SETOGT:
8845     case ISD::SETGT: Swap = true; // Fallthrough
8846     case ISD::SETLT:
8847     case ISD::SETOLT: SSECC = 1; break;
8848     case ISD::SETOGE:
8849     case ISD::SETGE: Swap = true; // Fallthrough
8850     case ISD::SETLE:
8851     case ISD::SETOLE: SSECC = 2; break;
8852     case ISD::SETUO:  SSECC = 3; break;
8853     case ISD::SETUNE:
8854     case ISD::SETNE:  SSECC = 4; break;
8855     case ISD::SETULE: Swap = true; // Fallthrough
8856     case ISD::SETUGE: SSECC = 5; break;
8857     case ISD::SETULT: Swap = true; // Fallthrough
8858     case ISD::SETUGT: SSECC = 6; break;
8859     case ISD::SETO:   SSECC = 7; break;
8860     case ISD::SETUEQ:
8861     case ISD::SETONE: SSECC = 8; break;
8862     }
8863     if (Swap)
8864       std::swap(Op0, Op1);
8865
8866     // In the two special cases we can't handle, emit two comparisons.
8867     if (SSECC == 8) {
8868       unsigned CC0, CC1;
8869       unsigned CombineOpc;
8870       if (SetCCOpcode == ISD::SETUEQ) {
8871         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8872       } else {
8873         assert(SetCCOpcode == ISD::SETONE);
8874         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8875       }
8876
8877       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8878                                  DAG.getConstant(CC0, MVT::i8));
8879       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8880                                  DAG.getConstant(CC1, MVT::i8));
8881       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8882     }
8883     // Handle all other FP comparisons here.
8884     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8885                        DAG.getConstant(SSECC, MVT::i8));
8886   }
8887
8888   // Break 256-bit integer vector compare into smaller ones.
8889   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8890     return Lower256IntVSETCC(Op, DAG);
8891
8892   // We are handling one of the integer comparisons here.  Since SSE only has
8893   // GT and EQ comparisons for integer, swapping operands and multiple
8894   // operations may be required for some comparisons.
8895   unsigned Opc;
8896   bool Swap = false, Invert = false, FlipSigns = false;
8897
8898   switch (SetCCOpcode) {
8899   default: llvm_unreachable("Unexpected SETCC condition");
8900   case ISD::SETNE:  Invert = true;
8901   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8902   case ISD::SETLT:  Swap = true;
8903   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8904   case ISD::SETGE:  Swap = true;
8905   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8906   case ISD::SETULT: Swap = true;
8907   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8908   case ISD::SETUGE: Swap = true;
8909   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8910   }
8911   if (Swap)
8912     std::swap(Op0, Op1);
8913
8914   // Check that the operation in question is available (most are plain SSE2,
8915   // but PCMPGTQ and PCMPEQQ have different requirements).
8916   if (VT == MVT::v2i64) {
8917     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8918       return SDValue();
8919     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8920       return SDValue();
8921   }
8922
8923   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8924   // bits of the inputs before performing those operations.
8925   if (FlipSigns) {
8926     EVT EltVT = VT.getVectorElementType();
8927     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8928                                       EltVT);
8929     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8930     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8931                                     SignBits.size());
8932     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8933     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8934   }
8935
8936   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8937
8938   // If the logical-not of the result is required, perform that now.
8939   if (Invert)
8940     Result = DAG.getNOT(dl, Result, VT);
8941
8942   return Result;
8943 }
8944
8945 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8946 static bool isX86LogicalCmp(SDValue Op) {
8947   unsigned Opc = Op.getNode()->getOpcode();
8948   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8949       Opc == X86ISD::SAHF)
8950     return true;
8951   if (Op.getResNo() == 1 &&
8952       (Opc == X86ISD::ADD ||
8953        Opc == X86ISD::SUB ||
8954        Opc == X86ISD::ADC ||
8955        Opc == X86ISD::SBB ||
8956        Opc == X86ISD::SMUL ||
8957        Opc == X86ISD::UMUL ||
8958        Opc == X86ISD::INC ||
8959        Opc == X86ISD::DEC ||
8960        Opc == X86ISD::OR ||
8961        Opc == X86ISD::XOR ||
8962        Opc == X86ISD::AND))
8963     return true;
8964
8965   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8966     return true;
8967
8968   return false;
8969 }
8970
8971 static bool isZero(SDValue V) {
8972   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8973   return C && C->isNullValue();
8974 }
8975
8976 static bool isAllOnes(SDValue V) {
8977   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8978   return C && C->isAllOnesValue();
8979 }
8980
8981 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8982   if (V.getOpcode() != ISD::TRUNCATE)
8983     return false;
8984
8985   SDValue VOp0 = V.getOperand(0);
8986   unsigned InBits = VOp0.getValueSizeInBits();
8987   unsigned Bits = V.getValueSizeInBits();
8988   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8989 }
8990
8991 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8992   bool addTest = true;
8993   SDValue Cond  = Op.getOperand(0);
8994   SDValue Op1 = Op.getOperand(1);
8995   SDValue Op2 = Op.getOperand(2);
8996   DebugLoc DL = Op.getDebugLoc();
8997   SDValue CC;
8998
8999   if (Cond.getOpcode() == ISD::SETCC) {
9000     SDValue NewCond = LowerSETCC(Cond, DAG);
9001     if (NewCond.getNode())
9002       Cond = NewCond;
9003   }
9004
9005   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9006   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9007   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9008   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9009   if (Cond.getOpcode() == X86ISD::SETCC &&
9010       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9011       isZero(Cond.getOperand(1).getOperand(1))) {
9012     SDValue Cmp = Cond.getOperand(1);
9013
9014     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9015
9016     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9017         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9018       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9019
9020       SDValue CmpOp0 = Cmp.getOperand(0);
9021       // Apply further optimizations for special cases
9022       // (select (x != 0), -1, 0) -> neg & sbb
9023       // (select (x == 0), 0, -1) -> neg & sbb
9024       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9025         if (YC->isNullValue() &&
9026             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9027           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9028           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9029                                     DAG.getConstant(0, CmpOp0.getValueType()),
9030                                     CmpOp0);
9031           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9032                                     DAG.getConstant(X86::COND_B, MVT::i8),
9033                                     SDValue(Neg.getNode(), 1));
9034           return Res;
9035         }
9036
9037       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9038                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9039       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9040
9041       SDValue Res =   // Res = 0 or -1.
9042         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9043                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9044
9045       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9046         Res = DAG.getNOT(DL, Res, Res.getValueType());
9047
9048       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9049       if (N2C == 0 || !N2C->isNullValue())
9050         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9051       return Res;
9052     }
9053   }
9054
9055   // Look past (and (setcc_carry (cmp ...)), 1).
9056   if (Cond.getOpcode() == ISD::AND &&
9057       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9058     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9059     if (C && C->getAPIntValue() == 1)
9060       Cond = Cond.getOperand(0);
9061   }
9062
9063   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9064   // setting operand in place of the X86ISD::SETCC.
9065   unsigned CondOpcode = Cond.getOpcode();
9066   if (CondOpcode == X86ISD::SETCC ||
9067       CondOpcode == X86ISD::SETCC_CARRY) {
9068     CC = Cond.getOperand(0);
9069
9070     SDValue Cmp = Cond.getOperand(1);
9071     unsigned Opc = Cmp.getOpcode();
9072     EVT VT = Op.getValueType();
9073
9074     bool IllegalFPCMov = false;
9075     if (VT.isFloatingPoint() && !VT.isVector() &&
9076         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9077       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9078
9079     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9080         Opc == X86ISD::BT) { // FIXME
9081       Cond = Cmp;
9082       addTest = false;
9083     }
9084   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9085              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9086              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9087               Cond.getOperand(0).getValueType() != MVT::i8)) {
9088     SDValue LHS = Cond.getOperand(0);
9089     SDValue RHS = Cond.getOperand(1);
9090     unsigned X86Opcode;
9091     unsigned X86Cond;
9092     SDVTList VTs;
9093     switch (CondOpcode) {
9094     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9095     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9096     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9097     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9098     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9099     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9100     default: llvm_unreachable("unexpected overflowing operator");
9101     }
9102     if (CondOpcode == ISD::UMULO)
9103       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9104                           MVT::i32);
9105     else
9106       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9107
9108     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9109
9110     if (CondOpcode == ISD::UMULO)
9111       Cond = X86Op.getValue(2);
9112     else
9113       Cond = X86Op.getValue(1);
9114
9115     CC = DAG.getConstant(X86Cond, MVT::i8);
9116     addTest = false;
9117   }
9118
9119   if (addTest) {
9120     // Look pass the truncate if the high bits are known zero.
9121     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9122         Cond = Cond.getOperand(0);
9123
9124     // We know the result of AND is compared against zero. Try to match
9125     // it to BT.
9126     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9127       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9128       if (NewSetCC.getNode()) {
9129         CC = NewSetCC.getOperand(0);
9130         Cond = NewSetCC.getOperand(1);
9131         addTest = false;
9132       }
9133     }
9134   }
9135
9136   if (addTest) {
9137     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9138     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9139   }
9140
9141   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9142   // a <  b ?  0 : -1 -> RES = setcc_carry
9143   // a >= b ? -1 :  0 -> RES = setcc_carry
9144   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9145   if (Cond.getOpcode() == X86ISD::SUB) {
9146     Cond = ConvertCmpIfNecessary(Cond, DAG);
9147     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9148
9149     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9150         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9151       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9152                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9153       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9154         return DAG.getNOT(DL, Res, Res.getValueType());
9155       return Res;
9156     }
9157   }
9158
9159   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9160   // widen the cmov and push the truncate through. This avoids introducing a new
9161   // branch during isel and doesn't add any extensions.
9162   if (Op.getValueType() == MVT::i8 &&
9163       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9164     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9165     if (T1.getValueType() == T2.getValueType() &&
9166         // Blacklist CopyFromReg to avoid partial register stalls.
9167         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9168       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9169       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9170       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9171     }
9172   }
9173
9174   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9175   // condition is true.
9176   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9177   SDValue Ops[] = { Op2, Op1, CC, Cond };
9178   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9179 }
9180
9181 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9182 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9183 // from the AND / OR.
9184 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9185   Opc = Op.getOpcode();
9186   if (Opc != ISD::OR && Opc != ISD::AND)
9187     return false;
9188   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9189           Op.getOperand(0).hasOneUse() &&
9190           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9191           Op.getOperand(1).hasOneUse());
9192 }
9193
9194 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9195 // 1 and that the SETCC node has a single use.
9196 static bool isXor1OfSetCC(SDValue Op) {
9197   if (Op.getOpcode() != ISD::XOR)
9198     return false;
9199   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9200   if (N1C && N1C->getAPIntValue() == 1) {
9201     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9202       Op.getOperand(0).hasOneUse();
9203   }
9204   return false;
9205 }
9206
9207 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9208   bool addTest = true;
9209   SDValue Chain = Op.getOperand(0);
9210   SDValue Cond  = Op.getOperand(1);
9211   SDValue Dest  = Op.getOperand(2);
9212   DebugLoc dl = Op.getDebugLoc();
9213   SDValue CC;
9214   bool Inverted = false;
9215
9216   if (Cond.getOpcode() == ISD::SETCC) {
9217     // Check for setcc([su]{add,sub,mul}o == 0).
9218     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9219         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9220         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9221         Cond.getOperand(0).getResNo() == 1 &&
9222         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9223          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9224          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9225          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9226          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9227          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9228       Inverted = true;
9229       Cond = Cond.getOperand(0);
9230     } else {
9231       SDValue NewCond = LowerSETCC(Cond, DAG);
9232       if (NewCond.getNode())
9233         Cond = NewCond;
9234     }
9235   }
9236 #if 0
9237   // FIXME: LowerXALUO doesn't handle these!!
9238   else if (Cond.getOpcode() == X86ISD::ADD  ||
9239            Cond.getOpcode() == X86ISD::SUB  ||
9240            Cond.getOpcode() == X86ISD::SMUL ||
9241            Cond.getOpcode() == X86ISD::UMUL)
9242     Cond = LowerXALUO(Cond, DAG);
9243 #endif
9244
9245   // Look pass (and (setcc_carry (cmp ...)), 1).
9246   if (Cond.getOpcode() == ISD::AND &&
9247       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9248     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9249     if (C && C->getAPIntValue() == 1)
9250       Cond = Cond.getOperand(0);
9251   }
9252
9253   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9254   // setting operand in place of the X86ISD::SETCC.
9255   unsigned CondOpcode = Cond.getOpcode();
9256   if (CondOpcode == X86ISD::SETCC ||
9257       CondOpcode == X86ISD::SETCC_CARRY) {
9258     CC = Cond.getOperand(0);
9259
9260     SDValue Cmp = Cond.getOperand(1);
9261     unsigned Opc = Cmp.getOpcode();
9262     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9263     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9264       Cond = Cmp;
9265       addTest = false;
9266     } else {
9267       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9268       default: break;
9269       case X86::COND_O:
9270       case X86::COND_B:
9271         // These can only come from an arithmetic instruction with overflow,
9272         // e.g. SADDO, UADDO.
9273         Cond = Cond.getNode()->getOperand(1);
9274         addTest = false;
9275         break;
9276       }
9277     }
9278   }
9279   CondOpcode = Cond.getOpcode();
9280   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9281       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9282       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9283        Cond.getOperand(0).getValueType() != MVT::i8)) {
9284     SDValue LHS = Cond.getOperand(0);
9285     SDValue RHS = Cond.getOperand(1);
9286     unsigned X86Opcode;
9287     unsigned X86Cond;
9288     SDVTList VTs;
9289     switch (CondOpcode) {
9290     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9291     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9292     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9293     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9294     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9295     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9296     default: llvm_unreachable("unexpected overflowing operator");
9297     }
9298     if (Inverted)
9299       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9300     if (CondOpcode == ISD::UMULO)
9301       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9302                           MVT::i32);
9303     else
9304       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9305
9306     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9307
9308     if (CondOpcode == ISD::UMULO)
9309       Cond = X86Op.getValue(2);
9310     else
9311       Cond = X86Op.getValue(1);
9312
9313     CC = DAG.getConstant(X86Cond, MVT::i8);
9314     addTest = false;
9315   } else {
9316     unsigned CondOpc;
9317     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9318       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9319       if (CondOpc == ISD::OR) {
9320         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9321         // two branches instead of an explicit OR instruction with a
9322         // separate test.
9323         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9324             isX86LogicalCmp(Cmp)) {
9325           CC = Cond.getOperand(0).getOperand(0);
9326           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9327                               Chain, Dest, CC, Cmp);
9328           CC = Cond.getOperand(1).getOperand(0);
9329           Cond = Cmp;
9330           addTest = false;
9331         }
9332       } else { // ISD::AND
9333         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9334         // two branches instead of an explicit AND instruction with a
9335         // separate test. However, we only do this if this block doesn't
9336         // have a fall-through edge, because this requires an explicit
9337         // jmp when the condition is false.
9338         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9339             isX86LogicalCmp(Cmp) &&
9340             Op.getNode()->hasOneUse()) {
9341           X86::CondCode CCode =
9342             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9343           CCode = X86::GetOppositeBranchCondition(CCode);
9344           CC = DAG.getConstant(CCode, MVT::i8);
9345           SDNode *User = *Op.getNode()->use_begin();
9346           // Look for an unconditional branch following this conditional branch.
9347           // We need this because we need to reverse the successors in order
9348           // to implement FCMP_OEQ.
9349           if (User->getOpcode() == ISD::BR) {
9350             SDValue FalseBB = User->getOperand(1);
9351             SDNode *NewBR =
9352               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9353             assert(NewBR == User);
9354             (void)NewBR;
9355             Dest = FalseBB;
9356
9357             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9358                                 Chain, Dest, CC, Cmp);
9359             X86::CondCode CCode =
9360               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9361             CCode = X86::GetOppositeBranchCondition(CCode);
9362             CC = DAG.getConstant(CCode, MVT::i8);
9363             Cond = Cmp;
9364             addTest = false;
9365           }
9366         }
9367       }
9368     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9369       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9370       // It should be transformed during dag combiner except when the condition
9371       // is set by a arithmetics with overflow node.
9372       X86::CondCode CCode =
9373         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9374       CCode = X86::GetOppositeBranchCondition(CCode);
9375       CC = DAG.getConstant(CCode, MVT::i8);
9376       Cond = Cond.getOperand(0).getOperand(1);
9377       addTest = false;
9378     } else if (Cond.getOpcode() == ISD::SETCC &&
9379                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9380       // For FCMP_OEQ, we can emit
9381       // two branches instead of an explicit AND instruction with a
9382       // separate test. However, we only do this if this block doesn't
9383       // have a fall-through edge, because this requires an explicit
9384       // jmp when the condition is false.
9385       if (Op.getNode()->hasOneUse()) {
9386         SDNode *User = *Op.getNode()->use_begin();
9387         // Look for an unconditional branch following this conditional branch.
9388         // We need this because we need to reverse the successors in order
9389         // to implement FCMP_OEQ.
9390         if (User->getOpcode() == ISD::BR) {
9391           SDValue FalseBB = User->getOperand(1);
9392           SDNode *NewBR =
9393             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9394           assert(NewBR == User);
9395           (void)NewBR;
9396           Dest = FalseBB;
9397
9398           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9399                                     Cond.getOperand(0), Cond.getOperand(1));
9400           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9401           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9402           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9403                               Chain, Dest, CC, Cmp);
9404           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9405           Cond = Cmp;
9406           addTest = false;
9407         }
9408       }
9409     } else if (Cond.getOpcode() == ISD::SETCC &&
9410                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9411       // For FCMP_UNE, we can emit
9412       // two branches instead of an explicit AND instruction with a
9413       // separate test. However, we only do this if this block doesn't
9414       // have a fall-through edge, because this requires an explicit
9415       // jmp when the condition is false.
9416       if (Op.getNode()->hasOneUse()) {
9417         SDNode *User = *Op.getNode()->use_begin();
9418         // Look for an unconditional branch following this conditional branch.
9419         // We need this because we need to reverse the successors in order
9420         // to implement FCMP_UNE.
9421         if (User->getOpcode() == ISD::BR) {
9422           SDValue FalseBB = User->getOperand(1);
9423           SDNode *NewBR =
9424             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9425           assert(NewBR == User);
9426           (void)NewBR;
9427
9428           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9429                                     Cond.getOperand(0), Cond.getOperand(1));
9430           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9431           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9432           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9433                               Chain, Dest, CC, Cmp);
9434           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9435           Cond = Cmp;
9436           addTest = false;
9437           Dest = FalseBB;
9438         }
9439       }
9440     }
9441   }
9442
9443   if (addTest) {
9444     // Look pass the truncate if the high bits are known zero.
9445     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9446         Cond = Cond.getOperand(0);
9447
9448     // We know the result of AND is compared against zero. Try to match
9449     // it to BT.
9450     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9451       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9452       if (NewSetCC.getNode()) {
9453         CC = NewSetCC.getOperand(0);
9454         Cond = NewSetCC.getOperand(1);
9455         addTest = false;
9456       }
9457     }
9458   }
9459
9460   if (addTest) {
9461     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9462     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9463   }
9464   Cond = ConvertCmpIfNecessary(Cond, DAG);
9465   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9466                      Chain, Dest, CC, Cond);
9467 }
9468
9469
9470 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9471 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9472 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9473 // that the guard pages used by the OS virtual memory manager are allocated in
9474 // correct sequence.
9475 SDValue
9476 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9477                                            SelectionDAG &DAG) const {
9478   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9479           getTargetMachine().Options.EnableSegmentedStacks) &&
9480          "This should be used only on Windows targets or when segmented stacks "
9481          "are being used");
9482   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9483   DebugLoc dl = Op.getDebugLoc();
9484
9485   // Get the inputs.
9486   SDValue Chain = Op.getOperand(0);
9487   SDValue Size  = Op.getOperand(1);
9488   // FIXME: Ensure alignment here
9489
9490   bool Is64Bit = Subtarget->is64Bit();
9491   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9492
9493   if (getTargetMachine().Options.EnableSegmentedStacks) {
9494     MachineFunction &MF = DAG.getMachineFunction();
9495     MachineRegisterInfo &MRI = MF.getRegInfo();
9496
9497     if (Is64Bit) {
9498       // The 64 bit implementation of segmented stacks needs to clobber both r10
9499       // r11. This makes it impossible to use it along with nested parameters.
9500       const Function *F = MF.getFunction();
9501
9502       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9503            I != E; ++I)
9504         if (I->hasNestAttr())
9505           report_fatal_error("Cannot use segmented stacks with functions that "
9506                              "have nested arguments.");
9507     }
9508
9509     const TargetRegisterClass *AddrRegClass =
9510       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9511     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9512     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9513     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9514                                 DAG.getRegister(Vreg, SPTy));
9515     SDValue Ops1[2] = { Value, Chain };
9516     return DAG.getMergeValues(Ops1, 2, dl);
9517   } else {
9518     SDValue Flag;
9519     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9520
9521     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9522     Flag = Chain.getValue(1);
9523     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9524
9525     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9526     Flag = Chain.getValue(1);
9527
9528     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9529
9530     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9531     return DAG.getMergeValues(Ops1, 2, dl);
9532   }
9533 }
9534
9535 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9536   MachineFunction &MF = DAG.getMachineFunction();
9537   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9538
9539   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9540   DebugLoc DL = Op.getDebugLoc();
9541
9542   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9543     // vastart just stores the address of the VarArgsFrameIndex slot into the
9544     // memory location argument.
9545     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9546                                    getPointerTy());
9547     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9548                         MachinePointerInfo(SV), false, false, 0);
9549   }
9550
9551   // __va_list_tag:
9552   //   gp_offset         (0 - 6 * 8)
9553   //   fp_offset         (48 - 48 + 8 * 16)
9554   //   overflow_arg_area (point to parameters coming in memory).
9555   //   reg_save_area
9556   SmallVector<SDValue, 8> MemOps;
9557   SDValue FIN = Op.getOperand(1);
9558   // Store gp_offset
9559   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9560                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9561                                                MVT::i32),
9562                                FIN, MachinePointerInfo(SV), false, false, 0);
9563   MemOps.push_back(Store);
9564
9565   // Store fp_offset
9566   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9567                     FIN, DAG.getIntPtrConstant(4));
9568   Store = DAG.getStore(Op.getOperand(0), DL,
9569                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9570                                        MVT::i32),
9571                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9572   MemOps.push_back(Store);
9573
9574   // Store ptr to overflow_arg_area
9575   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9576                     FIN, DAG.getIntPtrConstant(4));
9577   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9578                                     getPointerTy());
9579   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9580                        MachinePointerInfo(SV, 8),
9581                        false, false, 0);
9582   MemOps.push_back(Store);
9583
9584   // Store ptr to reg_save_area.
9585   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9586                     FIN, DAG.getIntPtrConstant(8));
9587   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9588                                     getPointerTy());
9589   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9590                        MachinePointerInfo(SV, 16), false, false, 0);
9591   MemOps.push_back(Store);
9592   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9593                      &MemOps[0], MemOps.size());
9594 }
9595
9596 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9597   assert(Subtarget->is64Bit() &&
9598          "LowerVAARG only handles 64-bit va_arg!");
9599   assert((Subtarget->isTargetLinux() ||
9600           Subtarget->isTargetDarwin()) &&
9601           "Unhandled target in LowerVAARG");
9602   assert(Op.getNode()->getNumOperands() == 4);
9603   SDValue Chain = Op.getOperand(0);
9604   SDValue SrcPtr = Op.getOperand(1);
9605   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9606   unsigned Align = Op.getConstantOperandVal(3);
9607   DebugLoc dl = Op.getDebugLoc();
9608
9609   EVT ArgVT = Op.getNode()->getValueType(0);
9610   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9611   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9612   uint8_t ArgMode;
9613
9614   // Decide which area this value should be read from.
9615   // TODO: Implement the AMD64 ABI in its entirety. This simple
9616   // selection mechanism works only for the basic types.
9617   if (ArgVT == MVT::f80) {
9618     llvm_unreachable("va_arg for f80 not yet implemented");
9619   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9620     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9621   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9622     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9623   } else {
9624     llvm_unreachable("Unhandled argument type in LowerVAARG");
9625   }
9626
9627   if (ArgMode == 2) {
9628     // Sanity Check: Make sure using fp_offset makes sense.
9629     assert(!getTargetMachine().Options.UseSoftFloat &&
9630            !(DAG.getMachineFunction()
9631                 .getFunction()->getFnAttributes()
9632                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9633            Subtarget->hasSSE1());
9634   }
9635
9636   // Insert VAARG_64 node into the DAG
9637   // VAARG_64 returns two values: Variable Argument Address, Chain
9638   SmallVector<SDValue, 11> InstOps;
9639   InstOps.push_back(Chain);
9640   InstOps.push_back(SrcPtr);
9641   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9642   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9643   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9644   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9645   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9646                                           VTs, &InstOps[0], InstOps.size(),
9647                                           MVT::i64,
9648                                           MachinePointerInfo(SV),
9649                                           /*Align=*/0,
9650                                           /*Volatile=*/false,
9651                                           /*ReadMem=*/true,
9652                                           /*WriteMem=*/true);
9653   Chain = VAARG.getValue(1);
9654
9655   // Load the next argument and return it
9656   return DAG.getLoad(ArgVT, dl,
9657                      Chain,
9658                      VAARG,
9659                      MachinePointerInfo(),
9660                      false, false, false, 0);
9661 }
9662
9663 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9664                            SelectionDAG &DAG) {
9665   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9666   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9667   SDValue Chain = Op.getOperand(0);
9668   SDValue DstPtr = Op.getOperand(1);
9669   SDValue SrcPtr = Op.getOperand(2);
9670   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9671   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9672   DebugLoc DL = Op.getDebugLoc();
9673
9674   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9675                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9676                        false,
9677                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9678 }
9679
9680 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9681 // may or may not be a constant. Takes immediate version of shift as input.
9682 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9683                                    SDValue SrcOp, SDValue ShAmt,
9684                                    SelectionDAG &DAG) {
9685   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9686
9687   if (isa<ConstantSDNode>(ShAmt)) {
9688     // Constant may be a TargetConstant. Use a regular constant.
9689     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9690     switch (Opc) {
9691       default: llvm_unreachable("Unknown target vector shift node");
9692       case X86ISD::VSHLI:
9693       case X86ISD::VSRLI:
9694       case X86ISD::VSRAI:
9695         return DAG.getNode(Opc, dl, VT, SrcOp,
9696                            DAG.getConstant(ShiftAmt, MVT::i32));
9697     }
9698   }
9699
9700   // Change opcode to non-immediate version
9701   switch (Opc) {
9702     default: llvm_unreachable("Unknown target vector shift node");
9703     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9704     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9705     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9706   }
9707
9708   // Need to build a vector containing shift amount
9709   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9710   SDValue ShOps[4];
9711   ShOps[0] = ShAmt;
9712   ShOps[1] = DAG.getConstant(0, MVT::i32);
9713   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9714   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9715
9716   // The return type has to be a 128-bit type with the same element
9717   // type as the input type.
9718   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9719   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9720
9721   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9722   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9723 }
9724
9725 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9726   DebugLoc dl = Op.getDebugLoc();
9727   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9728   switch (IntNo) {
9729   default: return SDValue();    // Don't custom lower most intrinsics.
9730   // Comparison intrinsics.
9731   case Intrinsic::x86_sse_comieq_ss:
9732   case Intrinsic::x86_sse_comilt_ss:
9733   case Intrinsic::x86_sse_comile_ss:
9734   case Intrinsic::x86_sse_comigt_ss:
9735   case Intrinsic::x86_sse_comige_ss:
9736   case Intrinsic::x86_sse_comineq_ss:
9737   case Intrinsic::x86_sse_ucomieq_ss:
9738   case Intrinsic::x86_sse_ucomilt_ss:
9739   case Intrinsic::x86_sse_ucomile_ss:
9740   case Intrinsic::x86_sse_ucomigt_ss:
9741   case Intrinsic::x86_sse_ucomige_ss:
9742   case Intrinsic::x86_sse_ucomineq_ss:
9743   case Intrinsic::x86_sse2_comieq_sd:
9744   case Intrinsic::x86_sse2_comilt_sd:
9745   case Intrinsic::x86_sse2_comile_sd:
9746   case Intrinsic::x86_sse2_comigt_sd:
9747   case Intrinsic::x86_sse2_comige_sd:
9748   case Intrinsic::x86_sse2_comineq_sd:
9749   case Intrinsic::x86_sse2_ucomieq_sd:
9750   case Intrinsic::x86_sse2_ucomilt_sd:
9751   case Intrinsic::x86_sse2_ucomile_sd:
9752   case Intrinsic::x86_sse2_ucomigt_sd:
9753   case Intrinsic::x86_sse2_ucomige_sd:
9754   case Intrinsic::x86_sse2_ucomineq_sd: {
9755     unsigned Opc;
9756     ISD::CondCode CC;
9757     switch (IntNo) {
9758     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9759     case Intrinsic::x86_sse_comieq_ss:
9760     case Intrinsic::x86_sse2_comieq_sd:
9761       Opc = X86ISD::COMI;
9762       CC = ISD::SETEQ;
9763       break;
9764     case Intrinsic::x86_sse_comilt_ss:
9765     case Intrinsic::x86_sse2_comilt_sd:
9766       Opc = X86ISD::COMI;
9767       CC = ISD::SETLT;
9768       break;
9769     case Intrinsic::x86_sse_comile_ss:
9770     case Intrinsic::x86_sse2_comile_sd:
9771       Opc = X86ISD::COMI;
9772       CC = ISD::SETLE;
9773       break;
9774     case Intrinsic::x86_sse_comigt_ss:
9775     case Intrinsic::x86_sse2_comigt_sd:
9776       Opc = X86ISD::COMI;
9777       CC = ISD::SETGT;
9778       break;
9779     case Intrinsic::x86_sse_comige_ss:
9780     case Intrinsic::x86_sse2_comige_sd:
9781       Opc = X86ISD::COMI;
9782       CC = ISD::SETGE;
9783       break;
9784     case Intrinsic::x86_sse_comineq_ss:
9785     case Intrinsic::x86_sse2_comineq_sd:
9786       Opc = X86ISD::COMI;
9787       CC = ISD::SETNE;
9788       break;
9789     case Intrinsic::x86_sse_ucomieq_ss:
9790     case Intrinsic::x86_sse2_ucomieq_sd:
9791       Opc = X86ISD::UCOMI;
9792       CC = ISD::SETEQ;
9793       break;
9794     case Intrinsic::x86_sse_ucomilt_ss:
9795     case Intrinsic::x86_sse2_ucomilt_sd:
9796       Opc = X86ISD::UCOMI;
9797       CC = ISD::SETLT;
9798       break;
9799     case Intrinsic::x86_sse_ucomile_ss:
9800     case Intrinsic::x86_sse2_ucomile_sd:
9801       Opc = X86ISD::UCOMI;
9802       CC = ISD::SETLE;
9803       break;
9804     case Intrinsic::x86_sse_ucomigt_ss:
9805     case Intrinsic::x86_sse2_ucomigt_sd:
9806       Opc = X86ISD::UCOMI;
9807       CC = ISD::SETGT;
9808       break;
9809     case Intrinsic::x86_sse_ucomige_ss:
9810     case Intrinsic::x86_sse2_ucomige_sd:
9811       Opc = X86ISD::UCOMI;
9812       CC = ISD::SETGE;
9813       break;
9814     case Intrinsic::x86_sse_ucomineq_ss:
9815     case Intrinsic::x86_sse2_ucomineq_sd:
9816       Opc = X86ISD::UCOMI;
9817       CC = ISD::SETNE;
9818       break;
9819     }
9820
9821     SDValue LHS = Op.getOperand(1);
9822     SDValue RHS = Op.getOperand(2);
9823     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9824     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9825     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9826     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9827                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9828     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9829   }
9830
9831   // Arithmetic intrinsics.
9832   case Intrinsic::x86_sse2_pmulu_dq:
9833   case Intrinsic::x86_avx2_pmulu_dq:
9834     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9835                        Op.getOperand(1), Op.getOperand(2));
9836
9837   // SSE3/AVX horizontal add/sub intrinsics
9838   case Intrinsic::x86_sse3_hadd_ps:
9839   case Intrinsic::x86_sse3_hadd_pd:
9840   case Intrinsic::x86_avx_hadd_ps_256:
9841   case Intrinsic::x86_avx_hadd_pd_256:
9842   case Intrinsic::x86_sse3_hsub_ps:
9843   case Intrinsic::x86_sse3_hsub_pd:
9844   case Intrinsic::x86_avx_hsub_ps_256:
9845   case Intrinsic::x86_avx_hsub_pd_256:
9846   case Intrinsic::x86_ssse3_phadd_w_128:
9847   case Intrinsic::x86_ssse3_phadd_d_128:
9848   case Intrinsic::x86_avx2_phadd_w:
9849   case Intrinsic::x86_avx2_phadd_d:
9850   case Intrinsic::x86_ssse3_phsub_w_128:
9851   case Intrinsic::x86_ssse3_phsub_d_128:
9852   case Intrinsic::x86_avx2_phsub_w:
9853   case Intrinsic::x86_avx2_phsub_d: {
9854     unsigned Opcode;
9855     switch (IntNo) {
9856     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9857     case Intrinsic::x86_sse3_hadd_ps:
9858     case Intrinsic::x86_sse3_hadd_pd:
9859     case Intrinsic::x86_avx_hadd_ps_256:
9860     case Intrinsic::x86_avx_hadd_pd_256:
9861       Opcode = X86ISD::FHADD;
9862       break;
9863     case Intrinsic::x86_sse3_hsub_ps:
9864     case Intrinsic::x86_sse3_hsub_pd:
9865     case Intrinsic::x86_avx_hsub_ps_256:
9866     case Intrinsic::x86_avx_hsub_pd_256:
9867       Opcode = X86ISD::FHSUB;
9868       break;
9869     case Intrinsic::x86_ssse3_phadd_w_128:
9870     case Intrinsic::x86_ssse3_phadd_d_128:
9871     case Intrinsic::x86_avx2_phadd_w:
9872     case Intrinsic::x86_avx2_phadd_d:
9873       Opcode = X86ISD::HADD;
9874       break;
9875     case Intrinsic::x86_ssse3_phsub_w_128:
9876     case Intrinsic::x86_ssse3_phsub_d_128:
9877     case Intrinsic::x86_avx2_phsub_w:
9878     case Intrinsic::x86_avx2_phsub_d:
9879       Opcode = X86ISD::HSUB;
9880       break;
9881     }
9882     return DAG.getNode(Opcode, dl, Op.getValueType(),
9883                        Op.getOperand(1), Op.getOperand(2));
9884   }
9885
9886   // AVX2 variable shift intrinsics
9887   case Intrinsic::x86_avx2_psllv_d:
9888   case Intrinsic::x86_avx2_psllv_q:
9889   case Intrinsic::x86_avx2_psllv_d_256:
9890   case Intrinsic::x86_avx2_psllv_q_256:
9891   case Intrinsic::x86_avx2_psrlv_d:
9892   case Intrinsic::x86_avx2_psrlv_q:
9893   case Intrinsic::x86_avx2_psrlv_d_256:
9894   case Intrinsic::x86_avx2_psrlv_q_256:
9895   case Intrinsic::x86_avx2_psrav_d:
9896   case Intrinsic::x86_avx2_psrav_d_256: {
9897     unsigned Opcode;
9898     switch (IntNo) {
9899     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9900     case Intrinsic::x86_avx2_psllv_d:
9901     case Intrinsic::x86_avx2_psllv_q:
9902     case Intrinsic::x86_avx2_psllv_d_256:
9903     case Intrinsic::x86_avx2_psllv_q_256:
9904       Opcode = ISD::SHL;
9905       break;
9906     case Intrinsic::x86_avx2_psrlv_d:
9907     case Intrinsic::x86_avx2_psrlv_q:
9908     case Intrinsic::x86_avx2_psrlv_d_256:
9909     case Intrinsic::x86_avx2_psrlv_q_256:
9910       Opcode = ISD::SRL;
9911       break;
9912     case Intrinsic::x86_avx2_psrav_d:
9913     case Intrinsic::x86_avx2_psrav_d_256:
9914       Opcode = ISD::SRA;
9915       break;
9916     }
9917     return DAG.getNode(Opcode, dl, Op.getValueType(),
9918                        Op.getOperand(1), Op.getOperand(2));
9919   }
9920
9921   case Intrinsic::x86_ssse3_pshuf_b_128:
9922   case Intrinsic::x86_avx2_pshuf_b:
9923     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9924                        Op.getOperand(1), Op.getOperand(2));
9925
9926   case Intrinsic::x86_ssse3_psign_b_128:
9927   case Intrinsic::x86_ssse3_psign_w_128:
9928   case Intrinsic::x86_ssse3_psign_d_128:
9929   case Intrinsic::x86_avx2_psign_b:
9930   case Intrinsic::x86_avx2_psign_w:
9931   case Intrinsic::x86_avx2_psign_d:
9932     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9933                        Op.getOperand(1), Op.getOperand(2));
9934
9935   case Intrinsic::x86_sse41_insertps:
9936     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9937                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9938
9939   case Intrinsic::x86_avx_vperm2f128_ps_256:
9940   case Intrinsic::x86_avx_vperm2f128_pd_256:
9941   case Intrinsic::x86_avx_vperm2f128_si_256:
9942   case Intrinsic::x86_avx2_vperm2i128:
9943     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9944                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9945
9946   case Intrinsic::x86_avx2_permd:
9947   case Intrinsic::x86_avx2_permps:
9948     // Operands intentionally swapped. Mask is last operand to intrinsic,
9949     // but second operand for node/intruction.
9950     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9951                        Op.getOperand(2), Op.getOperand(1));
9952
9953   // ptest and testp intrinsics. The intrinsic these come from are designed to
9954   // return an integer value, not just an instruction so lower it to the ptest
9955   // or testp pattern and a setcc for the result.
9956   case Intrinsic::x86_sse41_ptestz:
9957   case Intrinsic::x86_sse41_ptestc:
9958   case Intrinsic::x86_sse41_ptestnzc:
9959   case Intrinsic::x86_avx_ptestz_256:
9960   case Intrinsic::x86_avx_ptestc_256:
9961   case Intrinsic::x86_avx_ptestnzc_256:
9962   case Intrinsic::x86_avx_vtestz_ps:
9963   case Intrinsic::x86_avx_vtestc_ps:
9964   case Intrinsic::x86_avx_vtestnzc_ps:
9965   case Intrinsic::x86_avx_vtestz_pd:
9966   case Intrinsic::x86_avx_vtestc_pd:
9967   case Intrinsic::x86_avx_vtestnzc_pd:
9968   case Intrinsic::x86_avx_vtestz_ps_256:
9969   case Intrinsic::x86_avx_vtestc_ps_256:
9970   case Intrinsic::x86_avx_vtestnzc_ps_256:
9971   case Intrinsic::x86_avx_vtestz_pd_256:
9972   case Intrinsic::x86_avx_vtestc_pd_256:
9973   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9974     bool IsTestPacked = false;
9975     unsigned X86CC;
9976     switch (IntNo) {
9977     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9978     case Intrinsic::x86_avx_vtestz_ps:
9979     case Intrinsic::x86_avx_vtestz_pd:
9980     case Intrinsic::x86_avx_vtestz_ps_256:
9981     case Intrinsic::x86_avx_vtestz_pd_256:
9982       IsTestPacked = true; // Fallthrough
9983     case Intrinsic::x86_sse41_ptestz:
9984     case Intrinsic::x86_avx_ptestz_256:
9985       // ZF = 1
9986       X86CC = X86::COND_E;
9987       break;
9988     case Intrinsic::x86_avx_vtestc_ps:
9989     case Intrinsic::x86_avx_vtestc_pd:
9990     case Intrinsic::x86_avx_vtestc_ps_256:
9991     case Intrinsic::x86_avx_vtestc_pd_256:
9992       IsTestPacked = true; // Fallthrough
9993     case Intrinsic::x86_sse41_ptestc:
9994     case Intrinsic::x86_avx_ptestc_256:
9995       // CF = 1
9996       X86CC = X86::COND_B;
9997       break;
9998     case Intrinsic::x86_avx_vtestnzc_ps:
9999     case Intrinsic::x86_avx_vtestnzc_pd:
10000     case Intrinsic::x86_avx_vtestnzc_ps_256:
10001     case Intrinsic::x86_avx_vtestnzc_pd_256:
10002       IsTestPacked = true; // Fallthrough
10003     case Intrinsic::x86_sse41_ptestnzc:
10004     case Intrinsic::x86_avx_ptestnzc_256:
10005       // ZF and CF = 0
10006       X86CC = X86::COND_A;
10007       break;
10008     }
10009
10010     SDValue LHS = Op.getOperand(1);
10011     SDValue RHS = Op.getOperand(2);
10012     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10013     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10014     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10015     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10016     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10017   }
10018
10019   // SSE/AVX shift intrinsics
10020   case Intrinsic::x86_sse2_psll_w:
10021   case Intrinsic::x86_sse2_psll_d:
10022   case Intrinsic::x86_sse2_psll_q:
10023   case Intrinsic::x86_avx2_psll_w:
10024   case Intrinsic::x86_avx2_psll_d:
10025   case Intrinsic::x86_avx2_psll_q:
10026   case Intrinsic::x86_sse2_psrl_w:
10027   case Intrinsic::x86_sse2_psrl_d:
10028   case Intrinsic::x86_sse2_psrl_q:
10029   case Intrinsic::x86_avx2_psrl_w:
10030   case Intrinsic::x86_avx2_psrl_d:
10031   case Intrinsic::x86_avx2_psrl_q:
10032   case Intrinsic::x86_sse2_psra_w:
10033   case Intrinsic::x86_sse2_psra_d:
10034   case Intrinsic::x86_avx2_psra_w:
10035   case Intrinsic::x86_avx2_psra_d: {
10036     unsigned Opcode;
10037     switch (IntNo) {
10038     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10039     case Intrinsic::x86_sse2_psll_w:
10040     case Intrinsic::x86_sse2_psll_d:
10041     case Intrinsic::x86_sse2_psll_q:
10042     case Intrinsic::x86_avx2_psll_w:
10043     case Intrinsic::x86_avx2_psll_d:
10044     case Intrinsic::x86_avx2_psll_q:
10045       Opcode = X86ISD::VSHL;
10046       break;
10047     case Intrinsic::x86_sse2_psrl_w:
10048     case Intrinsic::x86_sse2_psrl_d:
10049     case Intrinsic::x86_sse2_psrl_q:
10050     case Intrinsic::x86_avx2_psrl_w:
10051     case Intrinsic::x86_avx2_psrl_d:
10052     case Intrinsic::x86_avx2_psrl_q:
10053       Opcode = X86ISD::VSRL;
10054       break;
10055     case Intrinsic::x86_sse2_psra_w:
10056     case Intrinsic::x86_sse2_psra_d:
10057     case Intrinsic::x86_avx2_psra_w:
10058     case Intrinsic::x86_avx2_psra_d:
10059       Opcode = X86ISD::VSRA;
10060       break;
10061     }
10062     return DAG.getNode(Opcode, dl, Op.getValueType(),
10063                        Op.getOperand(1), Op.getOperand(2));
10064   }
10065
10066   // SSE/AVX immediate shift intrinsics
10067   case Intrinsic::x86_sse2_pslli_w:
10068   case Intrinsic::x86_sse2_pslli_d:
10069   case Intrinsic::x86_sse2_pslli_q:
10070   case Intrinsic::x86_avx2_pslli_w:
10071   case Intrinsic::x86_avx2_pslli_d:
10072   case Intrinsic::x86_avx2_pslli_q:
10073   case Intrinsic::x86_sse2_psrli_w:
10074   case Intrinsic::x86_sse2_psrli_d:
10075   case Intrinsic::x86_sse2_psrli_q:
10076   case Intrinsic::x86_avx2_psrli_w:
10077   case Intrinsic::x86_avx2_psrli_d:
10078   case Intrinsic::x86_avx2_psrli_q:
10079   case Intrinsic::x86_sse2_psrai_w:
10080   case Intrinsic::x86_sse2_psrai_d:
10081   case Intrinsic::x86_avx2_psrai_w:
10082   case Intrinsic::x86_avx2_psrai_d: {
10083     unsigned Opcode;
10084     switch (IntNo) {
10085     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10086     case Intrinsic::x86_sse2_pslli_w:
10087     case Intrinsic::x86_sse2_pslli_d:
10088     case Intrinsic::x86_sse2_pslli_q:
10089     case Intrinsic::x86_avx2_pslli_w:
10090     case Intrinsic::x86_avx2_pslli_d:
10091     case Intrinsic::x86_avx2_pslli_q:
10092       Opcode = X86ISD::VSHLI;
10093       break;
10094     case Intrinsic::x86_sse2_psrli_w:
10095     case Intrinsic::x86_sse2_psrli_d:
10096     case Intrinsic::x86_sse2_psrli_q:
10097     case Intrinsic::x86_avx2_psrli_w:
10098     case Intrinsic::x86_avx2_psrli_d:
10099     case Intrinsic::x86_avx2_psrli_q:
10100       Opcode = X86ISD::VSRLI;
10101       break;
10102     case Intrinsic::x86_sse2_psrai_w:
10103     case Intrinsic::x86_sse2_psrai_d:
10104     case Intrinsic::x86_avx2_psrai_w:
10105     case Intrinsic::x86_avx2_psrai_d:
10106       Opcode = X86ISD::VSRAI;
10107       break;
10108     }
10109     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10110                                Op.getOperand(1), Op.getOperand(2), DAG);
10111   }
10112
10113   case Intrinsic::x86_sse42_pcmpistria128:
10114   case Intrinsic::x86_sse42_pcmpestria128:
10115   case Intrinsic::x86_sse42_pcmpistric128:
10116   case Intrinsic::x86_sse42_pcmpestric128:
10117   case Intrinsic::x86_sse42_pcmpistrio128:
10118   case Intrinsic::x86_sse42_pcmpestrio128:
10119   case Intrinsic::x86_sse42_pcmpistris128:
10120   case Intrinsic::x86_sse42_pcmpestris128:
10121   case Intrinsic::x86_sse42_pcmpistriz128:
10122   case Intrinsic::x86_sse42_pcmpestriz128: {
10123     unsigned Opcode;
10124     unsigned X86CC;
10125     switch (IntNo) {
10126     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10127     case Intrinsic::x86_sse42_pcmpistria128:
10128       Opcode = X86ISD::PCMPISTRI;
10129       X86CC = X86::COND_A;
10130       break;
10131     case Intrinsic::x86_sse42_pcmpestria128:
10132       Opcode = X86ISD::PCMPESTRI;
10133       X86CC = X86::COND_A;
10134       break;
10135     case Intrinsic::x86_sse42_pcmpistric128:
10136       Opcode = X86ISD::PCMPISTRI;
10137       X86CC = X86::COND_B;
10138       break;
10139     case Intrinsic::x86_sse42_pcmpestric128:
10140       Opcode = X86ISD::PCMPESTRI;
10141       X86CC = X86::COND_B;
10142       break;
10143     case Intrinsic::x86_sse42_pcmpistrio128:
10144       Opcode = X86ISD::PCMPISTRI;
10145       X86CC = X86::COND_O;
10146       break;
10147     case Intrinsic::x86_sse42_pcmpestrio128:
10148       Opcode = X86ISD::PCMPESTRI;
10149       X86CC = X86::COND_O;
10150       break;
10151     case Intrinsic::x86_sse42_pcmpistris128:
10152       Opcode = X86ISD::PCMPISTRI;
10153       X86CC = X86::COND_S;
10154       break;
10155     case Intrinsic::x86_sse42_pcmpestris128:
10156       Opcode = X86ISD::PCMPESTRI;
10157       X86CC = X86::COND_S;
10158       break;
10159     case Intrinsic::x86_sse42_pcmpistriz128:
10160       Opcode = X86ISD::PCMPISTRI;
10161       X86CC = X86::COND_E;
10162       break;
10163     case Intrinsic::x86_sse42_pcmpestriz128:
10164       Opcode = X86ISD::PCMPESTRI;
10165       X86CC = X86::COND_E;
10166       break;
10167     }
10168     SmallVector<SDValue, 5> NewOps;
10169     NewOps.append(Op->op_begin()+1, Op->op_end());
10170     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10171     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10172     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10173                                 DAG.getConstant(X86CC, MVT::i8),
10174                                 SDValue(PCMP.getNode(), 1));
10175     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10176   }
10177
10178   case Intrinsic::x86_sse42_pcmpistri128:
10179   case Intrinsic::x86_sse42_pcmpestri128: {
10180     unsigned Opcode;
10181     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10182       Opcode = X86ISD::PCMPISTRI;
10183     else
10184       Opcode = X86ISD::PCMPESTRI;
10185
10186     SmallVector<SDValue, 5> NewOps;
10187     NewOps.append(Op->op_begin()+1, Op->op_end());
10188     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10189     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10190   }
10191   case Intrinsic::x86_fma_vfmadd_ps:
10192   case Intrinsic::x86_fma_vfmadd_pd:
10193   case Intrinsic::x86_fma_vfmsub_ps:
10194   case Intrinsic::x86_fma_vfmsub_pd:
10195   case Intrinsic::x86_fma_vfnmadd_ps:
10196   case Intrinsic::x86_fma_vfnmadd_pd:
10197   case Intrinsic::x86_fma_vfnmsub_ps:
10198   case Intrinsic::x86_fma_vfnmsub_pd:
10199   case Intrinsic::x86_fma_vfmaddsub_ps:
10200   case Intrinsic::x86_fma_vfmaddsub_pd:
10201   case Intrinsic::x86_fma_vfmsubadd_ps:
10202   case Intrinsic::x86_fma_vfmsubadd_pd:
10203   case Intrinsic::x86_fma_vfmadd_ps_256:
10204   case Intrinsic::x86_fma_vfmadd_pd_256:
10205   case Intrinsic::x86_fma_vfmsub_ps_256:
10206   case Intrinsic::x86_fma_vfmsub_pd_256:
10207   case Intrinsic::x86_fma_vfnmadd_ps_256:
10208   case Intrinsic::x86_fma_vfnmadd_pd_256:
10209   case Intrinsic::x86_fma_vfnmsub_ps_256:
10210   case Intrinsic::x86_fma_vfnmsub_pd_256:
10211   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10212   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10213   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10214   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10215     unsigned Opc;
10216     switch (IntNo) {
10217     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10218     case Intrinsic::x86_fma_vfmadd_ps:
10219     case Intrinsic::x86_fma_vfmadd_pd:
10220     case Intrinsic::x86_fma_vfmadd_ps_256:
10221     case Intrinsic::x86_fma_vfmadd_pd_256:
10222       Opc = X86ISD::FMADD;
10223       break;
10224     case Intrinsic::x86_fma_vfmsub_ps:
10225     case Intrinsic::x86_fma_vfmsub_pd:
10226     case Intrinsic::x86_fma_vfmsub_ps_256:
10227     case Intrinsic::x86_fma_vfmsub_pd_256:
10228       Opc = X86ISD::FMSUB;
10229       break;
10230     case Intrinsic::x86_fma_vfnmadd_ps:
10231     case Intrinsic::x86_fma_vfnmadd_pd:
10232     case Intrinsic::x86_fma_vfnmadd_ps_256:
10233     case Intrinsic::x86_fma_vfnmadd_pd_256:
10234       Opc = X86ISD::FNMADD;
10235       break;
10236     case Intrinsic::x86_fma_vfnmsub_ps:
10237     case Intrinsic::x86_fma_vfnmsub_pd:
10238     case Intrinsic::x86_fma_vfnmsub_ps_256:
10239     case Intrinsic::x86_fma_vfnmsub_pd_256:
10240       Opc = X86ISD::FNMSUB;
10241       break;
10242     case Intrinsic::x86_fma_vfmaddsub_ps:
10243     case Intrinsic::x86_fma_vfmaddsub_pd:
10244     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10245     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10246       Opc = X86ISD::FMADDSUB;
10247       break;
10248     case Intrinsic::x86_fma_vfmsubadd_ps:
10249     case Intrinsic::x86_fma_vfmsubadd_pd:
10250     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10251     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10252       Opc = X86ISD::FMSUBADD;
10253       break;
10254     }
10255
10256     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10257                        Op.getOperand(2), Op.getOperand(3));
10258   }
10259   }
10260 }
10261
10262 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10263   DebugLoc dl = Op.getDebugLoc();
10264   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10265   switch (IntNo) {
10266   default: return SDValue();    // Don't custom lower most intrinsics.
10267
10268   // RDRAND intrinsics.
10269   case Intrinsic::x86_rdrand_16:
10270   case Intrinsic::x86_rdrand_32:
10271   case Intrinsic::x86_rdrand_64: {
10272     // Emit the node with the right value type.
10273     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10274     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10275
10276     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10277     // return the value from Rand, which is always 0, casted to i32.
10278     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10279                       DAG.getConstant(1, Op->getValueType(1)),
10280                       DAG.getConstant(X86::COND_B, MVT::i32),
10281                       SDValue(Result.getNode(), 1) };
10282     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10283                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10284                                   Ops, 4);
10285
10286     // Return { result, isValid, chain }.
10287     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10288                        SDValue(Result.getNode(), 2));
10289   }
10290   }
10291 }
10292
10293 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10294                                            SelectionDAG &DAG) const {
10295   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10296   MFI->setReturnAddressIsTaken(true);
10297
10298   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10299   DebugLoc dl = Op.getDebugLoc();
10300
10301   if (Depth > 0) {
10302     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10303     SDValue Offset =
10304       DAG.getConstant(TD->getPointerSize(0),
10305                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10306     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10307                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10308                                    FrameAddr, Offset),
10309                        MachinePointerInfo(), false, false, false, 0);
10310   }
10311
10312   // Just load the return address.
10313   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10314   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10315                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10316 }
10317
10318 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10319   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10320   MFI->setFrameAddressIsTaken(true);
10321
10322   EVT VT = Op.getValueType();
10323   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10324   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10325   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10326   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10327   while (Depth--)
10328     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10329                             MachinePointerInfo(),
10330                             false, false, false, 0);
10331   return FrameAddr;
10332 }
10333
10334 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10335                                                      SelectionDAG &DAG) const {
10336   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10337 }
10338
10339 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10340   SDValue Chain     = Op.getOperand(0);
10341   SDValue Offset    = Op.getOperand(1);
10342   SDValue Handler   = Op.getOperand(2);
10343   DebugLoc dl       = Op.getDebugLoc();
10344
10345   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10346                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10347                                      getPointerTy());
10348   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10349
10350   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10351                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10352   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10353   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10354                        false, false, 0);
10355   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10356
10357   return DAG.getNode(X86ISD::EH_RETURN, dl,
10358                      MVT::Other,
10359                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10360 }
10361
10362 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10363                                                SelectionDAG &DAG) const {
10364   DebugLoc DL = Op.getDebugLoc();
10365   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10366                      DAG.getVTList(MVT::i32, MVT::Other),
10367                      Op.getOperand(0), Op.getOperand(1));
10368 }
10369
10370 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10371                                                 SelectionDAG &DAG) const {
10372   DebugLoc DL = Op.getDebugLoc();
10373   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10374                      Op.getOperand(0), Op.getOperand(1));
10375 }
10376
10377 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10378   return Op.getOperand(0);
10379 }
10380
10381 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10382                                                 SelectionDAG &DAG) const {
10383   SDValue Root = Op.getOperand(0);
10384   SDValue Trmp = Op.getOperand(1); // trampoline
10385   SDValue FPtr = Op.getOperand(2); // nested function
10386   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10387   DebugLoc dl  = Op.getDebugLoc();
10388
10389   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10390   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10391
10392   if (Subtarget->is64Bit()) {
10393     SDValue OutChains[6];
10394
10395     // Large code-model.
10396     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10397     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10398
10399     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10400     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10401
10402     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10403
10404     // Load the pointer to the nested function into R11.
10405     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10406     SDValue Addr = Trmp;
10407     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10408                                 Addr, MachinePointerInfo(TrmpAddr),
10409                                 false, false, 0);
10410
10411     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10412                        DAG.getConstant(2, MVT::i64));
10413     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10414                                 MachinePointerInfo(TrmpAddr, 2),
10415                                 false, false, 2);
10416
10417     // Load the 'nest' parameter value into R10.
10418     // R10 is specified in X86CallingConv.td
10419     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10420     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10421                        DAG.getConstant(10, MVT::i64));
10422     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10423                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10424                                 false, false, 0);
10425
10426     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10427                        DAG.getConstant(12, MVT::i64));
10428     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10429                                 MachinePointerInfo(TrmpAddr, 12),
10430                                 false, false, 2);
10431
10432     // Jump to the nested function.
10433     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10434     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10435                        DAG.getConstant(20, MVT::i64));
10436     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10437                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10438                                 false, false, 0);
10439
10440     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10441     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10442                        DAG.getConstant(22, MVT::i64));
10443     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10444                                 MachinePointerInfo(TrmpAddr, 22),
10445                                 false, false, 0);
10446
10447     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10448   } else {
10449     const Function *Func =
10450       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10451     CallingConv::ID CC = Func->getCallingConv();
10452     unsigned NestReg;
10453
10454     switch (CC) {
10455     default:
10456       llvm_unreachable("Unsupported calling convention");
10457     case CallingConv::C:
10458     case CallingConv::X86_StdCall: {
10459       // Pass 'nest' parameter in ECX.
10460       // Must be kept in sync with X86CallingConv.td
10461       NestReg = X86::ECX;
10462
10463       // Check that ECX wasn't needed by an 'inreg' parameter.
10464       FunctionType *FTy = Func->getFunctionType();
10465       const AttrListPtr &Attrs = Func->getAttributes();
10466
10467       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10468         unsigned InRegCount = 0;
10469         unsigned Idx = 1;
10470
10471         for (FunctionType::param_iterator I = FTy->param_begin(),
10472              E = FTy->param_end(); I != E; ++I, ++Idx)
10473           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10474             // FIXME: should only count parameters that are lowered to integers.
10475             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10476
10477         if (InRegCount > 2) {
10478           report_fatal_error("Nest register in use - reduce number of inreg"
10479                              " parameters!");
10480         }
10481       }
10482       break;
10483     }
10484     case CallingConv::X86_FastCall:
10485     case CallingConv::X86_ThisCall:
10486     case CallingConv::Fast:
10487       // Pass 'nest' parameter in EAX.
10488       // Must be kept in sync with X86CallingConv.td
10489       NestReg = X86::EAX;
10490       break;
10491     }
10492
10493     SDValue OutChains[4];
10494     SDValue Addr, Disp;
10495
10496     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10497                        DAG.getConstant(10, MVT::i32));
10498     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10499
10500     // This is storing the opcode for MOV32ri.
10501     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10502     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10503     OutChains[0] = DAG.getStore(Root, dl,
10504                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10505                                 Trmp, MachinePointerInfo(TrmpAddr),
10506                                 false, false, 0);
10507
10508     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10509                        DAG.getConstant(1, MVT::i32));
10510     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10511                                 MachinePointerInfo(TrmpAddr, 1),
10512                                 false, false, 1);
10513
10514     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10515     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10516                        DAG.getConstant(5, MVT::i32));
10517     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10518                                 MachinePointerInfo(TrmpAddr, 5),
10519                                 false, false, 1);
10520
10521     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10522                        DAG.getConstant(6, MVT::i32));
10523     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10524                                 MachinePointerInfo(TrmpAddr, 6),
10525                                 false, false, 1);
10526
10527     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10528   }
10529 }
10530
10531 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10532                                             SelectionDAG &DAG) const {
10533   /*
10534    The rounding mode is in bits 11:10 of FPSR, and has the following
10535    settings:
10536      00 Round to nearest
10537      01 Round to -inf
10538      10 Round to +inf
10539      11 Round to 0
10540
10541   FLT_ROUNDS, on the other hand, expects the following:
10542     -1 Undefined
10543      0 Round to 0
10544      1 Round to nearest
10545      2 Round to +inf
10546      3 Round to -inf
10547
10548   To perform the conversion, we do:
10549     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10550   */
10551
10552   MachineFunction &MF = DAG.getMachineFunction();
10553   const TargetMachine &TM = MF.getTarget();
10554   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10555   unsigned StackAlignment = TFI.getStackAlignment();
10556   EVT VT = Op.getValueType();
10557   DebugLoc DL = Op.getDebugLoc();
10558
10559   // Save FP Control Word to stack slot
10560   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10561   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10562
10563
10564   MachineMemOperand *MMO =
10565    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10566                            MachineMemOperand::MOStore, 2, 2);
10567
10568   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10569   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10570                                           DAG.getVTList(MVT::Other),
10571                                           Ops, 2, MVT::i16, MMO);
10572
10573   // Load FP Control Word from stack slot
10574   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10575                             MachinePointerInfo(), false, false, false, 0);
10576
10577   // Transform as necessary
10578   SDValue CWD1 =
10579     DAG.getNode(ISD::SRL, DL, MVT::i16,
10580                 DAG.getNode(ISD::AND, DL, MVT::i16,
10581                             CWD, DAG.getConstant(0x800, MVT::i16)),
10582                 DAG.getConstant(11, MVT::i8));
10583   SDValue CWD2 =
10584     DAG.getNode(ISD::SRL, DL, MVT::i16,
10585                 DAG.getNode(ISD::AND, DL, MVT::i16,
10586                             CWD, DAG.getConstant(0x400, MVT::i16)),
10587                 DAG.getConstant(9, MVT::i8));
10588
10589   SDValue RetVal =
10590     DAG.getNode(ISD::AND, DL, MVT::i16,
10591                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10592                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10593                             DAG.getConstant(1, MVT::i16)),
10594                 DAG.getConstant(3, MVT::i16));
10595
10596
10597   return DAG.getNode((VT.getSizeInBits() < 16 ?
10598                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10599 }
10600
10601 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10602   EVT VT = Op.getValueType();
10603   EVT OpVT = VT;
10604   unsigned NumBits = VT.getSizeInBits();
10605   DebugLoc dl = Op.getDebugLoc();
10606
10607   Op = Op.getOperand(0);
10608   if (VT == MVT::i8) {
10609     // Zero extend to i32 since there is not an i8 bsr.
10610     OpVT = MVT::i32;
10611     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10612   }
10613
10614   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10615   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10616   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10617
10618   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10619   SDValue Ops[] = {
10620     Op,
10621     DAG.getConstant(NumBits+NumBits-1, OpVT),
10622     DAG.getConstant(X86::COND_E, MVT::i8),
10623     Op.getValue(1)
10624   };
10625   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10626
10627   // Finally xor with NumBits-1.
10628   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10629
10630   if (VT == MVT::i8)
10631     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10632   return Op;
10633 }
10634
10635 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10636   EVT VT = Op.getValueType();
10637   EVT OpVT = VT;
10638   unsigned NumBits = VT.getSizeInBits();
10639   DebugLoc dl = Op.getDebugLoc();
10640
10641   Op = Op.getOperand(0);
10642   if (VT == MVT::i8) {
10643     // Zero extend to i32 since there is not an i8 bsr.
10644     OpVT = MVT::i32;
10645     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10646   }
10647
10648   // Issue a bsr (scan bits in reverse).
10649   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10650   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10651
10652   // And xor with NumBits-1.
10653   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10654
10655   if (VT == MVT::i8)
10656     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10657   return Op;
10658 }
10659
10660 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10661   EVT VT = Op.getValueType();
10662   unsigned NumBits = VT.getSizeInBits();
10663   DebugLoc dl = Op.getDebugLoc();
10664   Op = Op.getOperand(0);
10665
10666   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10667   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10668   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10669
10670   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10671   SDValue Ops[] = {
10672     Op,
10673     DAG.getConstant(NumBits, VT),
10674     DAG.getConstant(X86::COND_E, MVT::i8),
10675     Op.getValue(1)
10676   };
10677   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10678 }
10679
10680 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10681 // ones, and then concatenate the result back.
10682 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10683   EVT VT = Op.getValueType();
10684
10685   assert(VT.is256BitVector() && VT.isInteger() &&
10686          "Unsupported value type for operation");
10687
10688   unsigned NumElems = VT.getVectorNumElements();
10689   DebugLoc dl = Op.getDebugLoc();
10690
10691   // Extract the LHS vectors
10692   SDValue LHS = Op.getOperand(0);
10693   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10694   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10695
10696   // Extract the RHS vectors
10697   SDValue RHS = Op.getOperand(1);
10698   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10699   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10700
10701   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10702   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10703
10704   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10705                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10706                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10707 }
10708
10709 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10710   assert(Op.getValueType().is256BitVector() &&
10711          Op.getValueType().isInteger() &&
10712          "Only handle AVX 256-bit vector integer operation");
10713   return Lower256IntArith(Op, DAG);
10714 }
10715
10716 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10717   assert(Op.getValueType().is256BitVector() &&
10718          Op.getValueType().isInteger() &&
10719          "Only handle AVX 256-bit vector integer operation");
10720   return Lower256IntArith(Op, DAG);
10721 }
10722
10723 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10724                         SelectionDAG &DAG) {
10725   EVT VT = Op.getValueType();
10726
10727   // Decompose 256-bit ops into smaller 128-bit ops.
10728   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10729     return Lower256IntArith(Op, DAG);
10730
10731   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10732          "Only know how to lower V2I64/V4I64 multiply");
10733
10734   DebugLoc dl = Op.getDebugLoc();
10735
10736   //  Ahi = psrlqi(a, 32);
10737   //  Bhi = psrlqi(b, 32);
10738   //
10739   //  AloBlo = pmuludq(a, b);
10740   //  AloBhi = pmuludq(a, Bhi);
10741   //  AhiBlo = pmuludq(Ahi, b);
10742
10743   //  AloBhi = psllqi(AloBhi, 32);
10744   //  AhiBlo = psllqi(AhiBlo, 32);
10745   //  return AloBlo + AloBhi + AhiBlo;
10746
10747   SDValue A = Op.getOperand(0);
10748   SDValue B = Op.getOperand(1);
10749
10750   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10751
10752   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10753   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10754
10755   // Bit cast to 32-bit vectors for MULUDQ
10756   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10757   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10758   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10759   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10760   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10761
10762   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10763   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10764   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10765
10766   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10767   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10768
10769   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10770   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10771 }
10772
10773 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10774
10775   EVT VT = Op.getValueType();
10776   DebugLoc dl = Op.getDebugLoc();
10777   SDValue R = Op.getOperand(0);
10778   SDValue Amt = Op.getOperand(1);
10779   LLVMContext *Context = DAG.getContext();
10780
10781   if (!Subtarget->hasSSE2())
10782     return SDValue();
10783
10784   // Optimize shl/srl/sra with constant shift amount.
10785   if (isSplatVector(Amt.getNode())) {
10786     SDValue SclrAmt = Amt->getOperand(0);
10787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10788       uint64_t ShiftAmt = C->getZExtValue();
10789
10790       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10791           (Subtarget->hasAVX2() &&
10792            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10793         if (Op.getOpcode() == ISD::SHL)
10794           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10795                              DAG.getConstant(ShiftAmt, MVT::i32));
10796         if (Op.getOpcode() == ISD::SRL)
10797           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10798                              DAG.getConstant(ShiftAmt, MVT::i32));
10799         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10800           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10801                              DAG.getConstant(ShiftAmt, MVT::i32));
10802       }
10803
10804       if (VT == MVT::v16i8) {
10805         if (Op.getOpcode() == ISD::SHL) {
10806           // Make a large shift.
10807           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10808                                     DAG.getConstant(ShiftAmt, MVT::i32));
10809           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10810           // Zero out the rightmost bits.
10811           SmallVector<SDValue, 16> V(16,
10812                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10813                                                      MVT::i8));
10814           return DAG.getNode(ISD::AND, dl, VT, SHL,
10815                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10816         }
10817         if (Op.getOpcode() == ISD::SRL) {
10818           // Make a large shift.
10819           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10820                                     DAG.getConstant(ShiftAmt, MVT::i32));
10821           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10822           // Zero out the leftmost bits.
10823           SmallVector<SDValue, 16> V(16,
10824                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10825                                                      MVT::i8));
10826           return DAG.getNode(ISD::AND, dl, VT, SRL,
10827                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10828         }
10829         if (Op.getOpcode() == ISD::SRA) {
10830           if (ShiftAmt == 7) {
10831             // R s>> 7  ===  R s< 0
10832             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10833             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10834           }
10835
10836           // R s>> a === ((R u>> a) ^ m) - m
10837           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10838           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10839                                                          MVT::i8));
10840           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10841           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10842           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10843           return Res;
10844         }
10845         llvm_unreachable("Unknown shift opcode.");
10846       }
10847
10848       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10849         if (Op.getOpcode() == ISD::SHL) {
10850           // Make a large shift.
10851           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10852                                     DAG.getConstant(ShiftAmt, MVT::i32));
10853           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10854           // Zero out the rightmost bits.
10855           SmallVector<SDValue, 32> V(32,
10856                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10857                                                      MVT::i8));
10858           return DAG.getNode(ISD::AND, dl, VT, SHL,
10859                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10860         }
10861         if (Op.getOpcode() == ISD::SRL) {
10862           // Make a large shift.
10863           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10864                                     DAG.getConstant(ShiftAmt, MVT::i32));
10865           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10866           // Zero out the leftmost bits.
10867           SmallVector<SDValue, 32> V(32,
10868                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10869                                                      MVT::i8));
10870           return DAG.getNode(ISD::AND, dl, VT, SRL,
10871                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10872         }
10873         if (Op.getOpcode() == ISD::SRA) {
10874           if (ShiftAmt == 7) {
10875             // R s>> 7  ===  R s< 0
10876             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10877             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10878           }
10879
10880           // R s>> a === ((R u>> a) ^ m) - m
10881           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10882           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10883                                                          MVT::i8));
10884           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10885           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10886           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10887           return Res;
10888         }
10889         llvm_unreachable("Unknown shift opcode.");
10890       }
10891     }
10892   }
10893
10894   // Lower SHL with variable shift amount.
10895   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10896     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10897                      DAG.getConstant(23, MVT::i32));
10898
10899     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10900     Constant *C = ConstantDataVector::get(*Context, CV);
10901     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10902     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10903                                  MachinePointerInfo::getConstantPool(),
10904                                  false, false, false, 16);
10905
10906     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10907     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10908     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10909     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10910   }
10911   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10912     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10913
10914     // a = a << 5;
10915     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10916                      DAG.getConstant(5, MVT::i32));
10917     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10918
10919     // Turn 'a' into a mask suitable for VSELECT
10920     SDValue VSelM = DAG.getConstant(0x80, VT);
10921     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10922     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10923
10924     SDValue CM1 = DAG.getConstant(0x0f, VT);
10925     SDValue CM2 = DAG.getConstant(0x3f, VT);
10926
10927     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10928     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10929     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10930                             DAG.getConstant(4, MVT::i32), DAG);
10931     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10932     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10933
10934     // a += a
10935     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10936     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10937     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10938
10939     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10940     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10941     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10942                             DAG.getConstant(2, MVT::i32), DAG);
10943     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10944     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10945
10946     // a += a
10947     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10948     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10949     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10950
10951     // return VSELECT(r, r+r, a);
10952     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10953                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10954     return R;
10955   }
10956
10957   // Decompose 256-bit shifts into smaller 128-bit shifts.
10958   if (VT.is256BitVector()) {
10959     unsigned NumElems = VT.getVectorNumElements();
10960     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10961     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10962
10963     // Extract the two vectors
10964     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10965     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10966
10967     // Recreate the shift amount vectors
10968     SDValue Amt1, Amt2;
10969     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10970       // Constant shift amount
10971       SmallVector<SDValue, 4> Amt1Csts;
10972       SmallVector<SDValue, 4> Amt2Csts;
10973       for (unsigned i = 0; i != NumElems/2; ++i)
10974         Amt1Csts.push_back(Amt->getOperand(i));
10975       for (unsigned i = NumElems/2; i != NumElems; ++i)
10976         Amt2Csts.push_back(Amt->getOperand(i));
10977
10978       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10979                                  &Amt1Csts[0], NumElems/2);
10980       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10981                                  &Amt2Csts[0], NumElems/2);
10982     } else {
10983       // Variable shift amount
10984       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10985       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10986     }
10987
10988     // Issue new vector shifts for the smaller types
10989     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10990     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10991
10992     // Concatenate the result back
10993     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10994   }
10995
10996   return SDValue();
10997 }
10998
10999 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11000   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11001   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11002   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11003   // has only one use.
11004   SDNode *N = Op.getNode();
11005   SDValue LHS = N->getOperand(0);
11006   SDValue RHS = N->getOperand(1);
11007   unsigned BaseOp = 0;
11008   unsigned Cond = 0;
11009   DebugLoc DL = Op.getDebugLoc();
11010   switch (Op.getOpcode()) {
11011   default: llvm_unreachable("Unknown ovf instruction!");
11012   case ISD::SADDO:
11013     // A subtract of one will be selected as a INC. Note that INC doesn't
11014     // set CF, so we can't do this for UADDO.
11015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11016       if (C->isOne()) {
11017         BaseOp = X86ISD::INC;
11018         Cond = X86::COND_O;
11019         break;
11020       }
11021     BaseOp = X86ISD::ADD;
11022     Cond = X86::COND_O;
11023     break;
11024   case ISD::UADDO:
11025     BaseOp = X86ISD::ADD;
11026     Cond = X86::COND_B;
11027     break;
11028   case ISD::SSUBO:
11029     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11030     // set CF, so we can't do this for USUBO.
11031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11032       if (C->isOne()) {
11033         BaseOp = X86ISD::DEC;
11034         Cond = X86::COND_O;
11035         break;
11036       }
11037     BaseOp = X86ISD::SUB;
11038     Cond = X86::COND_O;
11039     break;
11040   case ISD::USUBO:
11041     BaseOp = X86ISD::SUB;
11042     Cond = X86::COND_B;
11043     break;
11044   case ISD::SMULO:
11045     BaseOp = X86ISD::SMUL;
11046     Cond = X86::COND_O;
11047     break;
11048   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11049     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11050                                  MVT::i32);
11051     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11052
11053     SDValue SetCC =
11054       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11055                   DAG.getConstant(X86::COND_O, MVT::i32),
11056                   SDValue(Sum.getNode(), 2));
11057
11058     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11059   }
11060   }
11061
11062   // Also sets EFLAGS.
11063   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11064   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11065
11066   SDValue SetCC =
11067     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11068                 DAG.getConstant(Cond, MVT::i32),
11069                 SDValue(Sum.getNode(), 1));
11070
11071   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11072 }
11073
11074 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11075                                                   SelectionDAG &DAG) const {
11076   DebugLoc dl = Op.getDebugLoc();
11077   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11078   EVT VT = Op.getValueType();
11079
11080   if (!Subtarget->hasSSE2() || !VT.isVector())
11081     return SDValue();
11082
11083   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11084                       ExtraVT.getScalarType().getSizeInBits();
11085   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11086
11087   switch (VT.getSimpleVT().SimpleTy) {
11088     default: return SDValue();
11089     case MVT::v8i32:
11090     case MVT::v16i16:
11091       if (!Subtarget->hasAVX())
11092         return SDValue();
11093       if (!Subtarget->hasAVX2()) {
11094         // needs to be split
11095         unsigned NumElems = VT.getVectorNumElements();
11096
11097         // Extract the LHS vectors
11098         SDValue LHS = Op.getOperand(0);
11099         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11100         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11101
11102         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11103         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11104
11105         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11106         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11107         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11108                                    ExtraNumElems/2);
11109         SDValue Extra = DAG.getValueType(ExtraVT);
11110
11111         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11112         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11113
11114         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11115       }
11116       // fall through
11117     case MVT::v4i32:
11118     case MVT::v8i16: {
11119       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11120                                          Op.getOperand(0), ShAmt, DAG);
11121       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11122     }
11123   }
11124 }
11125
11126
11127 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11128                               SelectionDAG &DAG) {
11129   DebugLoc dl = Op.getDebugLoc();
11130
11131   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11132   // There isn't any reason to disable it if the target processor supports it.
11133   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11134     SDValue Chain = Op.getOperand(0);
11135     SDValue Zero = DAG.getConstant(0, MVT::i32);
11136     SDValue Ops[] = {
11137       DAG.getRegister(X86::ESP, MVT::i32), // Base
11138       DAG.getTargetConstant(1, MVT::i8),   // Scale
11139       DAG.getRegister(0, MVT::i32),        // Index
11140       DAG.getTargetConstant(0, MVT::i32),  // Disp
11141       DAG.getRegister(0, MVT::i32),        // Segment.
11142       Zero,
11143       Chain
11144     };
11145     SDNode *Res =
11146       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11147                           array_lengthof(Ops));
11148     return SDValue(Res, 0);
11149   }
11150
11151   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11152   if (!isDev)
11153     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11154
11155   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11156   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11157   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11158   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11159
11160   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11161   if (!Op1 && !Op2 && !Op3 && Op4)
11162     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11163
11164   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11165   if (Op1 && !Op2 && !Op3 && !Op4)
11166     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11167
11168   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11169   //           (MFENCE)>;
11170   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11171 }
11172
11173 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11174                                  SelectionDAG &DAG) {
11175   DebugLoc dl = Op.getDebugLoc();
11176   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11177     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11178   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11179     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11180
11181   // The only fence that needs an instruction is a sequentially-consistent
11182   // cross-thread fence.
11183   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11184     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11185     // no-sse2). There isn't any reason to disable it if the target processor
11186     // supports it.
11187     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11188       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11189
11190     SDValue Chain = Op.getOperand(0);
11191     SDValue Zero = DAG.getConstant(0, MVT::i32);
11192     SDValue Ops[] = {
11193       DAG.getRegister(X86::ESP, MVT::i32), // Base
11194       DAG.getTargetConstant(1, MVT::i8),   // Scale
11195       DAG.getRegister(0, MVT::i32),        // Index
11196       DAG.getTargetConstant(0, MVT::i32),  // Disp
11197       DAG.getRegister(0, MVT::i32),        // Segment.
11198       Zero,
11199       Chain
11200     };
11201     SDNode *Res =
11202       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11203                          array_lengthof(Ops));
11204     return SDValue(Res, 0);
11205   }
11206
11207   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11208   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11209 }
11210
11211
11212 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11213                              SelectionDAG &DAG) {
11214   EVT T = Op.getValueType();
11215   DebugLoc DL = Op.getDebugLoc();
11216   unsigned Reg = 0;
11217   unsigned size = 0;
11218   switch(T.getSimpleVT().SimpleTy) {
11219   default: llvm_unreachable("Invalid value type!");
11220   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11221   case MVT::i16: Reg = X86::AX;  size = 2; break;
11222   case MVT::i32: Reg = X86::EAX; size = 4; break;
11223   case MVT::i64:
11224     assert(Subtarget->is64Bit() && "Node not type legal!");
11225     Reg = X86::RAX; size = 8;
11226     break;
11227   }
11228   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11229                                     Op.getOperand(2), SDValue());
11230   SDValue Ops[] = { cpIn.getValue(0),
11231                     Op.getOperand(1),
11232                     Op.getOperand(3),
11233                     DAG.getTargetConstant(size, MVT::i8),
11234                     cpIn.getValue(1) };
11235   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11236   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11237   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11238                                            Ops, 5, T, MMO);
11239   SDValue cpOut =
11240     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11241   return cpOut;
11242 }
11243
11244 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11245                                      SelectionDAG &DAG) {
11246   assert(Subtarget->is64Bit() && "Result not type legalized?");
11247   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11248   SDValue TheChain = Op.getOperand(0);
11249   DebugLoc dl = Op.getDebugLoc();
11250   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11251   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11252   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11253                                    rax.getValue(2));
11254   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11255                             DAG.getConstant(32, MVT::i8));
11256   SDValue Ops[] = {
11257     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11258     rdx.getValue(1)
11259   };
11260   return DAG.getMergeValues(Ops, 2, dl);
11261 }
11262
11263 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11264   EVT SrcVT = Op.getOperand(0).getValueType();
11265   EVT DstVT = Op.getValueType();
11266   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11267          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11268   assert((DstVT == MVT::i64 ||
11269           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11270          "Unexpected custom BITCAST");
11271   // i64 <=> MMX conversions are Legal.
11272   if (SrcVT==MVT::i64 && DstVT.isVector())
11273     return Op;
11274   if (DstVT==MVT::i64 && SrcVT.isVector())
11275     return Op;
11276   // MMX <=> MMX conversions are Legal.
11277   if (SrcVT.isVector() && DstVT.isVector())
11278     return Op;
11279   // All other conversions need to be expanded.
11280   return SDValue();
11281 }
11282
11283 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11284   SDNode *Node = Op.getNode();
11285   DebugLoc dl = Node->getDebugLoc();
11286   EVT T = Node->getValueType(0);
11287   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11288                               DAG.getConstant(0, T), Node->getOperand(2));
11289   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11290                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11291                        Node->getOperand(0),
11292                        Node->getOperand(1), negOp,
11293                        cast<AtomicSDNode>(Node)->getSrcValue(),
11294                        cast<AtomicSDNode>(Node)->getAlignment(),
11295                        cast<AtomicSDNode>(Node)->getOrdering(),
11296                        cast<AtomicSDNode>(Node)->getSynchScope());
11297 }
11298
11299 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11300   SDNode *Node = Op.getNode();
11301   DebugLoc dl = Node->getDebugLoc();
11302   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11303
11304   // Convert seq_cst store -> xchg
11305   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11306   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11307   //        (The only way to get a 16-byte store is cmpxchg16b)
11308   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11309   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11310       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11311     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11312                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11313                                  Node->getOperand(0),
11314                                  Node->getOperand(1), Node->getOperand(2),
11315                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11316                                  cast<AtomicSDNode>(Node)->getOrdering(),
11317                                  cast<AtomicSDNode>(Node)->getSynchScope());
11318     return Swap.getValue(1);
11319   }
11320   // Other atomic stores have a simple pattern.
11321   return Op;
11322 }
11323
11324 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11325   EVT VT = Op.getNode()->getValueType(0);
11326
11327   // Let legalize expand this if it isn't a legal type yet.
11328   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11329     return SDValue();
11330
11331   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11332
11333   unsigned Opc;
11334   bool ExtraOp = false;
11335   switch (Op.getOpcode()) {
11336   default: llvm_unreachable("Invalid code");
11337   case ISD::ADDC: Opc = X86ISD::ADD; break;
11338   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11339   case ISD::SUBC: Opc = X86ISD::SUB; break;
11340   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11341   }
11342
11343   if (!ExtraOp)
11344     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11345                        Op.getOperand(1));
11346   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11347                      Op.getOperand(1), Op.getOperand(2));
11348 }
11349
11350 /// LowerOperation - Provide custom lowering hooks for some operations.
11351 ///
11352 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11353   switch (Op.getOpcode()) {
11354   default: llvm_unreachable("Should not custom lower this!");
11355   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11356   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11357   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11358   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11359   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11360   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11361   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11362   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11363   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11364   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11365   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11366   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11367   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11368   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11369   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11370   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11371   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11372   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11373   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11374   case ISD::SHL_PARTS:
11375   case ISD::SRA_PARTS:
11376   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11377   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11378   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11379   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11380   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11381   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11382   case ISD::FABS:               return LowerFABS(Op, DAG);
11383   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11384   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11385   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11386   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11387   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11388   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11389   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11390   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11391   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11392   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11393   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11394   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11395   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11396   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11397   case ISD::FRAME_TO_ARGS_OFFSET:
11398                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11399   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11400   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11401   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11402   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11403   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11404   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11405   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11406   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11407   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11408   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11409   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11410   case ISD::SRA:
11411   case ISD::SRL:
11412   case ISD::SHL:                return LowerShift(Op, DAG);
11413   case ISD::SADDO:
11414   case ISD::UADDO:
11415   case ISD::SSUBO:
11416   case ISD::USUBO:
11417   case ISD::SMULO:
11418   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11419   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11420   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11421   case ISD::ADDC:
11422   case ISD::ADDE:
11423   case ISD::SUBC:
11424   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11425   case ISD::ADD:                return LowerADD(Op, DAG);
11426   case ISD::SUB:                return LowerSUB(Op, DAG);
11427   }
11428 }
11429
11430 static void ReplaceATOMIC_LOAD(SDNode *Node,
11431                                   SmallVectorImpl<SDValue> &Results,
11432                                   SelectionDAG &DAG) {
11433   DebugLoc dl = Node->getDebugLoc();
11434   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11435
11436   // Convert wide load -> cmpxchg8b/cmpxchg16b
11437   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11438   //        (The only way to get a 16-byte load is cmpxchg16b)
11439   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11440   SDValue Zero = DAG.getConstant(0, VT);
11441   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11442                                Node->getOperand(0),
11443                                Node->getOperand(1), Zero, Zero,
11444                                cast<AtomicSDNode>(Node)->getMemOperand(),
11445                                cast<AtomicSDNode>(Node)->getOrdering(),
11446                                cast<AtomicSDNode>(Node)->getSynchScope());
11447   Results.push_back(Swap.getValue(0));
11448   Results.push_back(Swap.getValue(1));
11449 }
11450
11451 static void
11452 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11453                         SelectionDAG &DAG, unsigned NewOp) {
11454   DebugLoc dl = Node->getDebugLoc();
11455   assert (Node->getValueType(0) == MVT::i64 &&
11456           "Only know how to expand i64 atomics");
11457
11458   SDValue Chain = Node->getOperand(0);
11459   SDValue In1 = Node->getOperand(1);
11460   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11461                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11462   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11463                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11464   SDValue Ops[] = { Chain, In1, In2L, In2H };
11465   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11466   SDValue Result =
11467     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11468                             cast<MemSDNode>(Node)->getMemOperand());
11469   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11470   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11471   Results.push_back(Result.getValue(2));
11472 }
11473
11474 /// ReplaceNodeResults - Replace a node with an illegal result type
11475 /// with a new node built out of custom code.
11476 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11477                                            SmallVectorImpl<SDValue>&Results,
11478                                            SelectionDAG &DAG) const {
11479   DebugLoc dl = N->getDebugLoc();
11480   switch (N->getOpcode()) {
11481   default:
11482     llvm_unreachable("Do not know how to custom type legalize this operation!");
11483   case ISD::SIGN_EXTEND_INREG:
11484   case ISD::ADDC:
11485   case ISD::ADDE:
11486   case ISD::SUBC:
11487   case ISD::SUBE:
11488     // We don't want to expand or promote these.
11489     return;
11490   case ISD::FP_TO_SINT:
11491   case ISD::FP_TO_UINT: {
11492     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11493
11494     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11495       return;
11496
11497     std::pair<SDValue,SDValue> Vals =
11498         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11499     SDValue FIST = Vals.first, StackSlot = Vals.second;
11500     if (FIST.getNode() != 0) {
11501       EVT VT = N->getValueType(0);
11502       // Return a load from the stack slot.
11503       if (StackSlot.getNode() != 0)
11504         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11505                                       MachinePointerInfo(),
11506                                       false, false, false, 0));
11507       else
11508         Results.push_back(FIST);
11509     }
11510     return;
11511   }
11512   case ISD::FP_ROUND: {
11513     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11514     Results.push_back(V);
11515     return;
11516   }
11517   case ISD::READCYCLECOUNTER: {
11518     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11519     SDValue TheChain = N->getOperand(0);
11520     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11521     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11522                                      rd.getValue(1));
11523     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11524                                      eax.getValue(2));
11525     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11526     SDValue Ops[] = { eax, edx };
11527     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11528     Results.push_back(edx.getValue(1));
11529     return;
11530   }
11531   case ISD::ATOMIC_CMP_SWAP: {
11532     EVT T = N->getValueType(0);
11533     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11534     bool Regs64bit = T == MVT::i128;
11535     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11536     SDValue cpInL, cpInH;
11537     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11538                         DAG.getConstant(0, HalfT));
11539     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11540                         DAG.getConstant(1, HalfT));
11541     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11542                              Regs64bit ? X86::RAX : X86::EAX,
11543                              cpInL, SDValue());
11544     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11545                              Regs64bit ? X86::RDX : X86::EDX,
11546                              cpInH, cpInL.getValue(1));
11547     SDValue swapInL, swapInH;
11548     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11549                           DAG.getConstant(0, HalfT));
11550     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11551                           DAG.getConstant(1, HalfT));
11552     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11553                                Regs64bit ? X86::RBX : X86::EBX,
11554                                swapInL, cpInH.getValue(1));
11555     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11556                                Regs64bit ? X86::RCX : X86::ECX,
11557                                swapInH, swapInL.getValue(1));
11558     SDValue Ops[] = { swapInH.getValue(0),
11559                       N->getOperand(1),
11560                       swapInH.getValue(1) };
11561     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11562     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11563     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11564                                   X86ISD::LCMPXCHG8_DAG;
11565     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11566                                              Ops, 3, T, MMO);
11567     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11568                                         Regs64bit ? X86::RAX : X86::EAX,
11569                                         HalfT, Result.getValue(1));
11570     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11571                                         Regs64bit ? X86::RDX : X86::EDX,
11572                                         HalfT, cpOutL.getValue(2));
11573     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11574     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11575     Results.push_back(cpOutH.getValue(1));
11576     return;
11577   }
11578   case ISD::ATOMIC_LOAD_ADD:
11579   case ISD::ATOMIC_LOAD_AND:
11580   case ISD::ATOMIC_LOAD_NAND:
11581   case ISD::ATOMIC_LOAD_OR:
11582   case ISD::ATOMIC_LOAD_SUB:
11583   case ISD::ATOMIC_LOAD_XOR:
11584   case ISD::ATOMIC_LOAD_MAX:
11585   case ISD::ATOMIC_LOAD_MIN:
11586   case ISD::ATOMIC_LOAD_UMAX:
11587   case ISD::ATOMIC_LOAD_UMIN:
11588   case ISD::ATOMIC_SWAP: {
11589     unsigned Opc;
11590     switch (N->getOpcode()) {
11591     default: llvm_unreachable("Unexpected opcode");
11592     case ISD::ATOMIC_LOAD_ADD:
11593       Opc = X86ISD::ATOMADD64_DAG;
11594       break;
11595     case ISD::ATOMIC_LOAD_AND:
11596       Opc = X86ISD::ATOMAND64_DAG;
11597       break;
11598     case ISD::ATOMIC_LOAD_NAND:
11599       Opc = X86ISD::ATOMNAND64_DAG;
11600       break;
11601     case ISD::ATOMIC_LOAD_OR:
11602       Opc = X86ISD::ATOMOR64_DAG;
11603       break;
11604     case ISD::ATOMIC_LOAD_SUB:
11605       Opc = X86ISD::ATOMSUB64_DAG;
11606       break;
11607     case ISD::ATOMIC_LOAD_XOR:
11608       Opc = X86ISD::ATOMXOR64_DAG;
11609       break;
11610     case ISD::ATOMIC_LOAD_MAX:
11611       Opc = X86ISD::ATOMMAX64_DAG;
11612       break;
11613     case ISD::ATOMIC_LOAD_MIN:
11614       Opc = X86ISD::ATOMMIN64_DAG;
11615       break;
11616     case ISD::ATOMIC_LOAD_UMAX:
11617       Opc = X86ISD::ATOMUMAX64_DAG;
11618       break;
11619     case ISD::ATOMIC_LOAD_UMIN:
11620       Opc = X86ISD::ATOMUMIN64_DAG;
11621       break;
11622     case ISD::ATOMIC_SWAP:
11623       Opc = X86ISD::ATOMSWAP64_DAG;
11624       break;
11625     }
11626     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11627     return;
11628   }
11629   case ISD::ATOMIC_LOAD:
11630     ReplaceATOMIC_LOAD(N, Results, DAG);
11631   }
11632 }
11633
11634 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11635   switch (Opcode) {
11636   default: return NULL;
11637   case X86ISD::BSF:                return "X86ISD::BSF";
11638   case X86ISD::BSR:                return "X86ISD::BSR";
11639   case X86ISD::SHLD:               return "X86ISD::SHLD";
11640   case X86ISD::SHRD:               return "X86ISD::SHRD";
11641   case X86ISD::FAND:               return "X86ISD::FAND";
11642   case X86ISD::FOR:                return "X86ISD::FOR";
11643   case X86ISD::FXOR:               return "X86ISD::FXOR";
11644   case X86ISD::FSRL:               return "X86ISD::FSRL";
11645   case X86ISD::FILD:               return "X86ISD::FILD";
11646   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11647   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11648   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11649   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11650   case X86ISD::FLD:                return "X86ISD::FLD";
11651   case X86ISD::FST:                return "X86ISD::FST";
11652   case X86ISD::CALL:               return "X86ISD::CALL";
11653   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11654   case X86ISD::BT:                 return "X86ISD::BT";
11655   case X86ISD::CMP:                return "X86ISD::CMP";
11656   case X86ISD::COMI:               return "X86ISD::COMI";
11657   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11658   case X86ISD::SETCC:              return "X86ISD::SETCC";
11659   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11660   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11661   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11662   case X86ISD::CMOV:               return "X86ISD::CMOV";
11663   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11664   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11665   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11666   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11667   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11668   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11669   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11670   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11671   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11672   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11673   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11674   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11675   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11676   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11677   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11678   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11679   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11680   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11681   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11682   case X86ISD::HADD:               return "X86ISD::HADD";
11683   case X86ISD::HSUB:               return "X86ISD::HSUB";
11684   case X86ISD::FHADD:              return "X86ISD::FHADD";
11685   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11686   case X86ISD::FMAX:               return "X86ISD::FMAX";
11687   case X86ISD::FMIN:               return "X86ISD::FMIN";
11688   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11689   case X86ISD::FMINC:              return "X86ISD::FMINC";
11690   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11691   case X86ISD::FRCP:               return "X86ISD::FRCP";
11692   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11693   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11694   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11695   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11696   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11697   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11698   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11699   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11700   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11701   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11702   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11703   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11704   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11705   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11706   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11707   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11708   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11709   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11710   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11711   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11712   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11713   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11714   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11715   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11716   case X86ISD::VSHL:               return "X86ISD::VSHL";
11717   case X86ISD::VSRL:               return "X86ISD::VSRL";
11718   case X86ISD::VSRA:               return "X86ISD::VSRA";
11719   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11720   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11721   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11722   case X86ISD::CMPP:               return "X86ISD::CMPP";
11723   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11724   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11725   case X86ISD::ADD:                return "X86ISD::ADD";
11726   case X86ISD::SUB:                return "X86ISD::SUB";
11727   case X86ISD::ADC:                return "X86ISD::ADC";
11728   case X86ISD::SBB:                return "X86ISD::SBB";
11729   case X86ISD::SMUL:               return "X86ISD::SMUL";
11730   case X86ISD::UMUL:               return "X86ISD::UMUL";
11731   case X86ISD::INC:                return "X86ISD::INC";
11732   case X86ISD::DEC:                return "X86ISD::DEC";
11733   case X86ISD::OR:                 return "X86ISD::OR";
11734   case X86ISD::XOR:                return "X86ISD::XOR";
11735   case X86ISD::AND:                return "X86ISD::AND";
11736   case X86ISD::ANDN:               return "X86ISD::ANDN";
11737   case X86ISD::BLSI:               return "X86ISD::BLSI";
11738   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11739   case X86ISD::BLSR:               return "X86ISD::BLSR";
11740   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11741   case X86ISD::PTEST:              return "X86ISD::PTEST";
11742   case X86ISD::TESTP:              return "X86ISD::TESTP";
11743   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11744   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11745   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11746   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11747   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11748   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11749   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11750   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11751   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11752   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11753   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11754   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11755   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11756   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11757   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11758   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11759   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11760   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11761   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11762   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11763   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11764   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11765   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11766   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11767   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11768   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11769   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11770   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11771   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11772   case X86ISD::SAHF:               return "X86ISD::SAHF";
11773   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11774   case X86ISD::FMADD:              return "X86ISD::FMADD";
11775   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11776   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11777   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11778   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11779   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11780   }
11781 }
11782
11783 // isLegalAddressingMode - Return true if the addressing mode represented
11784 // by AM is legal for this target, for a load/store of the specified type.
11785 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11786                                               Type *Ty) const {
11787   // X86 supports extremely general addressing modes.
11788   CodeModel::Model M = getTargetMachine().getCodeModel();
11789   Reloc::Model R = getTargetMachine().getRelocationModel();
11790
11791   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11792   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11793     return false;
11794
11795   if (AM.BaseGV) {
11796     unsigned GVFlags =
11797       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11798
11799     // If a reference to this global requires an extra load, we can't fold it.
11800     if (isGlobalStubReference(GVFlags))
11801       return false;
11802
11803     // If BaseGV requires a register for the PIC base, we cannot also have a
11804     // BaseReg specified.
11805     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11806       return false;
11807
11808     // If lower 4G is not available, then we must use rip-relative addressing.
11809     if ((M != CodeModel::Small || R != Reloc::Static) &&
11810         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11811       return false;
11812   }
11813
11814   switch (AM.Scale) {
11815   case 0:
11816   case 1:
11817   case 2:
11818   case 4:
11819   case 8:
11820     // These scales always work.
11821     break;
11822   case 3:
11823   case 5:
11824   case 9:
11825     // These scales are formed with basereg+scalereg.  Only accept if there is
11826     // no basereg yet.
11827     if (AM.HasBaseReg)
11828       return false;
11829     break;
11830   default:  // Other stuff never works.
11831     return false;
11832   }
11833
11834   return true;
11835 }
11836
11837
11838 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11839   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11840     return false;
11841   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11842   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11843   if (NumBits1 <= NumBits2)
11844     return false;
11845   return true;
11846 }
11847
11848 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11849   return Imm == (int32_t)Imm;
11850 }
11851
11852 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11853   // Can also use sub to handle negated immediates.
11854   return Imm == (int32_t)Imm;
11855 }
11856
11857 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11858   if (!VT1.isInteger() || !VT2.isInteger())
11859     return false;
11860   unsigned NumBits1 = VT1.getSizeInBits();
11861   unsigned NumBits2 = VT2.getSizeInBits();
11862   if (NumBits1 <= NumBits2)
11863     return false;
11864   return true;
11865 }
11866
11867 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11868   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11869   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11870 }
11871
11872 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11873   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11874   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11875 }
11876
11877 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11878   // i16 instructions are longer (0x66 prefix) and potentially slower.
11879   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11880 }
11881
11882 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11883 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11884 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11885 /// are assumed to be legal.
11886 bool
11887 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11888                                       EVT VT) const {
11889   // Very little shuffling can be done for 64-bit vectors right now.
11890   if (VT.getSizeInBits() == 64)
11891     return false;
11892
11893   // FIXME: pshufb, blends, shifts.
11894   return (VT.getVectorNumElements() == 2 ||
11895           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11896           isMOVLMask(M, VT) ||
11897           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11898           isPSHUFDMask(M, VT) ||
11899           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11900           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11901           isPALIGNRMask(M, VT, Subtarget) ||
11902           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11903           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11904           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11905           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11906 }
11907
11908 bool
11909 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11910                                           EVT VT) const {
11911   unsigned NumElts = VT.getVectorNumElements();
11912   // FIXME: This collection of masks seems suspect.
11913   if (NumElts == 2)
11914     return true;
11915   if (NumElts == 4 && VT.is128BitVector()) {
11916     return (isMOVLMask(Mask, VT)  ||
11917             isCommutedMOVLMask(Mask, VT, true) ||
11918             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11919             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11920   }
11921   return false;
11922 }
11923
11924 //===----------------------------------------------------------------------===//
11925 //                           X86 Scheduler Hooks
11926 //===----------------------------------------------------------------------===//
11927
11928 // private utility function
11929
11930 // Get CMPXCHG opcode for the specified data type.
11931 static unsigned getCmpXChgOpcode(EVT VT) {
11932   switch (VT.getSimpleVT().SimpleTy) {
11933   case MVT::i8:  return X86::LCMPXCHG8;
11934   case MVT::i16: return X86::LCMPXCHG16;
11935   case MVT::i32: return X86::LCMPXCHG32;
11936   case MVT::i64: return X86::LCMPXCHG64;
11937   default:
11938     break;
11939   }
11940   llvm_unreachable("Invalid operand size!");
11941 }
11942
11943 // Get LOAD opcode for the specified data type.
11944 static unsigned getLoadOpcode(EVT VT) {
11945   switch (VT.getSimpleVT().SimpleTy) {
11946   case MVT::i8:  return X86::MOV8rm;
11947   case MVT::i16: return X86::MOV16rm;
11948   case MVT::i32: return X86::MOV32rm;
11949   case MVT::i64: return X86::MOV64rm;
11950   default:
11951     break;
11952   }
11953   llvm_unreachable("Invalid operand size!");
11954 }
11955
11956 // Get opcode of the non-atomic one from the specified atomic instruction.
11957 static unsigned getNonAtomicOpcode(unsigned Opc) {
11958   switch (Opc) {
11959   case X86::ATOMAND8:  return X86::AND8rr;
11960   case X86::ATOMAND16: return X86::AND16rr;
11961   case X86::ATOMAND32: return X86::AND32rr;
11962   case X86::ATOMAND64: return X86::AND64rr;
11963   case X86::ATOMOR8:   return X86::OR8rr;
11964   case X86::ATOMOR16:  return X86::OR16rr;
11965   case X86::ATOMOR32:  return X86::OR32rr;
11966   case X86::ATOMOR64:  return X86::OR64rr;
11967   case X86::ATOMXOR8:  return X86::XOR8rr;
11968   case X86::ATOMXOR16: return X86::XOR16rr;
11969   case X86::ATOMXOR32: return X86::XOR32rr;
11970   case X86::ATOMXOR64: return X86::XOR64rr;
11971   }
11972   llvm_unreachable("Unhandled atomic-load-op opcode!");
11973 }
11974
11975 // Get opcode of the non-atomic one from the specified atomic instruction with
11976 // extra opcode.
11977 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11978                                                unsigned &ExtraOpc) {
11979   switch (Opc) {
11980   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
11981   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
11982   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
11983   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
11984   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
11985   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
11986   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
11987   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
11988   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
11989   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
11990   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
11991   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
11992   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
11993   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
11994   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
11995   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
11996   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
11997   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
11998   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
11999   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12000   }
12001   llvm_unreachable("Unhandled atomic-load-op opcode!");
12002 }
12003
12004 // Get opcode of the non-atomic one from the specified atomic instruction for
12005 // 64-bit data type on 32-bit target.
12006 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12007   switch (Opc) {
12008   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12009   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12010   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12011   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12012   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12013   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12014   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12015   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12016   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12017   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12018   }
12019   llvm_unreachable("Unhandled atomic-load-op opcode!");
12020 }
12021
12022 // Get opcode of the non-atomic one from the specified atomic instruction for
12023 // 64-bit data type on 32-bit target with extra opcode.
12024 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12025                                                    unsigned &HiOpc,
12026                                                    unsigned &ExtraOpc) {
12027   switch (Opc) {
12028   case X86::ATOMNAND6432:
12029     ExtraOpc = X86::NOT32r;
12030     HiOpc = X86::AND32rr;
12031     return X86::AND32rr;
12032   }
12033   llvm_unreachable("Unhandled atomic-load-op opcode!");
12034 }
12035
12036 // Get pseudo CMOV opcode from the specified data type.
12037 static unsigned getPseudoCMOVOpc(EVT VT) {
12038   switch (VT.getSimpleVT().SimpleTy) {
12039   case MVT::i8:  return X86::CMOV_GR8;
12040   case MVT::i16: return X86::CMOV_GR16;
12041   case MVT::i32: return X86::CMOV_GR32;
12042   default:
12043     break;
12044   }
12045   llvm_unreachable("Unknown CMOV opcode!");
12046 }
12047
12048 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12049 // They will be translated into a spin-loop or compare-exchange loop from
12050 //
12051 //    ...
12052 //    dst = atomic-fetch-op MI.addr, MI.val
12053 //    ...
12054 //
12055 // to
12056 //
12057 //    ...
12058 //    EAX = LOAD MI.addr
12059 // loop:
12060 //    t1 = OP MI.val, EAX
12061 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12062 //    JNE loop
12063 // sink:
12064 //    dst = EAX
12065 //    ...
12066 MachineBasicBlock *
12067 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12068                                        MachineBasicBlock *MBB) const {
12069   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12070   DebugLoc DL = MI->getDebugLoc();
12071
12072   MachineFunction *MF = MBB->getParent();
12073   MachineRegisterInfo &MRI = MF->getRegInfo();
12074
12075   const BasicBlock *BB = MBB->getBasicBlock();
12076   MachineFunction::iterator I = MBB;
12077   ++I;
12078
12079   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12080          "Unexpected number of operands");
12081
12082   assert(MI->hasOneMemOperand() &&
12083          "Expected atomic-load-op to have one memoperand");
12084
12085   // Memory Reference
12086   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12087   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12088
12089   unsigned DstReg, SrcReg;
12090   unsigned MemOpndSlot;
12091
12092   unsigned CurOp = 0;
12093
12094   DstReg = MI->getOperand(CurOp++).getReg();
12095   MemOpndSlot = CurOp;
12096   CurOp += X86::AddrNumOperands;
12097   SrcReg = MI->getOperand(CurOp++).getReg();
12098
12099   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12100   MVT::SimpleValueType VT = *RC->vt_begin();
12101   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12102
12103   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12104   unsigned LOADOpc = getLoadOpcode(VT);
12105
12106   // For the atomic load-arith operator, we generate
12107   //
12108   //  thisMBB:
12109   //    EAX = LOAD [MI.addr]
12110   //  mainMBB:
12111   //    t1 = OP MI.val, EAX
12112   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12113   //    JNE mainMBB
12114   //  sinkMBB:
12115
12116   MachineBasicBlock *thisMBB = MBB;
12117   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12118   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12119   MF->insert(I, mainMBB);
12120   MF->insert(I, sinkMBB);
12121
12122   MachineInstrBuilder MIB;
12123
12124   // Transfer the remainder of BB and its successor edges to sinkMBB.
12125   sinkMBB->splice(sinkMBB->begin(), MBB,
12126                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12127   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12128
12129   // thisMBB:
12130   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12131   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12132     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12133   MIB.setMemRefs(MMOBegin, MMOEnd);
12134
12135   thisMBB->addSuccessor(mainMBB);
12136
12137   // mainMBB:
12138   MachineBasicBlock *origMainMBB = mainMBB;
12139   mainMBB->addLiveIn(AccPhyReg);
12140
12141   // Copy AccPhyReg as it is used more than once.
12142   unsigned AccReg = MRI.createVirtualRegister(RC);
12143   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12144     .addReg(AccPhyReg);
12145
12146   unsigned t1 = MRI.createVirtualRegister(RC);
12147   unsigned Opc = MI->getOpcode();
12148   switch (Opc) {
12149   default:
12150     llvm_unreachable("Unhandled atomic-load-op opcode!");
12151   case X86::ATOMAND8:
12152   case X86::ATOMAND16:
12153   case X86::ATOMAND32:
12154   case X86::ATOMAND64:
12155   case X86::ATOMOR8:
12156   case X86::ATOMOR16:
12157   case X86::ATOMOR32:
12158   case X86::ATOMOR64:
12159   case X86::ATOMXOR8:
12160   case X86::ATOMXOR16:
12161   case X86::ATOMXOR32:
12162   case X86::ATOMXOR64: {
12163     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12164     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12165       .addReg(AccReg);
12166     break;
12167   }
12168   case X86::ATOMNAND8:
12169   case X86::ATOMNAND16:
12170   case X86::ATOMNAND32:
12171   case X86::ATOMNAND64: {
12172     unsigned t2 = MRI.createVirtualRegister(RC);
12173     unsigned NOTOpc;
12174     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12175     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12176       .addReg(AccReg);
12177     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12178     break;
12179   }
12180   case X86::ATOMMAX8:
12181   case X86::ATOMMAX16:
12182   case X86::ATOMMAX32:
12183   case X86::ATOMMAX64:
12184   case X86::ATOMMIN8:
12185   case X86::ATOMMIN16:
12186   case X86::ATOMMIN32:
12187   case X86::ATOMMIN64:
12188   case X86::ATOMUMAX8:
12189   case X86::ATOMUMAX16:
12190   case X86::ATOMUMAX32:
12191   case X86::ATOMUMAX64:
12192   case X86::ATOMUMIN8:
12193   case X86::ATOMUMIN16:
12194   case X86::ATOMUMIN32:
12195   case X86::ATOMUMIN64: {
12196     unsigned CMPOpc;
12197     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12198
12199     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12200       .addReg(SrcReg)
12201       .addReg(AccReg);
12202
12203     if (Subtarget->hasCMov()) {
12204       if (VT != MVT::i8) {
12205         // Native support
12206         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12207           .addReg(SrcReg)
12208           .addReg(AccReg);
12209       } else {
12210         // Promote i8 to i32 to use CMOV32
12211         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12212         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12213         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12214         unsigned t2 = MRI.createVirtualRegister(RC32);
12215
12216         unsigned Undef = MRI.createVirtualRegister(RC32);
12217         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12218
12219         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12220           .addReg(Undef)
12221           .addReg(SrcReg)
12222           .addImm(X86::sub_8bit);
12223         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12224           .addReg(Undef)
12225           .addReg(AccReg)
12226           .addImm(X86::sub_8bit);
12227
12228         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12229           .addReg(SrcReg32)
12230           .addReg(AccReg32);
12231
12232         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12233           .addReg(t2, 0, X86::sub_8bit);
12234       }
12235     } else {
12236       // Use pseudo select and lower them.
12237       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12238              "Invalid atomic-load-op transformation!");
12239       unsigned SelOpc = getPseudoCMOVOpc(VT);
12240       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12241       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12242       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12243               .addReg(SrcReg).addReg(AccReg)
12244               .addImm(CC);
12245       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12246     }
12247     break;
12248   }
12249   }
12250
12251   // Copy AccPhyReg back from virtual register.
12252   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12253     .addReg(AccReg);
12254
12255   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12256   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12257     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12258   MIB.addReg(t1);
12259   MIB.setMemRefs(MMOBegin, MMOEnd);
12260
12261   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12262
12263   mainMBB->addSuccessor(origMainMBB);
12264   mainMBB->addSuccessor(sinkMBB);
12265
12266   // sinkMBB:
12267   sinkMBB->addLiveIn(AccPhyReg);
12268
12269   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12270           TII->get(TargetOpcode::COPY), DstReg)
12271     .addReg(AccPhyReg);
12272
12273   MI->eraseFromParent();
12274   return sinkMBB;
12275 }
12276
12277 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12278 // instructions. They will be translated into a spin-loop or compare-exchange
12279 // loop from
12280 //
12281 //    ...
12282 //    dst = atomic-fetch-op MI.addr, MI.val
12283 //    ...
12284 //
12285 // to
12286 //
12287 //    ...
12288 //    EAX = LOAD [MI.addr + 0]
12289 //    EDX = LOAD [MI.addr + 4]
12290 // loop:
12291 //    EBX = OP MI.val.lo, EAX
12292 //    ECX = OP MI.val.hi, EDX
12293 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12294 //    JNE loop
12295 // sink:
12296 //    dst = EDX:EAX
12297 //    ...
12298 MachineBasicBlock *
12299 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12300                                            MachineBasicBlock *MBB) const {
12301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12302   DebugLoc DL = MI->getDebugLoc();
12303
12304   MachineFunction *MF = MBB->getParent();
12305   MachineRegisterInfo &MRI = MF->getRegInfo();
12306
12307   const BasicBlock *BB = MBB->getBasicBlock();
12308   MachineFunction::iterator I = MBB;
12309   ++I;
12310
12311   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12312          "Unexpected number of operands");
12313
12314   assert(MI->hasOneMemOperand() &&
12315          "Expected atomic-load-op32 to have one memoperand");
12316
12317   // Memory Reference
12318   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12319   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12320
12321   unsigned DstLoReg, DstHiReg;
12322   unsigned SrcLoReg, SrcHiReg;
12323   unsigned MemOpndSlot;
12324
12325   unsigned CurOp = 0;
12326
12327   DstLoReg = MI->getOperand(CurOp++).getReg();
12328   DstHiReg = MI->getOperand(CurOp++).getReg();
12329   MemOpndSlot = CurOp;
12330   CurOp += X86::AddrNumOperands;
12331   SrcLoReg = MI->getOperand(CurOp++).getReg();
12332   SrcHiReg = MI->getOperand(CurOp++).getReg();
12333
12334   const TargetRegisterClass *RC = &X86::GR32RegClass;
12335   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12336
12337   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12338   unsigned LOADOpc = X86::MOV32rm;
12339
12340   // For the atomic load-arith operator, we generate
12341   //
12342   //  thisMBB:
12343   //    EAX = LOAD [MI.addr + 0]
12344   //    EDX = LOAD [MI.addr + 4]
12345   //  mainMBB:
12346   //    EBX = OP MI.vallo, EAX
12347   //    ECX = OP MI.valhi, EDX
12348   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12349   //    JNE mainMBB
12350   //  sinkMBB:
12351
12352   MachineBasicBlock *thisMBB = MBB;
12353   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12354   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12355   MF->insert(I, mainMBB);
12356   MF->insert(I, sinkMBB);
12357
12358   MachineInstrBuilder MIB;
12359
12360   // Transfer the remainder of BB and its successor edges to sinkMBB.
12361   sinkMBB->splice(sinkMBB->begin(), MBB,
12362                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12363   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12364
12365   // thisMBB:
12366   // Lo
12367   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12368   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12369     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12370   MIB.setMemRefs(MMOBegin, MMOEnd);
12371   // Hi
12372   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12373   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12374     if (i == X86::AddrDisp)
12375       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12376     else
12377       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12378   }
12379   MIB.setMemRefs(MMOBegin, MMOEnd);
12380
12381   thisMBB->addSuccessor(mainMBB);
12382
12383   // mainMBB:
12384   MachineBasicBlock *origMainMBB = mainMBB;
12385   mainMBB->addLiveIn(X86::EAX);
12386   mainMBB->addLiveIn(X86::EDX);
12387
12388   // Copy EDX:EAX as they are used more than once.
12389   unsigned LoReg = MRI.createVirtualRegister(RC);
12390   unsigned HiReg = MRI.createVirtualRegister(RC);
12391   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12392   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12393
12394   unsigned t1L = MRI.createVirtualRegister(RC);
12395   unsigned t1H = MRI.createVirtualRegister(RC);
12396
12397   unsigned Opc = MI->getOpcode();
12398   switch (Opc) {
12399   default:
12400     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12401   case X86::ATOMAND6432:
12402   case X86::ATOMOR6432:
12403   case X86::ATOMXOR6432:
12404   case X86::ATOMADD6432:
12405   case X86::ATOMSUB6432: {
12406     unsigned HiOpc;
12407     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12408     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12409     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12410     break;
12411   }
12412   case X86::ATOMNAND6432: {
12413     unsigned HiOpc, NOTOpc;
12414     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12415     unsigned t2L = MRI.createVirtualRegister(RC);
12416     unsigned t2H = MRI.createVirtualRegister(RC);
12417     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12418     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12419     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12420     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12421     break;
12422   }
12423   case X86::ATOMMAX6432:
12424   case X86::ATOMMIN6432:
12425   case X86::ATOMUMAX6432:
12426   case X86::ATOMUMIN6432: {
12427     unsigned HiOpc;
12428     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12429     unsigned cL = MRI.createVirtualRegister(RC8);
12430     unsigned cH = MRI.createVirtualRegister(RC8);
12431     unsigned cL32 = MRI.createVirtualRegister(RC);
12432     unsigned cH32 = MRI.createVirtualRegister(RC);
12433     unsigned cc = MRI.createVirtualRegister(RC);
12434     // cl := cmp src_lo, lo
12435     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12436       .addReg(SrcLoReg).addReg(LoReg);
12437     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12438     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12439     // ch := cmp src_hi, hi
12440     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12441       .addReg(SrcHiReg).addReg(HiReg);
12442     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12443     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12444     // cc := if (src_hi == hi) ? cl : ch;
12445     if (Subtarget->hasCMov()) {
12446       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12447         .addReg(cH32).addReg(cL32);
12448     } else {
12449       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12450               .addReg(cH32).addReg(cL32)
12451               .addImm(X86::COND_E);
12452       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12453     }
12454     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12455     if (Subtarget->hasCMov()) {
12456       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12457         .addReg(SrcLoReg).addReg(LoReg);
12458       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12459         .addReg(SrcHiReg).addReg(HiReg);
12460     } else {
12461       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12462               .addReg(SrcLoReg).addReg(LoReg)
12463               .addImm(X86::COND_NE);
12464       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12465       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12466               .addReg(SrcHiReg).addReg(HiReg)
12467               .addImm(X86::COND_NE);
12468       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12469     }
12470     break;
12471   }
12472   case X86::ATOMSWAP6432: {
12473     unsigned HiOpc;
12474     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12475     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12476     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12477     break;
12478   }
12479   }
12480
12481   // Copy EDX:EAX back from HiReg:LoReg
12482   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12483   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12484   // Copy ECX:EBX from t1H:t1L
12485   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12486   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12487
12488   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12489   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12490     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12491   MIB.setMemRefs(MMOBegin, MMOEnd);
12492
12493   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12494
12495   mainMBB->addSuccessor(origMainMBB);
12496   mainMBB->addSuccessor(sinkMBB);
12497
12498   // sinkMBB:
12499   sinkMBB->addLiveIn(X86::EAX);
12500   sinkMBB->addLiveIn(X86::EDX);
12501
12502   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12503           TII->get(TargetOpcode::COPY), DstLoReg)
12504     .addReg(X86::EAX);
12505   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12506           TII->get(TargetOpcode::COPY), DstHiReg)
12507     .addReg(X86::EDX);
12508
12509   MI->eraseFromParent();
12510   return sinkMBB;
12511 }
12512
12513 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12514 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12515 // in the .td file.
12516 MachineBasicBlock *
12517 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12518                             unsigned numArgs, bool memArg) const {
12519   assert(Subtarget->hasSSE42() &&
12520          "Target must have SSE4.2 or AVX features enabled");
12521
12522   DebugLoc dl = MI->getDebugLoc();
12523   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12524   unsigned Opc;
12525   if (!Subtarget->hasAVX()) {
12526     if (memArg)
12527       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12528     else
12529       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12530   } else {
12531     if (memArg)
12532       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12533     else
12534       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12535   }
12536
12537   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12538   for (unsigned i = 0; i < numArgs; ++i) {
12539     MachineOperand &Op = MI->getOperand(i+1);
12540     if (!(Op.isReg() && Op.isImplicit()))
12541       MIB.addOperand(Op);
12542   }
12543   BuildMI(*BB, MI, dl,
12544     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12545     .addReg(X86::XMM0);
12546
12547   MI->eraseFromParent();
12548   return BB;
12549 }
12550
12551 MachineBasicBlock *
12552 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12553   DebugLoc dl = MI->getDebugLoc();
12554   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12555
12556   // Address into RAX/EAX, other two args into ECX, EDX.
12557   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12558   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12559   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12560   for (int i = 0; i < X86::AddrNumOperands; ++i)
12561     MIB.addOperand(MI->getOperand(i));
12562
12563   unsigned ValOps = X86::AddrNumOperands;
12564   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12565     .addReg(MI->getOperand(ValOps).getReg());
12566   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12567     .addReg(MI->getOperand(ValOps+1).getReg());
12568
12569   // The instruction doesn't actually take any operands though.
12570   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12571
12572   MI->eraseFromParent(); // The pseudo is gone now.
12573   return BB;
12574 }
12575
12576 MachineBasicBlock *
12577 X86TargetLowering::EmitVAARG64WithCustomInserter(
12578                    MachineInstr *MI,
12579                    MachineBasicBlock *MBB) const {
12580   // Emit va_arg instruction on X86-64.
12581
12582   // Operands to this pseudo-instruction:
12583   // 0  ) Output        : destination address (reg)
12584   // 1-5) Input         : va_list address (addr, i64mem)
12585   // 6  ) ArgSize       : Size (in bytes) of vararg type
12586   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12587   // 8  ) Align         : Alignment of type
12588   // 9  ) EFLAGS (implicit-def)
12589
12590   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12591   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12592
12593   unsigned DestReg = MI->getOperand(0).getReg();
12594   MachineOperand &Base = MI->getOperand(1);
12595   MachineOperand &Scale = MI->getOperand(2);
12596   MachineOperand &Index = MI->getOperand(3);
12597   MachineOperand &Disp = MI->getOperand(4);
12598   MachineOperand &Segment = MI->getOperand(5);
12599   unsigned ArgSize = MI->getOperand(6).getImm();
12600   unsigned ArgMode = MI->getOperand(7).getImm();
12601   unsigned Align = MI->getOperand(8).getImm();
12602
12603   // Memory Reference
12604   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12605   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12606   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12607
12608   // Machine Information
12609   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12610   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12611   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12612   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12613   DebugLoc DL = MI->getDebugLoc();
12614
12615   // struct va_list {
12616   //   i32   gp_offset
12617   //   i32   fp_offset
12618   //   i64   overflow_area (address)
12619   //   i64   reg_save_area (address)
12620   // }
12621   // sizeof(va_list) = 24
12622   // alignment(va_list) = 8
12623
12624   unsigned TotalNumIntRegs = 6;
12625   unsigned TotalNumXMMRegs = 8;
12626   bool UseGPOffset = (ArgMode == 1);
12627   bool UseFPOffset = (ArgMode == 2);
12628   unsigned MaxOffset = TotalNumIntRegs * 8 +
12629                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12630
12631   /* Align ArgSize to a multiple of 8 */
12632   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12633   bool NeedsAlign = (Align > 8);
12634
12635   MachineBasicBlock *thisMBB = MBB;
12636   MachineBasicBlock *overflowMBB;
12637   MachineBasicBlock *offsetMBB;
12638   MachineBasicBlock *endMBB;
12639
12640   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12641   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12642   unsigned OffsetReg = 0;
12643
12644   if (!UseGPOffset && !UseFPOffset) {
12645     // If we only pull from the overflow region, we don't create a branch.
12646     // We don't need to alter control flow.
12647     OffsetDestReg = 0; // unused
12648     OverflowDestReg = DestReg;
12649
12650     offsetMBB = NULL;
12651     overflowMBB = thisMBB;
12652     endMBB = thisMBB;
12653   } else {
12654     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12655     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12656     // If not, pull from overflow_area. (branch to overflowMBB)
12657     //
12658     //       thisMBB
12659     //         |     .
12660     //         |        .
12661     //     offsetMBB   overflowMBB
12662     //         |        .
12663     //         |     .
12664     //        endMBB
12665
12666     // Registers for the PHI in endMBB
12667     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12668     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12669
12670     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12671     MachineFunction *MF = MBB->getParent();
12672     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12673     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12674     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12675
12676     MachineFunction::iterator MBBIter = MBB;
12677     ++MBBIter;
12678
12679     // Insert the new basic blocks
12680     MF->insert(MBBIter, offsetMBB);
12681     MF->insert(MBBIter, overflowMBB);
12682     MF->insert(MBBIter, endMBB);
12683
12684     // Transfer the remainder of MBB and its successor edges to endMBB.
12685     endMBB->splice(endMBB->begin(), thisMBB,
12686                     llvm::next(MachineBasicBlock::iterator(MI)),
12687                     thisMBB->end());
12688     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12689
12690     // Make offsetMBB and overflowMBB successors of thisMBB
12691     thisMBB->addSuccessor(offsetMBB);
12692     thisMBB->addSuccessor(overflowMBB);
12693
12694     // endMBB is a successor of both offsetMBB and overflowMBB
12695     offsetMBB->addSuccessor(endMBB);
12696     overflowMBB->addSuccessor(endMBB);
12697
12698     // Load the offset value into a register
12699     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12700     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12701       .addOperand(Base)
12702       .addOperand(Scale)
12703       .addOperand(Index)
12704       .addDisp(Disp, UseFPOffset ? 4 : 0)
12705       .addOperand(Segment)
12706       .setMemRefs(MMOBegin, MMOEnd);
12707
12708     // Check if there is enough room left to pull this argument.
12709     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12710       .addReg(OffsetReg)
12711       .addImm(MaxOffset + 8 - ArgSizeA8);
12712
12713     // Branch to "overflowMBB" if offset >= max
12714     // Fall through to "offsetMBB" otherwise
12715     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12716       .addMBB(overflowMBB);
12717   }
12718
12719   // In offsetMBB, emit code to use the reg_save_area.
12720   if (offsetMBB) {
12721     assert(OffsetReg != 0);
12722
12723     // Read the reg_save_area address.
12724     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12725     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12726       .addOperand(Base)
12727       .addOperand(Scale)
12728       .addOperand(Index)
12729       .addDisp(Disp, 16)
12730       .addOperand(Segment)
12731       .setMemRefs(MMOBegin, MMOEnd);
12732
12733     // Zero-extend the offset
12734     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12735       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12736         .addImm(0)
12737         .addReg(OffsetReg)
12738         .addImm(X86::sub_32bit);
12739
12740     // Add the offset to the reg_save_area to get the final address.
12741     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12742       .addReg(OffsetReg64)
12743       .addReg(RegSaveReg);
12744
12745     // Compute the offset for the next argument
12746     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12747     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12748       .addReg(OffsetReg)
12749       .addImm(UseFPOffset ? 16 : 8);
12750
12751     // Store it back into the va_list.
12752     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12753       .addOperand(Base)
12754       .addOperand(Scale)
12755       .addOperand(Index)
12756       .addDisp(Disp, UseFPOffset ? 4 : 0)
12757       .addOperand(Segment)
12758       .addReg(NextOffsetReg)
12759       .setMemRefs(MMOBegin, MMOEnd);
12760
12761     // Jump to endMBB
12762     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12763       .addMBB(endMBB);
12764   }
12765
12766   //
12767   // Emit code to use overflow area
12768   //
12769
12770   // Load the overflow_area address into a register.
12771   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12772   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12773     .addOperand(Base)
12774     .addOperand(Scale)
12775     .addOperand(Index)
12776     .addDisp(Disp, 8)
12777     .addOperand(Segment)
12778     .setMemRefs(MMOBegin, MMOEnd);
12779
12780   // If we need to align it, do so. Otherwise, just copy the address
12781   // to OverflowDestReg.
12782   if (NeedsAlign) {
12783     // Align the overflow address
12784     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12785     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12786
12787     // aligned_addr = (addr + (align-1)) & ~(align-1)
12788     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12789       .addReg(OverflowAddrReg)
12790       .addImm(Align-1);
12791
12792     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12793       .addReg(TmpReg)
12794       .addImm(~(uint64_t)(Align-1));
12795   } else {
12796     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12797       .addReg(OverflowAddrReg);
12798   }
12799
12800   // Compute the next overflow address after this argument.
12801   // (the overflow address should be kept 8-byte aligned)
12802   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12803   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12804     .addReg(OverflowDestReg)
12805     .addImm(ArgSizeA8);
12806
12807   // Store the new overflow address.
12808   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12809     .addOperand(Base)
12810     .addOperand(Scale)
12811     .addOperand(Index)
12812     .addDisp(Disp, 8)
12813     .addOperand(Segment)
12814     .addReg(NextAddrReg)
12815     .setMemRefs(MMOBegin, MMOEnd);
12816
12817   // If we branched, emit the PHI to the front of endMBB.
12818   if (offsetMBB) {
12819     BuildMI(*endMBB, endMBB->begin(), DL,
12820             TII->get(X86::PHI), DestReg)
12821       .addReg(OffsetDestReg).addMBB(offsetMBB)
12822       .addReg(OverflowDestReg).addMBB(overflowMBB);
12823   }
12824
12825   // Erase the pseudo instruction
12826   MI->eraseFromParent();
12827
12828   return endMBB;
12829 }
12830
12831 MachineBasicBlock *
12832 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12833                                                  MachineInstr *MI,
12834                                                  MachineBasicBlock *MBB) const {
12835   // Emit code to save XMM registers to the stack. The ABI says that the
12836   // number of registers to save is given in %al, so it's theoretically
12837   // possible to do an indirect jump trick to avoid saving all of them,
12838   // however this code takes a simpler approach and just executes all
12839   // of the stores if %al is non-zero. It's less code, and it's probably
12840   // easier on the hardware branch predictor, and stores aren't all that
12841   // expensive anyway.
12842
12843   // Create the new basic blocks. One block contains all the XMM stores,
12844   // and one block is the final destination regardless of whether any
12845   // stores were performed.
12846   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12847   MachineFunction *F = MBB->getParent();
12848   MachineFunction::iterator MBBIter = MBB;
12849   ++MBBIter;
12850   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12851   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12852   F->insert(MBBIter, XMMSaveMBB);
12853   F->insert(MBBIter, EndMBB);
12854
12855   // Transfer the remainder of MBB and its successor edges to EndMBB.
12856   EndMBB->splice(EndMBB->begin(), MBB,
12857                  llvm::next(MachineBasicBlock::iterator(MI)),
12858                  MBB->end());
12859   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12860
12861   // The original block will now fall through to the XMM save block.
12862   MBB->addSuccessor(XMMSaveMBB);
12863   // The XMMSaveMBB will fall through to the end block.
12864   XMMSaveMBB->addSuccessor(EndMBB);
12865
12866   // Now add the instructions.
12867   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12868   DebugLoc DL = MI->getDebugLoc();
12869
12870   unsigned CountReg = MI->getOperand(0).getReg();
12871   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12872   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12873
12874   if (!Subtarget->isTargetWin64()) {
12875     // If %al is 0, branch around the XMM save block.
12876     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12877     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12878     MBB->addSuccessor(EndMBB);
12879   }
12880
12881   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12882   // In the XMM save block, save all the XMM argument registers.
12883   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12884     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12885     MachineMemOperand *MMO =
12886       F->getMachineMemOperand(
12887           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12888         MachineMemOperand::MOStore,
12889         /*Size=*/16, /*Align=*/16);
12890     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12891       .addFrameIndex(RegSaveFrameIndex)
12892       .addImm(/*Scale=*/1)
12893       .addReg(/*IndexReg=*/0)
12894       .addImm(/*Disp=*/Offset)
12895       .addReg(/*Segment=*/0)
12896       .addReg(MI->getOperand(i).getReg())
12897       .addMemOperand(MMO);
12898   }
12899
12900   MI->eraseFromParent();   // The pseudo instruction is gone now.
12901
12902   return EndMBB;
12903 }
12904
12905 // The EFLAGS operand of SelectItr might be missing a kill marker
12906 // because there were multiple uses of EFLAGS, and ISel didn't know
12907 // which to mark. Figure out whether SelectItr should have had a
12908 // kill marker, and set it if it should. Returns the correct kill
12909 // marker value.
12910 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12911                                      MachineBasicBlock* BB,
12912                                      const TargetRegisterInfo* TRI) {
12913   // Scan forward through BB for a use/def of EFLAGS.
12914   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12915   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12916     const MachineInstr& mi = *miI;
12917     if (mi.readsRegister(X86::EFLAGS))
12918       return false;
12919     if (mi.definesRegister(X86::EFLAGS))
12920       break; // Should have kill-flag - update below.
12921   }
12922
12923   // If we hit the end of the block, check whether EFLAGS is live into a
12924   // successor.
12925   if (miI == BB->end()) {
12926     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12927                                           sEnd = BB->succ_end();
12928          sItr != sEnd; ++sItr) {
12929       MachineBasicBlock* succ = *sItr;
12930       if (succ->isLiveIn(X86::EFLAGS))
12931         return false;
12932     }
12933   }
12934
12935   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12936   // out. SelectMI should have a kill flag on EFLAGS.
12937   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12938   return true;
12939 }
12940
12941 MachineBasicBlock *
12942 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12943                                      MachineBasicBlock *BB) const {
12944   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12945   DebugLoc DL = MI->getDebugLoc();
12946
12947   // To "insert" a SELECT_CC instruction, we actually have to insert the
12948   // diamond control-flow pattern.  The incoming instruction knows the
12949   // destination vreg to set, the condition code register to branch on, the
12950   // true/false values to select between, and a branch opcode to use.
12951   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12952   MachineFunction::iterator It = BB;
12953   ++It;
12954
12955   //  thisMBB:
12956   //  ...
12957   //   TrueVal = ...
12958   //   cmpTY ccX, r1, r2
12959   //   bCC copy1MBB
12960   //   fallthrough --> copy0MBB
12961   MachineBasicBlock *thisMBB = BB;
12962   MachineFunction *F = BB->getParent();
12963   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12964   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12965   F->insert(It, copy0MBB);
12966   F->insert(It, sinkMBB);
12967
12968   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12969   // live into the sink and copy blocks.
12970   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12971   if (!MI->killsRegister(X86::EFLAGS) &&
12972       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12973     copy0MBB->addLiveIn(X86::EFLAGS);
12974     sinkMBB->addLiveIn(X86::EFLAGS);
12975   }
12976
12977   // Transfer the remainder of BB and its successor edges to sinkMBB.
12978   sinkMBB->splice(sinkMBB->begin(), BB,
12979                   llvm::next(MachineBasicBlock::iterator(MI)),
12980                   BB->end());
12981   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12982
12983   // Add the true and fallthrough blocks as its successors.
12984   BB->addSuccessor(copy0MBB);
12985   BB->addSuccessor(sinkMBB);
12986
12987   // Create the conditional branch instruction.
12988   unsigned Opc =
12989     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12990   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12991
12992   //  copy0MBB:
12993   //   %FalseValue = ...
12994   //   # fallthrough to sinkMBB
12995   copy0MBB->addSuccessor(sinkMBB);
12996
12997   //  sinkMBB:
12998   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12999   //  ...
13000   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13001           TII->get(X86::PHI), MI->getOperand(0).getReg())
13002     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13003     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13004
13005   MI->eraseFromParent();   // The pseudo instruction is gone now.
13006   return sinkMBB;
13007 }
13008
13009 MachineBasicBlock *
13010 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13011                                         bool Is64Bit) const {
13012   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13013   DebugLoc DL = MI->getDebugLoc();
13014   MachineFunction *MF = BB->getParent();
13015   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13016
13017   assert(getTargetMachine().Options.EnableSegmentedStacks);
13018
13019   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13020   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13021
13022   // BB:
13023   //  ... [Till the alloca]
13024   // If stacklet is not large enough, jump to mallocMBB
13025   //
13026   // bumpMBB:
13027   //  Allocate by subtracting from RSP
13028   //  Jump to continueMBB
13029   //
13030   // mallocMBB:
13031   //  Allocate by call to runtime
13032   //
13033   // continueMBB:
13034   //  ...
13035   //  [rest of original BB]
13036   //
13037
13038   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13039   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13040   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13041
13042   MachineRegisterInfo &MRI = MF->getRegInfo();
13043   const TargetRegisterClass *AddrRegClass =
13044     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13045
13046   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13047     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13048     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13049     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13050     sizeVReg = MI->getOperand(1).getReg(),
13051     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13052
13053   MachineFunction::iterator MBBIter = BB;
13054   ++MBBIter;
13055
13056   MF->insert(MBBIter, bumpMBB);
13057   MF->insert(MBBIter, mallocMBB);
13058   MF->insert(MBBIter, continueMBB);
13059
13060   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13061                       (MachineBasicBlock::iterator(MI)), BB->end());
13062   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13063
13064   // Add code to the main basic block to check if the stack limit has been hit,
13065   // and if so, jump to mallocMBB otherwise to bumpMBB.
13066   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13067   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13068     .addReg(tmpSPVReg).addReg(sizeVReg);
13069   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13070     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13071     .addReg(SPLimitVReg);
13072   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13073
13074   // bumpMBB simply decreases the stack pointer, since we know the current
13075   // stacklet has enough space.
13076   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13077     .addReg(SPLimitVReg);
13078   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13079     .addReg(SPLimitVReg);
13080   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13081
13082   // Calls into a routine in libgcc to allocate more space from the heap.
13083   const uint32_t *RegMask =
13084     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13085   if (Is64Bit) {
13086     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13087       .addReg(sizeVReg);
13088     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13089       .addExternalSymbol("__morestack_allocate_stack_space")
13090       .addRegMask(RegMask)
13091       .addReg(X86::RDI, RegState::Implicit)
13092       .addReg(X86::RAX, RegState::ImplicitDefine);
13093   } else {
13094     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13095       .addImm(12);
13096     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13097     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13098       .addExternalSymbol("__morestack_allocate_stack_space")
13099       .addRegMask(RegMask)
13100       .addReg(X86::EAX, RegState::ImplicitDefine);
13101   }
13102
13103   if (!Is64Bit)
13104     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13105       .addImm(16);
13106
13107   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13108     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13109   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13110
13111   // Set up the CFG correctly.
13112   BB->addSuccessor(bumpMBB);
13113   BB->addSuccessor(mallocMBB);
13114   mallocMBB->addSuccessor(continueMBB);
13115   bumpMBB->addSuccessor(continueMBB);
13116
13117   // Take care of the PHI nodes.
13118   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13119           MI->getOperand(0).getReg())
13120     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13121     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13122
13123   // Delete the original pseudo instruction.
13124   MI->eraseFromParent();
13125
13126   // And we're done.
13127   return continueMBB;
13128 }
13129
13130 MachineBasicBlock *
13131 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13132                                           MachineBasicBlock *BB) const {
13133   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13134   DebugLoc DL = MI->getDebugLoc();
13135
13136   assert(!Subtarget->isTargetEnvMacho());
13137
13138   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13139   // non-trivial part is impdef of ESP.
13140
13141   if (Subtarget->isTargetWin64()) {
13142     if (Subtarget->isTargetCygMing()) {
13143       // ___chkstk(Mingw64):
13144       // Clobbers R10, R11, RAX and EFLAGS.
13145       // Updates RSP.
13146       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13147         .addExternalSymbol("___chkstk")
13148         .addReg(X86::RAX, RegState::Implicit)
13149         .addReg(X86::RSP, RegState::Implicit)
13150         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13151         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13152         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13153     } else {
13154       // __chkstk(MSVCRT): does not update stack pointer.
13155       // Clobbers R10, R11 and EFLAGS.
13156       // FIXME: RAX(allocated size) might be reused and not killed.
13157       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13158         .addExternalSymbol("__chkstk")
13159         .addReg(X86::RAX, RegState::Implicit)
13160         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13161       // RAX has the offset to subtracted from RSP.
13162       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13163         .addReg(X86::RSP)
13164         .addReg(X86::RAX);
13165     }
13166   } else {
13167     const char *StackProbeSymbol =
13168       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13169
13170     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13171       .addExternalSymbol(StackProbeSymbol)
13172       .addReg(X86::EAX, RegState::Implicit)
13173       .addReg(X86::ESP, RegState::Implicit)
13174       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13175       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13176       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13177   }
13178
13179   MI->eraseFromParent();   // The pseudo instruction is gone now.
13180   return BB;
13181 }
13182
13183 MachineBasicBlock *
13184 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13185                                       MachineBasicBlock *BB) const {
13186   // This is pretty easy.  We're taking the value that we received from
13187   // our load from the relocation, sticking it in either RDI (x86-64)
13188   // or EAX and doing an indirect call.  The return value will then
13189   // be in the normal return register.
13190   const X86InstrInfo *TII
13191     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13192   DebugLoc DL = MI->getDebugLoc();
13193   MachineFunction *F = BB->getParent();
13194
13195   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13196   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13197
13198   // Get a register mask for the lowered call.
13199   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13200   // proper register mask.
13201   const uint32_t *RegMask =
13202     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13203   if (Subtarget->is64Bit()) {
13204     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13205                                       TII->get(X86::MOV64rm), X86::RDI)
13206     .addReg(X86::RIP)
13207     .addImm(0).addReg(0)
13208     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13209                       MI->getOperand(3).getTargetFlags())
13210     .addReg(0);
13211     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13212     addDirectMem(MIB, X86::RDI);
13213     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13214   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13215     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13216                                       TII->get(X86::MOV32rm), X86::EAX)
13217     .addReg(0)
13218     .addImm(0).addReg(0)
13219     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13220                       MI->getOperand(3).getTargetFlags())
13221     .addReg(0);
13222     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13223     addDirectMem(MIB, X86::EAX);
13224     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13225   } else {
13226     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13227                                       TII->get(X86::MOV32rm), X86::EAX)
13228     .addReg(TII->getGlobalBaseReg(F))
13229     .addImm(0).addReg(0)
13230     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13231                       MI->getOperand(3).getTargetFlags())
13232     .addReg(0);
13233     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13234     addDirectMem(MIB, X86::EAX);
13235     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13236   }
13237
13238   MI->eraseFromParent(); // The pseudo instruction is gone now.
13239   return BB;
13240 }
13241
13242 MachineBasicBlock *
13243 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13244                                     MachineBasicBlock *MBB) const {
13245   DebugLoc DL = MI->getDebugLoc();
13246   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13247
13248   MachineFunction *MF = MBB->getParent();
13249   MachineRegisterInfo &MRI = MF->getRegInfo();
13250
13251   const BasicBlock *BB = MBB->getBasicBlock();
13252   MachineFunction::iterator I = MBB;
13253   ++I;
13254
13255   // Memory Reference
13256   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13257   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13258
13259   unsigned DstReg;
13260   unsigned MemOpndSlot = 0;
13261
13262   unsigned CurOp = 0;
13263
13264   DstReg = MI->getOperand(CurOp++).getReg();
13265   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13266   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13267   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13268   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13269
13270   MemOpndSlot = CurOp;
13271
13272   MVT PVT = getPointerTy();
13273   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13274          "Invalid Pointer Size!");
13275
13276   // For v = setjmp(buf), we generate
13277   //
13278   // thisMBB:
13279   //  buf[Label_Offset] = ljMBB
13280   //  SjLjSetup restoreMBB
13281   //
13282   // mainMBB:
13283   //  v_main = 0
13284   //
13285   // sinkMBB:
13286   //  v = phi(main, restore)
13287   //
13288   // restoreMBB:
13289   //  v_restore = 1
13290
13291   MachineBasicBlock *thisMBB = MBB;
13292   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13293   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13294   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13295   MF->insert(I, mainMBB);
13296   MF->insert(I, sinkMBB);
13297   MF->push_back(restoreMBB);
13298
13299   MachineInstrBuilder MIB;
13300
13301   // Transfer the remainder of BB and its successor edges to sinkMBB.
13302   sinkMBB->splice(sinkMBB->begin(), MBB,
13303                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13304   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13305
13306   // thisMBB:
13307   unsigned PtrImmStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13308   const int64_t Label_Offset = 1 * PVT.getStoreSize();
13309
13310   // Store IP
13311   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrImmStoreOpc));
13312   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13313     if (i == X86::AddrDisp)
13314       MIB.addDisp(MI->getOperand(MemOpndSlot + i), Label_Offset);
13315     else
13316       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13317   }
13318   MIB.addMBB(restoreMBB);
13319   MIB.setMemRefs(MMOBegin, MMOEnd);
13320   // Setup
13321   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13322           .addMBB(restoreMBB);
13323   MIB.addRegMask(RegInfo->getNoPreservedMask());
13324   thisMBB->addSuccessor(mainMBB);
13325   thisMBB->addSuccessor(restoreMBB);
13326
13327   // mainMBB:
13328   //  EAX = 0
13329   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13330   mainMBB->addSuccessor(sinkMBB);
13331
13332   // sinkMBB:
13333   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13334           TII->get(X86::PHI), DstReg)
13335     .addReg(mainDstReg).addMBB(mainMBB)
13336     .addReg(restoreDstReg).addMBB(restoreMBB);
13337
13338   // restoreMBB:
13339   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13340   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13341   restoreMBB->addSuccessor(sinkMBB);
13342
13343   MI->eraseFromParent();
13344   return sinkMBB;
13345 }
13346
13347 MachineBasicBlock *
13348 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13349                                      MachineBasicBlock *MBB) const {
13350   DebugLoc DL = MI->getDebugLoc();
13351   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13352
13353   MachineFunction *MF = MBB->getParent();
13354   MachineRegisterInfo &MRI = MF->getRegInfo();
13355
13356   // Memory Reference
13357   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13358   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13359
13360   MVT PVT = getPointerTy();
13361   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13362          "Invalid Pointer Size!");
13363
13364   const TargetRegisterClass *RC =
13365     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13366   unsigned Tmp = MRI.createVirtualRegister(RC);
13367   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13368   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13369   unsigned SP = RegInfo->getStackRegister();
13370
13371   MachineInstrBuilder MIB;
13372
13373   const int64_t Label_Offset = 1 * PVT.getStoreSize();
13374   const int64_t SP_Offset = 2 * PVT.getStoreSize();
13375
13376   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13377   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13378
13379   // Reload FP
13380   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13381   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13382     MIB.addOperand(MI->getOperand(i));
13383   MIB.setMemRefs(MMOBegin, MMOEnd);
13384   // Reload IP
13385   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13386   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13387     if (i == X86::AddrDisp)
13388       MIB.addDisp(MI->getOperand(i), Label_Offset);
13389     else
13390       MIB.addOperand(MI->getOperand(i));
13391   }
13392   MIB.setMemRefs(MMOBegin, MMOEnd);
13393   // Reload SP
13394   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13395   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13396     if (i == X86::AddrDisp)
13397       MIB.addDisp(MI->getOperand(i), SP_Offset);
13398     else
13399       MIB.addOperand(MI->getOperand(i));
13400   }
13401   MIB.setMemRefs(MMOBegin, MMOEnd);
13402   // Jump
13403   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13404
13405   MI->eraseFromParent();
13406   return MBB;
13407 }
13408
13409 MachineBasicBlock *
13410 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13411                                                MachineBasicBlock *BB) const {
13412   switch (MI->getOpcode()) {
13413   default: llvm_unreachable("Unexpected instr type to insert");
13414   case X86::TAILJMPd64:
13415   case X86::TAILJMPr64:
13416   case X86::TAILJMPm64:
13417     llvm_unreachable("TAILJMP64 would not be touched here.");
13418   case X86::TCRETURNdi64:
13419   case X86::TCRETURNri64:
13420   case X86::TCRETURNmi64:
13421     return BB;
13422   case X86::WIN_ALLOCA:
13423     return EmitLoweredWinAlloca(MI, BB);
13424   case X86::SEG_ALLOCA_32:
13425     return EmitLoweredSegAlloca(MI, BB, false);
13426   case X86::SEG_ALLOCA_64:
13427     return EmitLoweredSegAlloca(MI, BB, true);
13428   case X86::TLSCall_32:
13429   case X86::TLSCall_64:
13430     return EmitLoweredTLSCall(MI, BB);
13431   case X86::CMOV_GR8:
13432   case X86::CMOV_FR32:
13433   case X86::CMOV_FR64:
13434   case X86::CMOV_V4F32:
13435   case X86::CMOV_V2F64:
13436   case X86::CMOV_V2I64:
13437   case X86::CMOV_V8F32:
13438   case X86::CMOV_V4F64:
13439   case X86::CMOV_V4I64:
13440   case X86::CMOV_GR16:
13441   case X86::CMOV_GR32:
13442   case X86::CMOV_RFP32:
13443   case X86::CMOV_RFP64:
13444   case X86::CMOV_RFP80:
13445     return EmitLoweredSelect(MI, BB);
13446
13447   case X86::FP32_TO_INT16_IN_MEM:
13448   case X86::FP32_TO_INT32_IN_MEM:
13449   case X86::FP32_TO_INT64_IN_MEM:
13450   case X86::FP64_TO_INT16_IN_MEM:
13451   case X86::FP64_TO_INT32_IN_MEM:
13452   case X86::FP64_TO_INT64_IN_MEM:
13453   case X86::FP80_TO_INT16_IN_MEM:
13454   case X86::FP80_TO_INT32_IN_MEM:
13455   case X86::FP80_TO_INT64_IN_MEM: {
13456     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13457     DebugLoc DL = MI->getDebugLoc();
13458
13459     // Change the floating point control register to use "round towards zero"
13460     // mode when truncating to an integer value.
13461     MachineFunction *F = BB->getParent();
13462     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13463     addFrameReference(BuildMI(*BB, MI, DL,
13464                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13465
13466     // Load the old value of the high byte of the control word...
13467     unsigned OldCW =
13468       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13469     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13470                       CWFrameIdx);
13471
13472     // Set the high part to be round to zero...
13473     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13474       .addImm(0xC7F);
13475
13476     // Reload the modified control word now...
13477     addFrameReference(BuildMI(*BB, MI, DL,
13478                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13479
13480     // Restore the memory image of control word to original value
13481     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13482       .addReg(OldCW);
13483
13484     // Get the X86 opcode to use.
13485     unsigned Opc;
13486     switch (MI->getOpcode()) {
13487     default: llvm_unreachable("illegal opcode!");
13488     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13489     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13490     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13491     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13492     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13493     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13494     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13495     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13496     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13497     }
13498
13499     X86AddressMode AM;
13500     MachineOperand &Op = MI->getOperand(0);
13501     if (Op.isReg()) {
13502       AM.BaseType = X86AddressMode::RegBase;
13503       AM.Base.Reg = Op.getReg();
13504     } else {
13505       AM.BaseType = X86AddressMode::FrameIndexBase;
13506       AM.Base.FrameIndex = Op.getIndex();
13507     }
13508     Op = MI->getOperand(1);
13509     if (Op.isImm())
13510       AM.Scale = Op.getImm();
13511     Op = MI->getOperand(2);
13512     if (Op.isImm())
13513       AM.IndexReg = Op.getImm();
13514     Op = MI->getOperand(3);
13515     if (Op.isGlobal()) {
13516       AM.GV = Op.getGlobal();
13517     } else {
13518       AM.Disp = Op.getImm();
13519     }
13520     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13521                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13522
13523     // Reload the original control word now.
13524     addFrameReference(BuildMI(*BB, MI, DL,
13525                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13526
13527     MI->eraseFromParent();   // The pseudo instruction is gone now.
13528     return BB;
13529   }
13530     // String/text processing lowering.
13531   case X86::PCMPISTRM128REG:
13532   case X86::VPCMPISTRM128REG:
13533   case X86::PCMPISTRM128MEM:
13534   case X86::VPCMPISTRM128MEM:
13535   case X86::PCMPESTRM128REG:
13536   case X86::VPCMPESTRM128REG:
13537   case X86::PCMPESTRM128MEM:
13538   case X86::VPCMPESTRM128MEM: {
13539     unsigned NumArgs;
13540     bool MemArg;
13541     switch (MI->getOpcode()) {
13542     default: llvm_unreachable("illegal opcode!");
13543     case X86::PCMPISTRM128REG:
13544     case X86::VPCMPISTRM128REG:
13545       NumArgs = 3; MemArg = false; break;
13546     case X86::PCMPISTRM128MEM:
13547     case X86::VPCMPISTRM128MEM:
13548       NumArgs = 3; MemArg = true; break;
13549     case X86::PCMPESTRM128REG:
13550     case X86::VPCMPESTRM128REG:
13551       NumArgs = 5; MemArg = false; break;
13552     case X86::PCMPESTRM128MEM:
13553     case X86::VPCMPESTRM128MEM:
13554       NumArgs = 5; MemArg = true; break;
13555     }
13556     return EmitPCMP(MI, BB, NumArgs, MemArg);
13557   }
13558
13559     // Thread synchronization.
13560   case X86::MONITOR:
13561     return EmitMonitor(MI, BB);
13562
13563     // Atomic Lowering.
13564   case X86::ATOMAND8:
13565   case X86::ATOMAND16:
13566   case X86::ATOMAND32:
13567   case X86::ATOMAND64:
13568     // Fall through
13569   case X86::ATOMOR8:
13570   case X86::ATOMOR16:
13571   case X86::ATOMOR32:
13572   case X86::ATOMOR64:
13573     // Fall through
13574   case X86::ATOMXOR16:
13575   case X86::ATOMXOR8:
13576   case X86::ATOMXOR32:
13577   case X86::ATOMXOR64:
13578     // Fall through
13579   case X86::ATOMNAND8:
13580   case X86::ATOMNAND16:
13581   case X86::ATOMNAND32:
13582   case X86::ATOMNAND64:
13583     // Fall through
13584   case X86::ATOMMAX8:
13585   case X86::ATOMMAX16:
13586   case X86::ATOMMAX32:
13587   case X86::ATOMMAX64:
13588     // Fall through
13589   case X86::ATOMMIN8:
13590   case X86::ATOMMIN16:
13591   case X86::ATOMMIN32:
13592   case X86::ATOMMIN64:
13593     // Fall through
13594   case X86::ATOMUMAX8:
13595   case X86::ATOMUMAX16:
13596   case X86::ATOMUMAX32:
13597   case X86::ATOMUMAX64:
13598     // Fall through
13599   case X86::ATOMUMIN8:
13600   case X86::ATOMUMIN16:
13601   case X86::ATOMUMIN32:
13602   case X86::ATOMUMIN64:
13603     return EmitAtomicLoadArith(MI, BB);
13604
13605   // This group does 64-bit operations on a 32-bit host.
13606   case X86::ATOMAND6432:
13607   case X86::ATOMOR6432:
13608   case X86::ATOMXOR6432:
13609   case X86::ATOMNAND6432:
13610   case X86::ATOMADD6432:
13611   case X86::ATOMSUB6432:
13612   case X86::ATOMMAX6432:
13613   case X86::ATOMMIN6432:
13614   case X86::ATOMUMAX6432:
13615   case X86::ATOMUMIN6432:
13616   case X86::ATOMSWAP6432:
13617     return EmitAtomicLoadArith6432(MI, BB);
13618
13619   case X86::VASTART_SAVE_XMM_REGS:
13620     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13621
13622   case X86::VAARG_64:
13623     return EmitVAARG64WithCustomInserter(MI, BB);
13624
13625   case X86::EH_SjLj_SetJmp32:
13626   case X86::EH_SjLj_SetJmp64:
13627     return emitEHSjLjSetJmp(MI, BB);
13628
13629   case X86::EH_SjLj_LongJmp32:
13630   case X86::EH_SjLj_LongJmp64:
13631     return emitEHSjLjLongJmp(MI, BB);
13632   }
13633 }
13634
13635 //===----------------------------------------------------------------------===//
13636 //                           X86 Optimization Hooks
13637 //===----------------------------------------------------------------------===//
13638
13639 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13640                                                        APInt &KnownZero,
13641                                                        APInt &KnownOne,
13642                                                        const SelectionDAG &DAG,
13643                                                        unsigned Depth) const {
13644   unsigned BitWidth = KnownZero.getBitWidth();
13645   unsigned Opc = Op.getOpcode();
13646   assert((Opc >= ISD::BUILTIN_OP_END ||
13647           Opc == ISD::INTRINSIC_WO_CHAIN ||
13648           Opc == ISD::INTRINSIC_W_CHAIN ||
13649           Opc == ISD::INTRINSIC_VOID) &&
13650          "Should use MaskedValueIsZero if you don't know whether Op"
13651          " is a target node!");
13652
13653   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13654   switch (Opc) {
13655   default: break;
13656   case X86ISD::ADD:
13657   case X86ISD::SUB:
13658   case X86ISD::ADC:
13659   case X86ISD::SBB:
13660   case X86ISD::SMUL:
13661   case X86ISD::UMUL:
13662   case X86ISD::INC:
13663   case X86ISD::DEC:
13664   case X86ISD::OR:
13665   case X86ISD::XOR:
13666   case X86ISD::AND:
13667     // These nodes' second result is a boolean.
13668     if (Op.getResNo() == 0)
13669       break;
13670     // Fallthrough
13671   case X86ISD::SETCC:
13672     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13673     break;
13674   case ISD::INTRINSIC_WO_CHAIN: {
13675     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13676     unsigned NumLoBits = 0;
13677     switch (IntId) {
13678     default: break;
13679     case Intrinsic::x86_sse_movmsk_ps:
13680     case Intrinsic::x86_avx_movmsk_ps_256:
13681     case Intrinsic::x86_sse2_movmsk_pd:
13682     case Intrinsic::x86_avx_movmsk_pd_256:
13683     case Intrinsic::x86_mmx_pmovmskb:
13684     case Intrinsic::x86_sse2_pmovmskb_128:
13685     case Intrinsic::x86_avx2_pmovmskb: {
13686       // High bits of movmskp{s|d}, pmovmskb are known zero.
13687       switch (IntId) {
13688         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13689         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13690         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13691         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13692         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13693         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13694         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13695         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13696       }
13697       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13698       break;
13699     }
13700     }
13701     break;
13702   }
13703   }
13704 }
13705
13706 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13707                                                          unsigned Depth) const {
13708   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13709   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13710     return Op.getValueType().getScalarType().getSizeInBits();
13711
13712   // Fallback case.
13713   return 1;
13714 }
13715
13716 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13717 /// node is a GlobalAddress + offset.
13718 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13719                                        const GlobalValue* &GA,
13720                                        int64_t &Offset) const {
13721   if (N->getOpcode() == X86ISD::Wrapper) {
13722     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13723       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13724       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13725       return true;
13726     }
13727   }
13728   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13729 }
13730
13731 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13732 /// same as extracting the high 128-bit part of 256-bit vector and then
13733 /// inserting the result into the low part of a new 256-bit vector
13734 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13735   EVT VT = SVOp->getValueType(0);
13736   unsigned NumElems = VT.getVectorNumElements();
13737
13738   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13739   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13740     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13741         SVOp->getMaskElt(j) >= 0)
13742       return false;
13743
13744   return true;
13745 }
13746
13747 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13748 /// same as extracting the low 128-bit part of 256-bit vector and then
13749 /// inserting the result into the high part of a new 256-bit vector
13750 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13751   EVT VT = SVOp->getValueType(0);
13752   unsigned NumElems = VT.getVectorNumElements();
13753
13754   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13755   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13756     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13757         SVOp->getMaskElt(j) >= 0)
13758       return false;
13759
13760   return true;
13761 }
13762
13763 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13764 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13765                                         TargetLowering::DAGCombinerInfo &DCI,
13766                                         const X86Subtarget* Subtarget) {
13767   DebugLoc dl = N->getDebugLoc();
13768   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13769   SDValue V1 = SVOp->getOperand(0);
13770   SDValue V2 = SVOp->getOperand(1);
13771   EVT VT = SVOp->getValueType(0);
13772   unsigned NumElems = VT.getVectorNumElements();
13773
13774   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13775       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13776     //
13777     //                   0,0,0,...
13778     //                      |
13779     //    V      UNDEF    BUILD_VECTOR    UNDEF
13780     //     \      /           \           /
13781     //  CONCAT_VECTOR         CONCAT_VECTOR
13782     //         \                  /
13783     //          \                /
13784     //          RESULT: V + zero extended
13785     //
13786     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13787         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13788         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13789       return SDValue();
13790
13791     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13792       return SDValue();
13793
13794     // To match the shuffle mask, the first half of the mask should
13795     // be exactly the first vector, and all the rest a splat with the
13796     // first element of the second one.
13797     for (unsigned i = 0; i != NumElems/2; ++i)
13798       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13799           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13800         return SDValue();
13801
13802     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13803     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13804       if (Ld->hasNUsesOfValue(1, 0)) {
13805         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13806         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13807         SDValue ResNode =
13808           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13809                                   Ld->getMemoryVT(),
13810                                   Ld->getPointerInfo(),
13811                                   Ld->getAlignment(),
13812                                   false/*isVolatile*/, true/*ReadMem*/,
13813                                   false/*WriteMem*/);
13814         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13815       }
13816     }
13817
13818     // Emit a zeroed vector and insert the desired subvector on its
13819     // first half.
13820     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13821     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13822     return DCI.CombineTo(N, InsV);
13823   }
13824
13825   //===--------------------------------------------------------------------===//
13826   // Combine some shuffles into subvector extracts and inserts:
13827   //
13828
13829   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13830   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13831     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13832     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13833     return DCI.CombineTo(N, InsV);
13834   }
13835
13836   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13837   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13838     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13839     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13840     return DCI.CombineTo(N, InsV);
13841   }
13842
13843   return SDValue();
13844 }
13845
13846 /// PerformShuffleCombine - Performs several different shuffle combines.
13847 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13848                                      TargetLowering::DAGCombinerInfo &DCI,
13849                                      const X86Subtarget *Subtarget) {
13850   DebugLoc dl = N->getDebugLoc();
13851   EVT VT = N->getValueType(0);
13852
13853   // Don't create instructions with illegal types after legalize types has run.
13854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13855   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13856     return SDValue();
13857
13858   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13859   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13860       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13861     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13862
13863   // Only handle 128 wide vector from here on.
13864   if (!VT.is128BitVector())
13865     return SDValue();
13866
13867   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13868   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13869   // consecutive, non-overlapping, and in the right order.
13870   SmallVector<SDValue, 16> Elts;
13871   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13872     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13873
13874   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13875 }
13876
13877
13878 /// PerformTruncateCombine - Converts truncate operation to
13879 /// a sequence of vector shuffle operations.
13880 /// It is possible when we truncate 256-bit vector to 128-bit vector
13881 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13882                                       TargetLowering::DAGCombinerInfo &DCI,
13883                                       const X86Subtarget *Subtarget)  {
13884   if (!DCI.isBeforeLegalizeOps())
13885     return SDValue();
13886
13887   if (!Subtarget->hasAVX())
13888     return SDValue();
13889
13890   EVT VT = N->getValueType(0);
13891   SDValue Op = N->getOperand(0);
13892   EVT OpVT = Op.getValueType();
13893   DebugLoc dl = N->getDebugLoc();
13894
13895   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13896
13897     if (Subtarget->hasAVX2()) {
13898       // AVX2: v4i64 -> v4i32
13899
13900       // VPERMD
13901       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13902
13903       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13904       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13905                                 ShufMask);
13906
13907       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13908                          DAG.getIntPtrConstant(0));
13909     }
13910
13911     // AVX: v4i64 -> v4i32
13912     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13913                                DAG.getIntPtrConstant(0));
13914
13915     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13916                                DAG.getIntPtrConstant(2));
13917
13918     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13919     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13920
13921     // PSHUFD
13922     static const int ShufMask1[] = {0, 2, 0, 0};
13923
13924     SDValue Undef = DAG.getUNDEF(VT);
13925     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13926     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13927
13928     // MOVLHPS
13929     static const int ShufMask2[] = {0, 1, 4, 5};
13930
13931     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13932   }
13933
13934   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13935
13936     if (Subtarget->hasAVX2()) {
13937       // AVX2: v8i32 -> v8i16
13938
13939       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13940
13941       // PSHUFB
13942       SmallVector<SDValue,32> pshufbMask;
13943       for (unsigned i = 0; i < 2; ++i) {
13944         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13945         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13946         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13947         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13948         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13949         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13950         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13951         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13952         for (unsigned j = 0; j < 8; ++j)
13953           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13954       }
13955       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13956                                &pshufbMask[0], 32);
13957       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13958
13959       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13960
13961       static const int ShufMask[] = {0,  2,  -1,  -1};
13962       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13963                                 &ShufMask[0]);
13964
13965       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13966                        DAG.getIntPtrConstant(0));
13967
13968       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13969     }
13970
13971     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13972                                DAG.getIntPtrConstant(0));
13973
13974     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13975                                DAG.getIntPtrConstant(4));
13976
13977     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13978     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13979
13980     // PSHUFB
13981     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13982                                    -1, -1, -1, -1, -1, -1, -1, -1};
13983
13984     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13985     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13986     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13987
13988     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13989     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13990
13991     // MOVLHPS
13992     static const int ShufMask2[] = {0, 1, 4, 5};
13993
13994     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13995     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13996   }
13997
13998   return SDValue();
13999 }
14000
14001 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14002 /// specific shuffle of a load can be folded into a single element load.
14003 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14004 /// shuffles have been customed lowered so we need to handle those here.
14005 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14006                                          TargetLowering::DAGCombinerInfo &DCI) {
14007   if (DCI.isBeforeLegalizeOps())
14008     return SDValue();
14009
14010   SDValue InVec = N->getOperand(0);
14011   SDValue EltNo = N->getOperand(1);
14012
14013   if (!isa<ConstantSDNode>(EltNo))
14014     return SDValue();
14015
14016   EVT VT = InVec.getValueType();
14017
14018   bool HasShuffleIntoBitcast = false;
14019   if (InVec.getOpcode() == ISD::BITCAST) {
14020     // Don't duplicate a load with other uses.
14021     if (!InVec.hasOneUse())
14022       return SDValue();
14023     EVT BCVT = InVec.getOperand(0).getValueType();
14024     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14025       return SDValue();
14026     InVec = InVec.getOperand(0);
14027     HasShuffleIntoBitcast = true;
14028   }
14029
14030   if (!isTargetShuffle(InVec.getOpcode()))
14031     return SDValue();
14032
14033   // Don't duplicate a load with other uses.
14034   if (!InVec.hasOneUse())
14035     return SDValue();
14036
14037   SmallVector<int, 16> ShuffleMask;
14038   bool UnaryShuffle;
14039   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14040                             UnaryShuffle))
14041     return SDValue();
14042
14043   // Select the input vector, guarding against out of range extract vector.
14044   unsigned NumElems = VT.getVectorNumElements();
14045   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14046   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14047   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14048                                          : InVec.getOperand(1);
14049
14050   // If inputs to shuffle are the same for both ops, then allow 2 uses
14051   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14052
14053   if (LdNode.getOpcode() == ISD::BITCAST) {
14054     // Don't duplicate a load with other uses.
14055     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14056       return SDValue();
14057
14058     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14059     LdNode = LdNode.getOperand(0);
14060   }
14061
14062   if (!ISD::isNormalLoad(LdNode.getNode()))
14063     return SDValue();
14064
14065   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14066
14067   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14068     return SDValue();
14069
14070   if (HasShuffleIntoBitcast) {
14071     // If there's a bitcast before the shuffle, check if the load type and
14072     // alignment is valid.
14073     unsigned Align = LN0->getAlignment();
14074     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14075     unsigned NewAlign = TLI.getDataLayout()->
14076       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14077
14078     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14079       return SDValue();
14080   }
14081
14082   // All checks match so transform back to vector_shuffle so that DAG combiner
14083   // can finish the job
14084   DebugLoc dl = N->getDebugLoc();
14085
14086   // Create shuffle node taking into account the case that its a unary shuffle
14087   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14088   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14089                                  InVec.getOperand(0), Shuffle,
14090                                  &ShuffleMask[0]);
14091   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14092   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14093                      EltNo);
14094 }
14095
14096 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14097 /// generation and convert it from being a bunch of shuffles and extracts
14098 /// to a simple store and scalar loads to extract the elements.
14099 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14100                                          TargetLowering::DAGCombinerInfo &DCI) {
14101   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14102   if (NewOp.getNode())
14103     return NewOp;
14104
14105   SDValue InputVector = N->getOperand(0);
14106
14107   // Only operate on vectors of 4 elements, where the alternative shuffling
14108   // gets to be more expensive.
14109   if (InputVector.getValueType() != MVT::v4i32)
14110     return SDValue();
14111
14112   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14113   // single use which is a sign-extend or zero-extend, and all elements are
14114   // used.
14115   SmallVector<SDNode *, 4> Uses;
14116   unsigned ExtractedElements = 0;
14117   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14118        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14119     if (UI.getUse().getResNo() != InputVector.getResNo())
14120       return SDValue();
14121
14122     SDNode *Extract = *UI;
14123     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14124       return SDValue();
14125
14126     if (Extract->getValueType(0) != MVT::i32)
14127       return SDValue();
14128     if (!Extract->hasOneUse())
14129       return SDValue();
14130     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14131         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14132       return SDValue();
14133     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14134       return SDValue();
14135
14136     // Record which element was extracted.
14137     ExtractedElements |=
14138       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14139
14140     Uses.push_back(Extract);
14141   }
14142
14143   // If not all the elements were used, this may not be worthwhile.
14144   if (ExtractedElements != 15)
14145     return SDValue();
14146
14147   // Ok, we've now decided to do the transformation.
14148   DebugLoc dl = InputVector.getDebugLoc();
14149
14150   // Store the value to a temporary stack slot.
14151   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14152   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14153                             MachinePointerInfo(), false, false, 0);
14154
14155   // Replace each use (extract) with a load of the appropriate element.
14156   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14157        UE = Uses.end(); UI != UE; ++UI) {
14158     SDNode *Extract = *UI;
14159
14160     // cOMpute the element's address.
14161     SDValue Idx = Extract->getOperand(1);
14162     unsigned EltSize =
14163         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14164     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14165     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14166     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14167
14168     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14169                                      StackPtr, OffsetVal);
14170
14171     // Load the scalar.
14172     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14173                                      ScalarAddr, MachinePointerInfo(),
14174                                      false, false, false, 0);
14175
14176     // Replace the exact with the load.
14177     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14178   }
14179
14180   // The replacement was made in place; don't return anything.
14181   return SDValue();
14182 }
14183
14184 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14185 /// nodes.
14186 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14187                                     TargetLowering::DAGCombinerInfo &DCI,
14188                                     const X86Subtarget *Subtarget) {
14189   DebugLoc DL = N->getDebugLoc();
14190   SDValue Cond = N->getOperand(0);
14191   // Get the LHS/RHS of the select.
14192   SDValue LHS = N->getOperand(1);
14193   SDValue RHS = N->getOperand(2);
14194   EVT VT = LHS.getValueType();
14195
14196   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14197   // instructions match the semantics of the common C idiom x<y?x:y but not
14198   // x<=y?x:y, because of how they handle negative zero (which can be
14199   // ignored in unsafe-math mode).
14200   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14201       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14202       (Subtarget->hasSSE2() ||
14203        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14204     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14205
14206     unsigned Opcode = 0;
14207     // Check for x CC y ? x : y.
14208     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14209         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14210       switch (CC) {
14211       default: break;
14212       case ISD::SETULT:
14213         // Converting this to a min would handle NaNs incorrectly, and swapping
14214         // the operands would cause it to handle comparisons between positive
14215         // and negative zero incorrectly.
14216         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14217           if (!DAG.getTarget().Options.UnsafeFPMath &&
14218               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14219             break;
14220           std::swap(LHS, RHS);
14221         }
14222         Opcode = X86ISD::FMIN;
14223         break;
14224       case ISD::SETOLE:
14225         // Converting this to a min would handle comparisons between positive
14226         // and negative zero incorrectly.
14227         if (!DAG.getTarget().Options.UnsafeFPMath &&
14228             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14229           break;
14230         Opcode = X86ISD::FMIN;
14231         break;
14232       case ISD::SETULE:
14233         // Converting this to a min would handle both negative zeros and NaNs
14234         // incorrectly, but we can swap the operands to fix both.
14235         std::swap(LHS, RHS);
14236       case ISD::SETOLT:
14237       case ISD::SETLT:
14238       case ISD::SETLE:
14239         Opcode = X86ISD::FMIN;
14240         break;
14241
14242       case ISD::SETOGE:
14243         // Converting this to a max would handle comparisons between positive
14244         // and negative zero incorrectly.
14245         if (!DAG.getTarget().Options.UnsafeFPMath &&
14246             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14247           break;
14248         Opcode = X86ISD::FMAX;
14249         break;
14250       case ISD::SETUGT:
14251         // Converting this to a max would handle NaNs incorrectly, and swapping
14252         // the operands would cause it to handle comparisons between positive
14253         // and negative zero incorrectly.
14254         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14255           if (!DAG.getTarget().Options.UnsafeFPMath &&
14256               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14257             break;
14258           std::swap(LHS, RHS);
14259         }
14260         Opcode = X86ISD::FMAX;
14261         break;
14262       case ISD::SETUGE:
14263         // Converting this to a max would handle both negative zeros and NaNs
14264         // incorrectly, but we can swap the operands to fix both.
14265         std::swap(LHS, RHS);
14266       case ISD::SETOGT:
14267       case ISD::SETGT:
14268       case ISD::SETGE:
14269         Opcode = X86ISD::FMAX;
14270         break;
14271       }
14272     // Check for x CC y ? y : x -- a min/max with reversed arms.
14273     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14274                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14275       switch (CC) {
14276       default: break;
14277       case ISD::SETOGE:
14278         // Converting this to a min would handle comparisons between positive
14279         // and negative zero incorrectly, and swapping the operands would
14280         // cause it to handle NaNs incorrectly.
14281         if (!DAG.getTarget().Options.UnsafeFPMath &&
14282             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14283           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14284             break;
14285           std::swap(LHS, RHS);
14286         }
14287         Opcode = X86ISD::FMIN;
14288         break;
14289       case ISD::SETUGT:
14290         // Converting this to a min would handle NaNs incorrectly.
14291         if (!DAG.getTarget().Options.UnsafeFPMath &&
14292             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14293           break;
14294         Opcode = X86ISD::FMIN;
14295         break;
14296       case ISD::SETUGE:
14297         // Converting this to a min would handle both negative zeros and NaNs
14298         // incorrectly, but we can swap the operands to fix both.
14299         std::swap(LHS, RHS);
14300       case ISD::SETOGT:
14301       case ISD::SETGT:
14302       case ISD::SETGE:
14303         Opcode = X86ISD::FMIN;
14304         break;
14305
14306       case ISD::SETULT:
14307         // Converting this to a max would handle NaNs incorrectly.
14308         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14309           break;
14310         Opcode = X86ISD::FMAX;
14311         break;
14312       case ISD::SETOLE:
14313         // Converting this to a max would handle comparisons between positive
14314         // and negative zero incorrectly, and swapping the operands would
14315         // cause it to handle NaNs incorrectly.
14316         if (!DAG.getTarget().Options.UnsafeFPMath &&
14317             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14318           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14319             break;
14320           std::swap(LHS, RHS);
14321         }
14322         Opcode = X86ISD::FMAX;
14323         break;
14324       case ISD::SETULE:
14325         // Converting this to a max would handle both negative zeros and NaNs
14326         // incorrectly, but we can swap the operands to fix both.
14327         std::swap(LHS, RHS);
14328       case ISD::SETOLT:
14329       case ISD::SETLT:
14330       case ISD::SETLE:
14331         Opcode = X86ISD::FMAX;
14332         break;
14333       }
14334     }
14335
14336     if (Opcode)
14337       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14338   }
14339
14340   // If this is a select between two integer constants, try to do some
14341   // optimizations.
14342   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14343     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14344       // Don't do this for crazy integer types.
14345       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14346         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14347         // so that TrueC (the true value) is larger than FalseC.
14348         bool NeedsCondInvert = false;
14349
14350         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14351             // Efficiently invertible.
14352             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14353              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14354               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14355           NeedsCondInvert = true;
14356           std::swap(TrueC, FalseC);
14357         }
14358
14359         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14360         if (FalseC->getAPIntValue() == 0 &&
14361             TrueC->getAPIntValue().isPowerOf2()) {
14362           if (NeedsCondInvert) // Invert the condition if needed.
14363             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14364                                DAG.getConstant(1, Cond.getValueType()));
14365
14366           // Zero extend the condition if needed.
14367           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14368
14369           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14370           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14371                              DAG.getConstant(ShAmt, MVT::i8));
14372         }
14373
14374         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14375         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14376           if (NeedsCondInvert) // Invert the condition if needed.
14377             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14378                                DAG.getConstant(1, Cond.getValueType()));
14379
14380           // Zero extend the condition if needed.
14381           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14382                              FalseC->getValueType(0), Cond);
14383           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14384                              SDValue(FalseC, 0));
14385         }
14386
14387         // Optimize cases that will turn into an LEA instruction.  This requires
14388         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14389         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14390           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14391           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14392
14393           bool isFastMultiplier = false;
14394           if (Diff < 10) {
14395             switch ((unsigned char)Diff) {
14396               default: break;
14397               case 1:  // result = add base, cond
14398               case 2:  // result = lea base(    , cond*2)
14399               case 3:  // result = lea base(cond, cond*2)
14400               case 4:  // result = lea base(    , cond*4)
14401               case 5:  // result = lea base(cond, cond*4)
14402               case 8:  // result = lea base(    , cond*8)
14403               case 9:  // result = lea base(cond, cond*8)
14404                 isFastMultiplier = true;
14405                 break;
14406             }
14407           }
14408
14409           if (isFastMultiplier) {
14410             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14411             if (NeedsCondInvert) // Invert the condition if needed.
14412               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14413                                  DAG.getConstant(1, Cond.getValueType()));
14414
14415             // Zero extend the condition if needed.
14416             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14417                                Cond);
14418             // Scale the condition by the difference.
14419             if (Diff != 1)
14420               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14421                                  DAG.getConstant(Diff, Cond.getValueType()));
14422
14423             // Add the base if non-zero.
14424             if (FalseC->getAPIntValue() != 0)
14425               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14426                                  SDValue(FalseC, 0));
14427             return Cond;
14428           }
14429         }
14430       }
14431   }
14432
14433   // Canonicalize max and min:
14434   // (x > y) ? x : y -> (x >= y) ? x : y
14435   // (x < y) ? x : y -> (x <= y) ? x : y
14436   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14437   // the need for an extra compare
14438   // against zero. e.g.
14439   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14440   // subl   %esi, %edi
14441   // testl  %edi, %edi
14442   // movl   $0, %eax
14443   // cmovgl %edi, %eax
14444   // =>
14445   // xorl   %eax, %eax
14446   // subl   %esi, $edi
14447   // cmovsl %eax, %edi
14448   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14449       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14450       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14451     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14452     switch (CC) {
14453     default: break;
14454     case ISD::SETLT:
14455     case ISD::SETGT: {
14456       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14457       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14458                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14459       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14460     }
14461     }
14462   }
14463
14464   // If we know that this node is legal then we know that it is going to be
14465   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14466   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14467   // to simplify previous instructions.
14468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14469   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14470       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14471     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14472
14473     // Don't optimize vector selects that map to mask-registers.
14474     if (BitWidth == 1)
14475       return SDValue();
14476
14477     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14478     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14479
14480     APInt KnownZero, KnownOne;
14481     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14482                                           DCI.isBeforeLegalizeOps());
14483     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14484         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14485       DCI.CommitTargetLoweringOpt(TLO);
14486   }
14487
14488   return SDValue();
14489 }
14490
14491 // Check whether a boolean test is testing a boolean value generated by
14492 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14493 // code.
14494 //
14495 // Simplify the following patterns:
14496 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14497 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14498 // to (Op EFLAGS Cond)
14499 //
14500 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14501 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14502 // to (Op EFLAGS !Cond)
14503 //
14504 // where Op could be BRCOND or CMOV.
14505 //
14506 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14507   // Quit if not CMP and SUB with its value result used.
14508   if (Cmp.getOpcode() != X86ISD::CMP &&
14509       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14510       return SDValue();
14511
14512   // Quit if not used as a boolean value.
14513   if (CC != X86::COND_E && CC != X86::COND_NE)
14514     return SDValue();
14515
14516   // Check CMP operands. One of them should be 0 or 1 and the other should be
14517   // an SetCC or extended from it.
14518   SDValue Op1 = Cmp.getOperand(0);
14519   SDValue Op2 = Cmp.getOperand(1);
14520
14521   SDValue SetCC;
14522   const ConstantSDNode* C = 0;
14523   bool needOppositeCond = (CC == X86::COND_E);
14524
14525   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14526     SetCC = Op2;
14527   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14528     SetCC = Op1;
14529   else // Quit if all operands are not constants.
14530     return SDValue();
14531
14532   if (C->getZExtValue() == 1)
14533     needOppositeCond = !needOppositeCond;
14534   else if (C->getZExtValue() != 0)
14535     // Quit if the constant is neither 0 or 1.
14536     return SDValue();
14537
14538   // Skip 'zext' node.
14539   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14540     SetCC = SetCC.getOperand(0);
14541
14542   switch (SetCC.getOpcode()) {
14543   case X86ISD::SETCC:
14544     // Set the condition code or opposite one if necessary.
14545     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14546     if (needOppositeCond)
14547       CC = X86::GetOppositeBranchCondition(CC);
14548     return SetCC.getOperand(1);
14549   case X86ISD::CMOV: {
14550     // Check whether false/true value has canonical one, i.e. 0 or 1.
14551     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14552     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14553     // Quit if true value is not a constant.
14554     if (!TVal)
14555       return SDValue();
14556     // Quit if false value is not a constant.
14557     if (!FVal) {
14558       // A special case for rdrand, where 0 is set if false cond is found.
14559       SDValue Op = SetCC.getOperand(0);
14560       if (Op.getOpcode() != X86ISD::RDRAND)
14561         return SDValue();
14562     }
14563     // Quit if false value is not the constant 0 or 1.
14564     bool FValIsFalse = true;
14565     if (FVal && FVal->getZExtValue() != 0) {
14566       if (FVal->getZExtValue() != 1)
14567         return SDValue();
14568       // If FVal is 1, opposite cond is needed.
14569       needOppositeCond = !needOppositeCond;
14570       FValIsFalse = false;
14571     }
14572     // Quit if TVal is not the constant opposite of FVal.
14573     if (FValIsFalse && TVal->getZExtValue() != 1)
14574       return SDValue();
14575     if (!FValIsFalse && TVal->getZExtValue() != 0)
14576       return SDValue();
14577     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14578     if (needOppositeCond)
14579       CC = X86::GetOppositeBranchCondition(CC);
14580     return SetCC.getOperand(3);
14581   }
14582   }
14583
14584   return SDValue();
14585 }
14586
14587 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14588 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14589                                   TargetLowering::DAGCombinerInfo &DCI,
14590                                   const X86Subtarget *Subtarget) {
14591   DebugLoc DL = N->getDebugLoc();
14592
14593   // If the flag operand isn't dead, don't touch this CMOV.
14594   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14595     return SDValue();
14596
14597   SDValue FalseOp = N->getOperand(0);
14598   SDValue TrueOp = N->getOperand(1);
14599   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14600   SDValue Cond = N->getOperand(3);
14601
14602   if (CC == X86::COND_E || CC == X86::COND_NE) {
14603     switch (Cond.getOpcode()) {
14604     default: break;
14605     case X86ISD::BSR:
14606     case X86ISD::BSF:
14607       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14608       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14609         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14610     }
14611   }
14612
14613   SDValue Flags;
14614
14615   Flags = checkBoolTestSetCCCombine(Cond, CC);
14616   if (Flags.getNode() &&
14617       // Extra check as FCMOV only supports a subset of X86 cond.
14618       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14619     SDValue Ops[] = { FalseOp, TrueOp,
14620                       DAG.getConstant(CC, MVT::i8), Flags };
14621     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14622                        Ops, array_lengthof(Ops));
14623   }
14624
14625   // If this is a select between two integer constants, try to do some
14626   // optimizations.  Note that the operands are ordered the opposite of SELECT
14627   // operands.
14628   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14629     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14630       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14631       // larger than FalseC (the false value).
14632       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14633         CC = X86::GetOppositeBranchCondition(CC);
14634         std::swap(TrueC, FalseC);
14635       }
14636
14637       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14638       // This is efficient for any integer data type (including i8/i16) and
14639       // shift amount.
14640       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14641         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14642                            DAG.getConstant(CC, MVT::i8), Cond);
14643
14644         // Zero extend the condition if needed.
14645         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14646
14647         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14648         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14649                            DAG.getConstant(ShAmt, MVT::i8));
14650         if (N->getNumValues() == 2)  // Dead flag value?
14651           return DCI.CombineTo(N, Cond, SDValue());
14652         return Cond;
14653       }
14654
14655       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14656       // for any integer data type, including i8/i16.
14657       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14658         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14659                            DAG.getConstant(CC, MVT::i8), Cond);
14660
14661         // Zero extend the condition if needed.
14662         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14663                            FalseC->getValueType(0), Cond);
14664         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14665                            SDValue(FalseC, 0));
14666
14667         if (N->getNumValues() == 2)  // Dead flag value?
14668           return DCI.CombineTo(N, Cond, SDValue());
14669         return Cond;
14670       }
14671
14672       // Optimize cases that will turn into an LEA instruction.  This requires
14673       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14674       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14675         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14676         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14677
14678         bool isFastMultiplier = false;
14679         if (Diff < 10) {
14680           switch ((unsigned char)Diff) {
14681           default: break;
14682           case 1:  // result = add base, cond
14683           case 2:  // result = lea base(    , cond*2)
14684           case 3:  // result = lea base(cond, cond*2)
14685           case 4:  // result = lea base(    , cond*4)
14686           case 5:  // result = lea base(cond, cond*4)
14687           case 8:  // result = lea base(    , cond*8)
14688           case 9:  // result = lea base(cond, cond*8)
14689             isFastMultiplier = true;
14690             break;
14691           }
14692         }
14693
14694         if (isFastMultiplier) {
14695           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14696           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14697                              DAG.getConstant(CC, MVT::i8), Cond);
14698           // Zero extend the condition if needed.
14699           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14700                              Cond);
14701           // Scale the condition by the difference.
14702           if (Diff != 1)
14703             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14704                                DAG.getConstant(Diff, Cond.getValueType()));
14705
14706           // Add the base if non-zero.
14707           if (FalseC->getAPIntValue() != 0)
14708             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14709                                SDValue(FalseC, 0));
14710           if (N->getNumValues() == 2)  // Dead flag value?
14711             return DCI.CombineTo(N, Cond, SDValue());
14712           return Cond;
14713         }
14714       }
14715     }
14716   }
14717   return SDValue();
14718 }
14719
14720
14721 /// PerformMulCombine - Optimize a single multiply with constant into two
14722 /// in order to implement it with two cheaper instructions, e.g.
14723 /// LEA + SHL, LEA + LEA.
14724 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14725                                  TargetLowering::DAGCombinerInfo &DCI) {
14726   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14727     return SDValue();
14728
14729   EVT VT = N->getValueType(0);
14730   if (VT != MVT::i64)
14731     return SDValue();
14732
14733   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14734   if (!C)
14735     return SDValue();
14736   uint64_t MulAmt = C->getZExtValue();
14737   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14738     return SDValue();
14739
14740   uint64_t MulAmt1 = 0;
14741   uint64_t MulAmt2 = 0;
14742   if ((MulAmt % 9) == 0) {
14743     MulAmt1 = 9;
14744     MulAmt2 = MulAmt / 9;
14745   } else if ((MulAmt % 5) == 0) {
14746     MulAmt1 = 5;
14747     MulAmt2 = MulAmt / 5;
14748   } else if ((MulAmt % 3) == 0) {
14749     MulAmt1 = 3;
14750     MulAmt2 = MulAmt / 3;
14751   }
14752   if (MulAmt2 &&
14753       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14754     DebugLoc DL = N->getDebugLoc();
14755
14756     if (isPowerOf2_64(MulAmt2) &&
14757         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14758       // If second multiplifer is pow2, issue it first. We want the multiply by
14759       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14760       // is an add.
14761       std::swap(MulAmt1, MulAmt2);
14762
14763     SDValue NewMul;
14764     if (isPowerOf2_64(MulAmt1))
14765       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14766                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14767     else
14768       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14769                            DAG.getConstant(MulAmt1, VT));
14770
14771     if (isPowerOf2_64(MulAmt2))
14772       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14773                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14774     else
14775       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14776                            DAG.getConstant(MulAmt2, VT));
14777
14778     // Do not add new nodes to DAG combiner worklist.
14779     DCI.CombineTo(N, NewMul, false);
14780   }
14781   return SDValue();
14782 }
14783
14784 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14785   SDValue N0 = N->getOperand(0);
14786   SDValue N1 = N->getOperand(1);
14787   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14788   EVT VT = N0.getValueType();
14789
14790   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14791   // since the result of setcc_c is all zero's or all ones.
14792   if (VT.isInteger() && !VT.isVector() &&
14793       N1C && N0.getOpcode() == ISD::AND &&
14794       N0.getOperand(1).getOpcode() == ISD::Constant) {
14795     SDValue N00 = N0.getOperand(0);
14796     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14797         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14798           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14799          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14800       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14801       APInt ShAmt = N1C->getAPIntValue();
14802       Mask = Mask.shl(ShAmt);
14803       if (Mask != 0)
14804         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14805                            N00, DAG.getConstant(Mask, VT));
14806     }
14807   }
14808
14809
14810   // Hardware support for vector shifts is sparse which makes us scalarize the
14811   // vector operations in many cases. Also, on sandybridge ADD is faster than
14812   // shl.
14813   // (shl V, 1) -> add V,V
14814   if (isSplatVector(N1.getNode())) {
14815     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14816     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14817     // We shift all of the values by one. In many cases we do not have
14818     // hardware support for this operation. This is better expressed as an ADD
14819     // of two values.
14820     if (N1C && (1 == N1C->getZExtValue())) {
14821       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14822     }
14823   }
14824
14825   return SDValue();
14826 }
14827
14828 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14829 ///                       when possible.
14830 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14831                                    TargetLowering::DAGCombinerInfo &DCI,
14832                                    const X86Subtarget *Subtarget) {
14833   EVT VT = N->getValueType(0);
14834   if (N->getOpcode() == ISD::SHL) {
14835     SDValue V = PerformSHLCombine(N, DAG);
14836     if (V.getNode()) return V;
14837   }
14838
14839   // On X86 with SSE2 support, we can transform this to a vector shift if
14840   // all elements are shifted by the same amount.  We can't do this in legalize
14841   // because the a constant vector is typically transformed to a constant pool
14842   // so we have no knowledge of the shift amount.
14843   if (!Subtarget->hasSSE2())
14844     return SDValue();
14845
14846   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14847       (!Subtarget->hasAVX2() ||
14848        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14849     return SDValue();
14850
14851   SDValue ShAmtOp = N->getOperand(1);
14852   EVT EltVT = VT.getVectorElementType();
14853   DebugLoc DL = N->getDebugLoc();
14854   SDValue BaseShAmt = SDValue();
14855   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14856     unsigned NumElts = VT.getVectorNumElements();
14857     unsigned i = 0;
14858     for (; i != NumElts; ++i) {
14859       SDValue Arg = ShAmtOp.getOperand(i);
14860       if (Arg.getOpcode() == ISD::UNDEF) continue;
14861       BaseShAmt = Arg;
14862       break;
14863     }
14864     // Handle the case where the build_vector is all undef
14865     // FIXME: Should DAG allow this?
14866     if (i == NumElts)
14867       return SDValue();
14868
14869     for (; i != NumElts; ++i) {
14870       SDValue Arg = ShAmtOp.getOperand(i);
14871       if (Arg.getOpcode() == ISD::UNDEF) continue;
14872       if (Arg != BaseShAmt) {
14873         return SDValue();
14874       }
14875     }
14876   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14877              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14878     SDValue InVec = ShAmtOp.getOperand(0);
14879     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14880       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14881       unsigned i = 0;
14882       for (; i != NumElts; ++i) {
14883         SDValue Arg = InVec.getOperand(i);
14884         if (Arg.getOpcode() == ISD::UNDEF) continue;
14885         BaseShAmt = Arg;
14886         break;
14887       }
14888     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14889        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14890          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14891          if (C->getZExtValue() == SplatIdx)
14892            BaseShAmt = InVec.getOperand(1);
14893        }
14894     }
14895     if (BaseShAmt.getNode() == 0) {
14896       // Don't create instructions with illegal types after legalize
14897       // types has run.
14898       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14899           !DCI.isBeforeLegalize())
14900         return SDValue();
14901
14902       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14903                               DAG.getIntPtrConstant(0));
14904     }
14905   } else
14906     return SDValue();
14907
14908   // The shift amount is an i32.
14909   if (EltVT.bitsGT(MVT::i32))
14910     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14911   else if (EltVT.bitsLT(MVT::i32))
14912     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14913
14914   // The shift amount is identical so we can do a vector shift.
14915   SDValue  ValOp = N->getOperand(0);
14916   switch (N->getOpcode()) {
14917   default:
14918     llvm_unreachable("Unknown shift opcode!");
14919   case ISD::SHL:
14920     switch (VT.getSimpleVT().SimpleTy) {
14921     default: return SDValue();
14922     case MVT::v2i64:
14923     case MVT::v4i32:
14924     case MVT::v8i16:
14925     case MVT::v4i64:
14926     case MVT::v8i32:
14927     case MVT::v16i16:
14928       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14929     }
14930   case ISD::SRA:
14931     switch (VT.getSimpleVT().SimpleTy) {
14932     default: return SDValue();
14933     case MVT::v4i32:
14934     case MVT::v8i16:
14935     case MVT::v8i32:
14936     case MVT::v16i16:
14937       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14938     }
14939   case ISD::SRL:
14940     switch (VT.getSimpleVT().SimpleTy) {
14941     default: return SDValue();
14942     case MVT::v2i64:
14943     case MVT::v4i32:
14944     case MVT::v8i16:
14945     case MVT::v4i64:
14946     case MVT::v8i32:
14947     case MVT::v16i16:
14948       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14949     }
14950   }
14951 }
14952
14953
14954 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14955 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14956 // and friends.  Likewise for OR -> CMPNEQSS.
14957 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14958                             TargetLowering::DAGCombinerInfo &DCI,
14959                             const X86Subtarget *Subtarget) {
14960   unsigned opcode;
14961
14962   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14963   // we're requiring SSE2 for both.
14964   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14965     SDValue N0 = N->getOperand(0);
14966     SDValue N1 = N->getOperand(1);
14967     SDValue CMP0 = N0->getOperand(1);
14968     SDValue CMP1 = N1->getOperand(1);
14969     DebugLoc DL = N->getDebugLoc();
14970
14971     // The SETCCs should both refer to the same CMP.
14972     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14973       return SDValue();
14974
14975     SDValue CMP00 = CMP0->getOperand(0);
14976     SDValue CMP01 = CMP0->getOperand(1);
14977     EVT     VT    = CMP00.getValueType();
14978
14979     if (VT == MVT::f32 || VT == MVT::f64) {
14980       bool ExpectingFlags = false;
14981       // Check for any users that want flags:
14982       for (SDNode::use_iterator UI = N->use_begin(),
14983              UE = N->use_end();
14984            !ExpectingFlags && UI != UE; ++UI)
14985         switch (UI->getOpcode()) {
14986         default:
14987         case ISD::BR_CC:
14988         case ISD::BRCOND:
14989         case ISD::SELECT:
14990           ExpectingFlags = true;
14991           break;
14992         case ISD::CopyToReg:
14993         case ISD::SIGN_EXTEND:
14994         case ISD::ZERO_EXTEND:
14995         case ISD::ANY_EXTEND:
14996           break;
14997         }
14998
14999       if (!ExpectingFlags) {
15000         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15001         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15002
15003         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15004           X86::CondCode tmp = cc0;
15005           cc0 = cc1;
15006           cc1 = tmp;
15007         }
15008
15009         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15010             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15011           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15012           X86ISD::NodeType NTOperator = is64BitFP ?
15013             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15014           // FIXME: need symbolic constants for these magic numbers.
15015           // See X86ATTInstPrinter.cpp:printSSECC().
15016           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15017           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15018                                               DAG.getConstant(x86cc, MVT::i8));
15019           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15020                                               OnesOrZeroesF);
15021           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15022                                       DAG.getConstant(1, MVT::i32));
15023           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15024           return OneBitOfTruth;
15025         }
15026       }
15027     }
15028   }
15029   return SDValue();
15030 }
15031
15032 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15033 /// so it can be folded inside ANDNP.
15034 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15035   EVT VT = N->getValueType(0);
15036
15037   // Match direct AllOnes for 128 and 256-bit vectors
15038   if (ISD::isBuildVectorAllOnes(N))
15039     return true;
15040
15041   // Look through a bit convert.
15042   if (N->getOpcode() == ISD::BITCAST)
15043     N = N->getOperand(0).getNode();
15044
15045   // Sometimes the operand may come from a insert_subvector building a 256-bit
15046   // allones vector
15047   if (VT.is256BitVector() &&
15048       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15049     SDValue V1 = N->getOperand(0);
15050     SDValue V2 = N->getOperand(1);
15051
15052     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15053         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15054         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15055         ISD::isBuildVectorAllOnes(V2.getNode()))
15056       return true;
15057   }
15058
15059   return false;
15060 }
15061
15062 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15063                                  TargetLowering::DAGCombinerInfo &DCI,
15064                                  const X86Subtarget *Subtarget) {
15065   if (DCI.isBeforeLegalizeOps())
15066     return SDValue();
15067
15068   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15069   if (R.getNode())
15070     return R;
15071
15072   EVT VT = N->getValueType(0);
15073
15074   // Create ANDN, BLSI, and BLSR instructions
15075   // BLSI is X & (-X)
15076   // BLSR is X & (X-1)
15077   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15078     SDValue N0 = N->getOperand(0);
15079     SDValue N1 = N->getOperand(1);
15080     DebugLoc DL = N->getDebugLoc();
15081
15082     // Check LHS for not
15083     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15084       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15085     // Check RHS for not
15086     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15087       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15088
15089     // Check LHS for neg
15090     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15091         isZero(N0.getOperand(0)))
15092       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15093
15094     // Check RHS for neg
15095     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15096         isZero(N1.getOperand(0)))
15097       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15098
15099     // Check LHS for X-1
15100     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15101         isAllOnes(N0.getOperand(1)))
15102       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15103
15104     // Check RHS for X-1
15105     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15106         isAllOnes(N1.getOperand(1)))
15107       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15108
15109     return SDValue();
15110   }
15111
15112   // Want to form ANDNP nodes:
15113   // 1) In the hopes of then easily combining them with OR and AND nodes
15114   //    to form PBLEND/PSIGN.
15115   // 2) To match ANDN packed intrinsics
15116   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15117     return SDValue();
15118
15119   SDValue N0 = N->getOperand(0);
15120   SDValue N1 = N->getOperand(1);
15121   DebugLoc DL = N->getDebugLoc();
15122
15123   // Check LHS for vnot
15124   if (N0.getOpcode() == ISD::XOR &&
15125       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15126       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15127     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15128
15129   // Check RHS for vnot
15130   if (N1.getOpcode() == ISD::XOR &&
15131       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15132       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15133     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15134
15135   return SDValue();
15136 }
15137
15138 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15139                                 TargetLowering::DAGCombinerInfo &DCI,
15140                                 const X86Subtarget *Subtarget) {
15141   if (DCI.isBeforeLegalizeOps())
15142     return SDValue();
15143
15144   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15145   if (R.getNode())
15146     return R;
15147
15148   EVT VT = N->getValueType(0);
15149
15150   SDValue N0 = N->getOperand(0);
15151   SDValue N1 = N->getOperand(1);
15152
15153   // look for psign/blend
15154   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15155     if (!Subtarget->hasSSSE3() ||
15156         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15157       return SDValue();
15158
15159     // Canonicalize pandn to RHS
15160     if (N0.getOpcode() == X86ISD::ANDNP)
15161       std::swap(N0, N1);
15162     // or (and (m, y), (pandn m, x))
15163     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15164       SDValue Mask = N1.getOperand(0);
15165       SDValue X    = N1.getOperand(1);
15166       SDValue Y;
15167       if (N0.getOperand(0) == Mask)
15168         Y = N0.getOperand(1);
15169       if (N0.getOperand(1) == Mask)
15170         Y = N0.getOperand(0);
15171
15172       // Check to see if the mask appeared in both the AND and ANDNP and
15173       if (!Y.getNode())
15174         return SDValue();
15175
15176       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15177       // Look through mask bitcast.
15178       if (Mask.getOpcode() == ISD::BITCAST)
15179         Mask = Mask.getOperand(0);
15180       if (X.getOpcode() == ISD::BITCAST)
15181         X = X.getOperand(0);
15182       if (Y.getOpcode() == ISD::BITCAST)
15183         Y = Y.getOperand(0);
15184
15185       EVT MaskVT = Mask.getValueType();
15186
15187       // Validate that the Mask operand is a vector sra node.
15188       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15189       // there is no psrai.b
15190       if (Mask.getOpcode() != X86ISD::VSRAI)
15191         return SDValue();
15192
15193       // Check that the SRA is all signbits.
15194       SDValue SraC = Mask.getOperand(1);
15195       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15196       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15197       if ((SraAmt + 1) != EltBits)
15198         return SDValue();
15199
15200       DebugLoc DL = N->getDebugLoc();
15201
15202       // Now we know we at least have a plendvb with the mask val.  See if
15203       // we can form a psignb/w/d.
15204       // psign = x.type == y.type == mask.type && y = sub(0, x);
15205       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15206           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15207           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15208         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15209                "Unsupported VT for PSIGN");
15210         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15211         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15212       }
15213       // PBLENDVB only available on SSE 4.1
15214       if (!Subtarget->hasSSE41())
15215         return SDValue();
15216
15217       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15218
15219       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15220       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15221       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15222       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15223       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15224     }
15225   }
15226
15227   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15228     return SDValue();
15229
15230   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15231   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15232     std::swap(N0, N1);
15233   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15234     return SDValue();
15235   if (!N0.hasOneUse() || !N1.hasOneUse())
15236     return SDValue();
15237
15238   SDValue ShAmt0 = N0.getOperand(1);
15239   if (ShAmt0.getValueType() != MVT::i8)
15240     return SDValue();
15241   SDValue ShAmt1 = N1.getOperand(1);
15242   if (ShAmt1.getValueType() != MVT::i8)
15243     return SDValue();
15244   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15245     ShAmt0 = ShAmt0.getOperand(0);
15246   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15247     ShAmt1 = ShAmt1.getOperand(0);
15248
15249   DebugLoc DL = N->getDebugLoc();
15250   unsigned Opc = X86ISD::SHLD;
15251   SDValue Op0 = N0.getOperand(0);
15252   SDValue Op1 = N1.getOperand(0);
15253   if (ShAmt0.getOpcode() == ISD::SUB) {
15254     Opc = X86ISD::SHRD;
15255     std::swap(Op0, Op1);
15256     std::swap(ShAmt0, ShAmt1);
15257   }
15258
15259   unsigned Bits = VT.getSizeInBits();
15260   if (ShAmt1.getOpcode() == ISD::SUB) {
15261     SDValue Sum = ShAmt1.getOperand(0);
15262     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15263       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15264       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15265         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15266       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15267         return DAG.getNode(Opc, DL, VT,
15268                            Op0, Op1,
15269                            DAG.getNode(ISD::TRUNCATE, DL,
15270                                        MVT::i8, ShAmt0));
15271     }
15272   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15273     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15274     if (ShAmt0C &&
15275         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15276       return DAG.getNode(Opc, DL, VT,
15277                          N0.getOperand(0), N1.getOperand(0),
15278                          DAG.getNode(ISD::TRUNCATE, DL,
15279                                        MVT::i8, ShAmt0));
15280   }
15281
15282   return SDValue();
15283 }
15284
15285 // Generate NEG and CMOV for integer abs.
15286 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15287   EVT VT = N->getValueType(0);
15288
15289   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15290   // 8-bit integer abs to NEG and CMOV.
15291   if (VT.isInteger() && VT.getSizeInBits() == 8)
15292     return SDValue();
15293
15294   SDValue N0 = N->getOperand(0);
15295   SDValue N1 = N->getOperand(1);
15296   DebugLoc DL = N->getDebugLoc();
15297
15298   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15299   // and change it to SUB and CMOV.
15300   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15301       N0.getOpcode() == ISD::ADD &&
15302       N0.getOperand(1) == N1 &&
15303       N1.getOpcode() == ISD::SRA &&
15304       N1.getOperand(0) == N0.getOperand(0))
15305     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15306       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15307         // Generate SUB & CMOV.
15308         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15309                                   DAG.getConstant(0, VT), N0.getOperand(0));
15310
15311         SDValue Ops[] = { N0.getOperand(0), Neg,
15312                           DAG.getConstant(X86::COND_GE, MVT::i8),
15313                           SDValue(Neg.getNode(), 1) };
15314         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15315                            Ops, array_lengthof(Ops));
15316       }
15317   return SDValue();
15318 }
15319
15320 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15321 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15322                                  TargetLowering::DAGCombinerInfo &DCI,
15323                                  const X86Subtarget *Subtarget) {
15324   if (DCI.isBeforeLegalizeOps())
15325     return SDValue();
15326
15327   if (Subtarget->hasCMov()) {
15328     SDValue RV = performIntegerAbsCombine(N, DAG);
15329     if (RV.getNode())
15330       return RV;
15331   }
15332
15333   // Try forming BMI if it is available.
15334   if (!Subtarget->hasBMI())
15335     return SDValue();
15336
15337   EVT VT = N->getValueType(0);
15338
15339   if (VT != MVT::i32 && VT != MVT::i64)
15340     return SDValue();
15341
15342   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15343
15344   // Create BLSMSK instructions by finding X ^ (X-1)
15345   SDValue N0 = N->getOperand(0);
15346   SDValue N1 = N->getOperand(1);
15347   DebugLoc DL = N->getDebugLoc();
15348
15349   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15350       isAllOnes(N0.getOperand(1)))
15351     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15352
15353   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15354       isAllOnes(N1.getOperand(1)))
15355     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15356
15357   return SDValue();
15358 }
15359
15360 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15361 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15362                                   TargetLowering::DAGCombinerInfo &DCI,
15363                                   const X86Subtarget *Subtarget) {
15364   LoadSDNode *Ld = cast<LoadSDNode>(N);
15365   EVT RegVT = Ld->getValueType(0);
15366   EVT MemVT = Ld->getMemoryVT();
15367   DebugLoc dl = Ld->getDebugLoc();
15368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15369
15370   ISD::LoadExtType Ext = Ld->getExtensionType();
15371
15372   // If this is a vector EXT Load then attempt to optimize it using a
15373   // shuffle. We need SSE4 for the shuffles.
15374   // TODO: It is possible to support ZExt by zeroing the undef values
15375   // during the shuffle phase or after the shuffle.
15376   if (RegVT.isVector() && RegVT.isInteger() &&
15377       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15378     assert(MemVT != RegVT && "Cannot extend to the same type");
15379     assert(MemVT.isVector() && "Must load a vector from memory");
15380
15381     unsigned NumElems = RegVT.getVectorNumElements();
15382     unsigned RegSz = RegVT.getSizeInBits();
15383     unsigned MemSz = MemVT.getSizeInBits();
15384     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15385
15386     // All sizes must be a power of two.
15387     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15388       return SDValue();
15389
15390     // Attempt to load the original value using scalar loads.
15391     // Find the largest scalar type that divides the total loaded size.
15392     MVT SclrLoadTy = MVT::i8;
15393     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15394          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15395       MVT Tp = (MVT::SimpleValueType)tp;
15396       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15397         SclrLoadTy = Tp;
15398       }
15399     }
15400
15401     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15402     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15403         (64 <= MemSz))
15404       SclrLoadTy = MVT::f64;
15405
15406     // Calculate the number of scalar loads that we need to perform
15407     // in order to load our vector from memory.
15408     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15409
15410     // Represent our vector as a sequence of elements which are the
15411     // largest scalar that we can load.
15412     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15413       RegSz/SclrLoadTy.getSizeInBits());
15414
15415     // Represent the data using the same element type that is stored in
15416     // memory. In practice, we ''widen'' MemVT.
15417     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15418                                   RegSz/MemVT.getScalarType().getSizeInBits());
15419
15420     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15421       "Invalid vector type");
15422
15423     // We can't shuffle using an illegal type.
15424     if (!TLI.isTypeLegal(WideVecVT))
15425       return SDValue();
15426
15427     SmallVector<SDValue, 8> Chains;
15428     SDValue Ptr = Ld->getBasePtr();
15429     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15430                                         TLI.getPointerTy());
15431     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15432
15433     for (unsigned i = 0; i < NumLoads; ++i) {
15434       // Perform a single load.
15435       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15436                                        Ptr, Ld->getPointerInfo(),
15437                                        Ld->isVolatile(), Ld->isNonTemporal(),
15438                                        Ld->isInvariant(), Ld->getAlignment());
15439       Chains.push_back(ScalarLoad.getValue(1));
15440       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15441       // another round of DAGCombining.
15442       if (i == 0)
15443         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15444       else
15445         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15446                           ScalarLoad, DAG.getIntPtrConstant(i));
15447
15448       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15449     }
15450
15451     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15452                                Chains.size());
15453
15454     // Bitcast the loaded value to a vector of the original element type, in
15455     // the size of the target vector type.
15456     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15457     unsigned SizeRatio = RegSz/MemSz;
15458
15459     // Redistribute the loaded elements into the different locations.
15460     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15461     for (unsigned i = 0; i != NumElems; ++i)
15462       ShuffleVec[i*SizeRatio] = i;
15463
15464     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15465                                          DAG.getUNDEF(WideVecVT),
15466                                          &ShuffleVec[0]);
15467
15468     // Bitcast to the requested type.
15469     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15470     // Replace the original load with the new sequence
15471     // and return the new chain.
15472     return DCI.CombineTo(N, Shuff, TF, true);
15473   }
15474
15475   return SDValue();
15476 }
15477
15478 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15479 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15480                                    const X86Subtarget *Subtarget) {
15481   StoreSDNode *St = cast<StoreSDNode>(N);
15482   EVT VT = St->getValue().getValueType();
15483   EVT StVT = St->getMemoryVT();
15484   DebugLoc dl = St->getDebugLoc();
15485   SDValue StoredVal = St->getOperand(1);
15486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15487
15488   // If we are saving a concatenation of two XMM registers, perform two stores.
15489   // On Sandy Bridge, 256-bit memory operations are executed by two
15490   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15491   // memory  operation.
15492   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15493       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15494       StoredVal.getNumOperands() == 2) {
15495     SDValue Value0 = StoredVal.getOperand(0);
15496     SDValue Value1 = StoredVal.getOperand(1);
15497
15498     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15499     SDValue Ptr0 = St->getBasePtr();
15500     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15501
15502     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15503                                 St->getPointerInfo(), St->isVolatile(),
15504                                 St->isNonTemporal(), St->getAlignment());
15505     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15506                                 St->getPointerInfo(), St->isVolatile(),
15507                                 St->isNonTemporal(), St->getAlignment());
15508     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15509   }
15510
15511   // Optimize trunc store (of multiple scalars) to shuffle and store.
15512   // First, pack all of the elements in one place. Next, store to memory
15513   // in fewer chunks.
15514   if (St->isTruncatingStore() && VT.isVector()) {
15515     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15516     unsigned NumElems = VT.getVectorNumElements();
15517     assert(StVT != VT && "Cannot truncate to the same type");
15518     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15519     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15520
15521     // From, To sizes and ElemCount must be pow of two
15522     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15523     // We are going to use the original vector elt for storing.
15524     // Accumulated smaller vector elements must be a multiple of the store size.
15525     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15526
15527     unsigned SizeRatio  = FromSz / ToSz;
15528
15529     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15530
15531     // Create a type on which we perform the shuffle
15532     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15533             StVT.getScalarType(), NumElems*SizeRatio);
15534
15535     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15536
15537     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15538     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15539     for (unsigned i = 0; i != NumElems; ++i)
15540       ShuffleVec[i] = i * SizeRatio;
15541
15542     // Can't shuffle using an illegal type.
15543     if (!TLI.isTypeLegal(WideVecVT))
15544       return SDValue();
15545
15546     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15547                                          DAG.getUNDEF(WideVecVT),
15548                                          &ShuffleVec[0]);
15549     // At this point all of the data is stored at the bottom of the
15550     // register. We now need to save it to mem.
15551
15552     // Find the largest store unit
15553     MVT StoreType = MVT::i8;
15554     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15555          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15556       MVT Tp = (MVT::SimpleValueType)tp;
15557       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15558         StoreType = Tp;
15559     }
15560
15561     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15562     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15563         (64 <= NumElems * ToSz))
15564       StoreType = MVT::f64;
15565
15566     // Bitcast the original vector into a vector of store-size units
15567     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15568             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15569     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15570     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15571     SmallVector<SDValue, 8> Chains;
15572     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15573                                         TLI.getPointerTy());
15574     SDValue Ptr = St->getBasePtr();
15575
15576     // Perform one or more big stores into memory.
15577     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15578       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15579                                    StoreType, ShuffWide,
15580                                    DAG.getIntPtrConstant(i));
15581       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15582                                 St->getPointerInfo(), St->isVolatile(),
15583                                 St->isNonTemporal(), St->getAlignment());
15584       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15585       Chains.push_back(Ch);
15586     }
15587
15588     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15589                                Chains.size());
15590   }
15591
15592
15593   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15594   // the FP state in cases where an emms may be missing.
15595   // A preferable solution to the general problem is to figure out the right
15596   // places to insert EMMS.  This qualifies as a quick hack.
15597
15598   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15599   if (VT.getSizeInBits() != 64)
15600     return SDValue();
15601
15602   const Function *F = DAG.getMachineFunction().getFunction();
15603   bool NoImplicitFloatOps = F->getFnAttributes().
15604     hasAttribute(Attributes::NoImplicitFloat);
15605   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15606                      && Subtarget->hasSSE2();
15607   if ((VT.isVector() ||
15608        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15609       isa<LoadSDNode>(St->getValue()) &&
15610       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15611       St->getChain().hasOneUse() && !St->isVolatile()) {
15612     SDNode* LdVal = St->getValue().getNode();
15613     LoadSDNode *Ld = 0;
15614     int TokenFactorIndex = -1;
15615     SmallVector<SDValue, 8> Ops;
15616     SDNode* ChainVal = St->getChain().getNode();
15617     // Must be a store of a load.  We currently handle two cases:  the load
15618     // is a direct child, and it's under an intervening TokenFactor.  It is
15619     // possible to dig deeper under nested TokenFactors.
15620     if (ChainVal == LdVal)
15621       Ld = cast<LoadSDNode>(St->getChain());
15622     else if (St->getValue().hasOneUse() &&
15623              ChainVal->getOpcode() == ISD::TokenFactor) {
15624       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15625         if (ChainVal->getOperand(i).getNode() == LdVal) {
15626           TokenFactorIndex = i;
15627           Ld = cast<LoadSDNode>(St->getValue());
15628         } else
15629           Ops.push_back(ChainVal->getOperand(i));
15630       }
15631     }
15632
15633     if (!Ld || !ISD::isNormalLoad(Ld))
15634       return SDValue();
15635
15636     // If this is not the MMX case, i.e. we are just turning i64 load/store
15637     // into f64 load/store, avoid the transformation if there are multiple
15638     // uses of the loaded value.
15639     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15640       return SDValue();
15641
15642     DebugLoc LdDL = Ld->getDebugLoc();
15643     DebugLoc StDL = N->getDebugLoc();
15644     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15645     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15646     // pair instead.
15647     if (Subtarget->is64Bit() || F64IsLegal) {
15648       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15649       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15650                                   Ld->getPointerInfo(), Ld->isVolatile(),
15651                                   Ld->isNonTemporal(), Ld->isInvariant(),
15652                                   Ld->getAlignment());
15653       SDValue NewChain = NewLd.getValue(1);
15654       if (TokenFactorIndex != -1) {
15655         Ops.push_back(NewChain);
15656         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15657                                Ops.size());
15658       }
15659       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15660                           St->getPointerInfo(),
15661                           St->isVolatile(), St->isNonTemporal(),
15662                           St->getAlignment());
15663     }
15664
15665     // Otherwise, lower to two pairs of 32-bit loads / stores.
15666     SDValue LoAddr = Ld->getBasePtr();
15667     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15668                                  DAG.getConstant(4, MVT::i32));
15669
15670     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15671                                Ld->getPointerInfo(),
15672                                Ld->isVolatile(), Ld->isNonTemporal(),
15673                                Ld->isInvariant(), Ld->getAlignment());
15674     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15675                                Ld->getPointerInfo().getWithOffset(4),
15676                                Ld->isVolatile(), Ld->isNonTemporal(),
15677                                Ld->isInvariant(),
15678                                MinAlign(Ld->getAlignment(), 4));
15679
15680     SDValue NewChain = LoLd.getValue(1);
15681     if (TokenFactorIndex != -1) {
15682       Ops.push_back(LoLd);
15683       Ops.push_back(HiLd);
15684       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15685                              Ops.size());
15686     }
15687
15688     LoAddr = St->getBasePtr();
15689     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15690                          DAG.getConstant(4, MVT::i32));
15691
15692     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15693                                 St->getPointerInfo(),
15694                                 St->isVolatile(), St->isNonTemporal(),
15695                                 St->getAlignment());
15696     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15697                                 St->getPointerInfo().getWithOffset(4),
15698                                 St->isVolatile(),
15699                                 St->isNonTemporal(),
15700                                 MinAlign(St->getAlignment(), 4));
15701     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15702   }
15703   return SDValue();
15704 }
15705
15706 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15707 /// and return the operands for the horizontal operation in LHS and RHS.  A
15708 /// horizontal operation performs the binary operation on successive elements
15709 /// of its first operand, then on successive elements of its second operand,
15710 /// returning the resulting values in a vector.  For example, if
15711 ///   A = < float a0, float a1, float a2, float a3 >
15712 /// and
15713 ///   B = < float b0, float b1, float b2, float b3 >
15714 /// then the result of doing a horizontal operation on A and B is
15715 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15716 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15717 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15718 /// set to A, RHS to B, and the routine returns 'true'.
15719 /// Note that the binary operation should have the property that if one of the
15720 /// operands is UNDEF then the result is UNDEF.
15721 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15722   // Look for the following pattern: if
15723   //   A = < float a0, float a1, float a2, float a3 >
15724   //   B = < float b0, float b1, float b2, float b3 >
15725   // and
15726   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15727   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15728   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15729   // which is A horizontal-op B.
15730
15731   // At least one of the operands should be a vector shuffle.
15732   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15733       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15734     return false;
15735
15736   EVT VT = LHS.getValueType();
15737
15738   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15739          "Unsupported vector type for horizontal add/sub");
15740
15741   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15742   // operate independently on 128-bit lanes.
15743   unsigned NumElts = VT.getVectorNumElements();
15744   unsigned NumLanes = VT.getSizeInBits()/128;
15745   unsigned NumLaneElts = NumElts / NumLanes;
15746   assert((NumLaneElts % 2 == 0) &&
15747          "Vector type should have an even number of elements in each lane");
15748   unsigned HalfLaneElts = NumLaneElts/2;
15749
15750   // View LHS in the form
15751   //   LHS = VECTOR_SHUFFLE A, B, LMask
15752   // If LHS is not a shuffle then pretend it is the shuffle
15753   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15754   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15755   // type VT.
15756   SDValue A, B;
15757   SmallVector<int, 16> LMask(NumElts);
15758   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15759     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15760       A = LHS.getOperand(0);
15761     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15762       B = LHS.getOperand(1);
15763     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15764     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15765   } else {
15766     if (LHS.getOpcode() != ISD::UNDEF)
15767       A = LHS;
15768     for (unsigned i = 0; i != NumElts; ++i)
15769       LMask[i] = i;
15770   }
15771
15772   // Likewise, view RHS in the form
15773   //   RHS = VECTOR_SHUFFLE C, D, RMask
15774   SDValue C, D;
15775   SmallVector<int, 16> RMask(NumElts);
15776   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15777     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15778       C = RHS.getOperand(0);
15779     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15780       D = RHS.getOperand(1);
15781     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15782     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15783   } else {
15784     if (RHS.getOpcode() != ISD::UNDEF)
15785       C = RHS;
15786     for (unsigned i = 0; i != NumElts; ++i)
15787       RMask[i] = i;
15788   }
15789
15790   // Check that the shuffles are both shuffling the same vectors.
15791   if (!(A == C && B == D) && !(A == D && B == C))
15792     return false;
15793
15794   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15795   if (!A.getNode() && !B.getNode())
15796     return false;
15797
15798   // If A and B occur in reverse order in RHS, then "swap" them (which means
15799   // rewriting the mask).
15800   if (A != C)
15801     CommuteVectorShuffleMask(RMask, NumElts);
15802
15803   // At this point LHS and RHS are equivalent to
15804   //   LHS = VECTOR_SHUFFLE A, B, LMask
15805   //   RHS = VECTOR_SHUFFLE A, B, RMask
15806   // Check that the masks correspond to performing a horizontal operation.
15807   for (unsigned i = 0; i != NumElts; ++i) {
15808     int LIdx = LMask[i], RIdx = RMask[i];
15809
15810     // Ignore any UNDEF components.
15811     if (LIdx < 0 || RIdx < 0 ||
15812         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15813         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15814       continue;
15815
15816     // Check that successive elements are being operated on.  If not, this is
15817     // not a horizontal operation.
15818     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15819     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15820     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15821     if (!(LIdx == Index && RIdx == Index + 1) &&
15822         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15823       return false;
15824   }
15825
15826   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15827   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15828   return true;
15829 }
15830
15831 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15832 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15833                                   const X86Subtarget *Subtarget) {
15834   EVT VT = N->getValueType(0);
15835   SDValue LHS = N->getOperand(0);
15836   SDValue RHS = N->getOperand(1);
15837
15838   // Try to synthesize horizontal adds from adds of shuffles.
15839   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15840        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15841       isHorizontalBinOp(LHS, RHS, true))
15842     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15843   return SDValue();
15844 }
15845
15846 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15847 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15848                                   const X86Subtarget *Subtarget) {
15849   EVT VT = N->getValueType(0);
15850   SDValue LHS = N->getOperand(0);
15851   SDValue RHS = N->getOperand(1);
15852
15853   // Try to synthesize horizontal subs from subs of shuffles.
15854   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15855        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15856       isHorizontalBinOp(LHS, RHS, false))
15857     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15858   return SDValue();
15859 }
15860
15861 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15862 /// X86ISD::FXOR nodes.
15863 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15864   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15865   // F[X]OR(0.0, x) -> x
15866   // F[X]OR(x, 0.0) -> x
15867   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15868     if (C->getValueAPF().isPosZero())
15869       return N->getOperand(1);
15870   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15871     if (C->getValueAPF().isPosZero())
15872       return N->getOperand(0);
15873   return SDValue();
15874 }
15875
15876 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15877 /// X86ISD::FMAX nodes.
15878 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15879   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15880
15881   // Only perform optimizations if UnsafeMath is used.
15882   if (!DAG.getTarget().Options.UnsafeFPMath)
15883     return SDValue();
15884
15885   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15886   // into FMINC and FMAXC, which are Commutative operations.
15887   unsigned NewOp = 0;
15888   switch (N->getOpcode()) {
15889     default: llvm_unreachable("unknown opcode");
15890     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15891     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15892   }
15893
15894   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15895                      N->getOperand(0), N->getOperand(1));
15896 }
15897
15898
15899 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15900 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15901   // FAND(0.0, x) -> 0.0
15902   // FAND(x, 0.0) -> 0.0
15903   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15904     if (C->getValueAPF().isPosZero())
15905       return N->getOperand(0);
15906   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15907     if (C->getValueAPF().isPosZero())
15908       return N->getOperand(1);
15909   return SDValue();
15910 }
15911
15912 static SDValue PerformBTCombine(SDNode *N,
15913                                 SelectionDAG &DAG,
15914                                 TargetLowering::DAGCombinerInfo &DCI) {
15915   // BT ignores high bits in the bit index operand.
15916   SDValue Op1 = N->getOperand(1);
15917   if (Op1.hasOneUse()) {
15918     unsigned BitWidth = Op1.getValueSizeInBits();
15919     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15920     APInt KnownZero, KnownOne;
15921     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15922                                           !DCI.isBeforeLegalizeOps());
15923     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15924     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15925         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15926       DCI.CommitTargetLoweringOpt(TLO);
15927   }
15928   return SDValue();
15929 }
15930
15931 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15932   SDValue Op = N->getOperand(0);
15933   if (Op.getOpcode() == ISD::BITCAST)
15934     Op = Op.getOperand(0);
15935   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15936   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15937       VT.getVectorElementType().getSizeInBits() ==
15938       OpVT.getVectorElementType().getSizeInBits()) {
15939     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15940   }
15941   return SDValue();
15942 }
15943
15944 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15945                                   TargetLowering::DAGCombinerInfo &DCI,
15946                                   const X86Subtarget *Subtarget) {
15947   if (!DCI.isBeforeLegalizeOps())
15948     return SDValue();
15949
15950   if (!Subtarget->hasAVX())
15951     return SDValue();
15952
15953   EVT VT = N->getValueType(0);
15954   SDValue Op = N->getOperand(0);
15955   EVT OpVT = Op.getValueType();
15956   DebugLoc dl = N->getDebugLoc();
15957
15958   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15959       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15960
15961     if (Subtarget->hasAVX2())
15962       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15963
15964     // Optimize vectors in AVX mode
15965     // Sign extend  v8i16 to v8i32 and
15966     //              v4i32 to v4i64
15967     //
15968     // Divide input vector into two parts
15969     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15970     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15971     // concat the vectors to original VT
15972
15973     unsigned NumElems = OpVT.getVectorNumElements();
15974     SDValue Undef = DAG.getUNDEF(OpVT);
15975
15976     SmallVector<int,8> ShufMask1(NumElems, -1);
15977     for (unsigned i = 0; i != NumElems/2; ++i)
15978       ShufMask1[i] = i;
15979
15980     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15981
15982     SmallVector<int,8> ShufMask2(NumElems, -1);
15983     for (unsigned i = 0; i != NumElems/2; ++i)
15984       ShufMask2[i] = i + NumElems/2;
15985
15986     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15987
15988     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15989                                   VT.getVectorNumElements()/2);
15990
15991     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15992     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15993
15994     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15995   }
15996   return SDValue();
15997 }
15998
15999 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16000                                  const X86Subtarget* Subtarget) {
16001   DebugLoc dl = N->getDebugLoc();
16002   EVT VT = N->getValueType(0);
16003
16004   // Let legalize expand this if it isn't a legal type yet.
16005   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16006     return SDValue();
16007
16008   EVT ScalarVT = VT.getScalarType();
16009   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16010       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16011     return SDValue();
16012
16013   SDValue A = N->getOperand(0);
16014   SDValue B = N->getOperand(1);
16015   SDValue C = N->getOperand(2);
16016
16017   bool NegA = (A.getOpcode() == ISD::FNEG);
16018   bool NegB = (B.getOpcode() == ISD::FNEG);
16019   bool NegC = (C.getOpcode() == ISD::FNEG);
16020
16021   // Negative multiplication when NegA xor NegB
16022   bool NegMul = (NegA != NegB);
16023   if (NegA)
16024     A = A.getOperand(0);
16025   if (NegB)
16026     B = B.getOperand(0);
16027   if (NegC)
16028     C = C.getOperand(0);
16029
16030   unsigned Opcode;
16031   if (!NegMul)
16032     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16033   else
16034     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16035
16036   return DAG.getNode(Opcode, dl, VT, A, B, C);
16037 }
16038
16039 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16040                                   TargetLowering::DAGCombinerInfo &DCI,
16041                                   const X86Subtarget *Subtarget) {
16042   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16043   //           (and (i32 x86isd::setcc_carry), 1)
16044   // This eliminates the zext. This transformation is necessary because
16045   // ISD::SETCC is always legalized to i8.
16046   DebugLoc dl = N->getDebugLoc();
16047   SDValue N0 = N->getOperand(0);
16048   EVT VT = N->getValueType(0);
16049   EVT OpVT = N0.getValueType();
16050
16051   if (N0.getOpcode() == ISD::AND &&
16052       N0.hasOneUse() &&
16053       N0.getOperand(0).hasOneUse()) {
16054     SDValue N00 = N0.getOperand(0);
16055     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16056       return SDValue();
16057     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16058     if (!C || C->getZExtValue() != 1)
16059       return SDValue();
16060     return DAG.getNode(ISD::AND, dl, VT,
16061                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16062                                    N00.getOperand(0), N00.getOperand(1)),
16063                        DAG.getConstant(1, VT));
16064   }
16065
16066   // Optimize vectors in AVX mode:
16067   //
16068   //   v8i16 -> v8i32
16069   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16070   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16071   //   Concat upper and lower parts.
16072   //
16073   //   v4i32 -> v4i64
16074   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16075   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16076   //   Concat upper and lower parts.
16077   //
16078   if (!DCI.isBeforeLegalizeOps())
16079     return SDValue();
16080
16081   if (!Subtarget->hasAVX())
16082     return SDValue();
16083
16084   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16085       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16086
16087     if (Subtarget->hasAVX2())
16088       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16089
16090     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16091     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16092     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16093
16094     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16095                                VT.getVectorNumElements()/2);
16096
16097     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16098     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16099
16100     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16101   }
16102
16103   return SDValue();
16104 }
16105
16106 // Optimize x == -y --> x+y == 0
16107 //          x != -y --> x+y != 0
16108 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16109   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16110   SDValue LHS = N->getOperand(0);
16111   SDValue RHS = N->getOperand(1);
16112
16113   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16114     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16115       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16116         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16117                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16118         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16119                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16120       }
16121   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16122     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16123       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16124         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16125                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16126         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16127                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16128       }
16129   return SDValue();
16130 }
16131
16132 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16133 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16134                                    TargetLowering::DAGCombinerInfo &DCI,
16135                                    const X86Subtarget *Subtarget) {
16136   DebugLoc DL = N->getDebugLoc();
16137   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16138   SDValue EFLAGS = N->getOperand(1);
16139
16140   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16141   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16142   // cases.
16143   if (CC == X86::COND_B)
16144     return DAG.getNode(ISD::AND, DL, MVT::i8,
16145                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16146                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16147                        DAG.getConstant(1, MVT::i8));
16148
16149   SDValue Flags;
16150
16151   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16152   if (Flags.getNode()) {
16153     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16154     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16155   }
16156
16157   return SDValue();
16158 }
16159
16160 // Optimize branch condition evaluation.
16161 //
16162 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16163                                     TargetLowering::DAGCombinerInfo &DCI,
16164                                     const X86Subtarget *Subtarget) {
16165   DebugLoc DL = N->getDebugLoc();
16166   SDValue Chain = N->getOperand(0);
16167   SDValue Dest = N->getOperand(1);
16168   SDValue EFLAGS = N->getOperand(3);
16169   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16170
16171   SDValue Flags;
16172
16173   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16174   if (Flags.getNode()) {
16175     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16176     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16177                        Flags);
16178   }
16179
16180   return SDValue();
16181 }
16182
16183 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16184   SDValue Op0 = N->getOperand(0);
16185   EVT InVT = Op0->getValueType(0);
16186
16187   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16188   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16189     DebugLoc dl = N->getDebugLoc();
16190     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16191     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16192     // Notice that we use SINT_TO_FP because we know that the high bits
16193     // are zero and SINT_TO_FP is better supported by the hardware.
16194     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16195   }
16196
16197   return SDValue();
16198 }
16199
16200 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16201                                         const X86TargetLowering *XTLI) {
16202   SDValue Op0 = N->getOperand(0);
16203   EVT InVT = Op0->getValueType(0);
16204
16205   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16206   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16207     DebugLoc dl = N->getDebugLoc();
16208     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16209     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16210     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16211   }
16212
16213   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16214   // a 32-bit target where SSE doesn't support i64->FP operations.
16215   if (Op0.getOpcode() == ISD::LOAD) {
16216     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16217     EVT VT = Ld->getValueType(0);
16218     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16219         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16220         !XTLI->getSubtarget()->is64Bit() &&
16221         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16222       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16223                                           Ld->getChain(), Op0, DAG);
16224       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16225       return FILDChain;
16226     }
16227   }
16228   return SDValue();
16229 }
16230
16231 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
16232   EVT VT = N->getValueType(0);
16233
16234   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
16235   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
16236     DebugLoc dl = N->getDebugLoc();
16237     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16238     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
16239     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
16240   }
16241
16242   return SDValue();
16243 }
16244
16245 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16246 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16247                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16248   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16249   // the result is either zero or one (depending on the input carry bit).
16250   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16251   if (X86::isZeroNode(N->getOperand(0)) &&
16252       X86::isZeroNode(N->getOperand(1)) &&
16253       // We don't have a good way to replace an EFLAGS use, so only do this when
16254       // dead right now.
16255       SDValue(N, 1).use_empty()) {
16256     DebugLoc DL = N->getDebugLoc();
16257     EVT VT = N->getValueType(0);
16258     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16259     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16260                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16261                                            DAG.getConstant(X86::COND_B,MVT::i8),
16262                                            N->getOperand(2)),
16263                                DAG.getConstant(1, VT));
16264     return DCI.CombineTo(N, Res1, CarryOut);
16265   }
16266
16267   return SDValue();
16268 }
16269
16270 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16271 //      (add Y, (setne X, 0)) -> sbb -1, Y
16272 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16273 //      (sub (setne X, 0), Y) -> adc -1, Y
16274 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16275   DebugLoc DL = N->getDebugLoc();
16276
16277   // Look through ZExts.
16278   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16279   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16280     return SDValue();
16281
16282   SDValue SetCC = Ext.getOperand(0);
16283   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16284     return SDValue();
16285
16286   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16287   if (CC != X86::COND_E && CC != X86::COND_NE)
16288     return SDValue();
16289
16290   SDValue Cmp = SetCC.getOperand(1);
16291   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16292       !X86::isZeroNode(Cmp.getOperand(1)) ||
16293       !Cmp.getOperand(0).getValueType().isInteger())
16294     return SDValue();
16295
16296   SDValue CmpOp0 = Cmp.getOperand(0);
16297   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16298                                DAG.getConstant(1, CmpOp0.getValueType()));
16299
16300   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16301   if (CC == X86::COND_NE)
16302     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16303                        DL, OtherVal.getValueType(), OtherVal,
16304                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16305   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16306                      DL, OtherVal.getValueType(), OtherVal,
16307                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16308 }
16309
16310 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16311 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16312                                  const X86Subtarget *Subtarget) {
16313   EVT VT = N->getValueType(0);
16314   SDValue Op0 = N->getOperand(0);
16315   SDValue Op1 = N->getOperand(1);
16316
16317   // Try to synthesize horizontal adds from adds of shuffles.
16318   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16319        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16320       isHorizontalBinOp(Op0, Op1, true))
16321     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16322
16323   return OptimizeConditionalInDecrement(N, DAG);
16324 }
16325
16326 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16327                                  const X86Subtarget *Subtarget) {
16328   SDValue Op0 = N->getOperand(0);
16329   SDValue Op1 = N->getOperand(1);
16330
16331   // X86 can't encode an immediate LHS of a sub. See if we can push the
16332   // negation into a preceding instruction.
16333   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16334     // If the RHS of the sub is a XOR with one use and a constant, invert the
16335     // immediate. Then add one to the LHS of the sub so we can turn
16336     // X-Y -> X+~Y+1, saving one register.
16337     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16338         isa<ConstantSDNode>(Op1.getOperand(1))) {
16339       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16340       EVT VT = Op0.getValueType();
16341       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16342                                    Op1.getOperand(0),
16343                                    DAG.getConstant(~XorC, VT));
16344       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16345                          DAG.getConstant(C->getAPIntValue()+1, VT));
16346     }
16347   }
16348
16349   // Try to synthesize horizontal adds from adds of shuffles.
16350   EVT VT = N->getValueType(0);
16351   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16352        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16353       isHorizontalBinOp(Op0, Op1, true))
16354     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16355
16356   return OptimizeConditionalInDecrement(N, DAG);
16357 }
16358
16359 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16360                                              DAGCombinerInfo &DCI) const {
16361   SelectionDAG &DAG = DCI.DAG;
16362   switch (N->getOpcode()) {
16363   default: break;
16364   case ISD::EXTRACT_VECTOR_ELT:
16365     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16366   case ISD::VSELECT:
16367   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16368   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16369   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16370   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16371   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16372   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16373   case ISD::SHL:
16374   case ISD::SRA:
16375   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16376   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16377   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16378   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16379   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16380   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16381   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16382   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16383   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16384   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16385   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16386   case X86ISD::FXOR:
16387   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16388   case X86ISD::FMIN:
16389   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16390   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16391   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16392   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16393   case ISD::ANY_EXTEND:
16394   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16395   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16396   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16397   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16398   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16399   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16400   case X86ISD::SHUFP:       // Handle all target specific shuffles
16401   case X86ISD::PALIGN:
16402   case X86ISD::UNPCKH:
16403   case X86ISD::UNPCKL:
16404   case X86ISD::MOVHLPS:
16405   case X86ISD::MOVLHPS:
16406   case X86ISD::PSHUFD:
16407   case X86ISD::PSHUFHW:
16408   case X86ISD::PSHUFLW:
16409   case X86ISD::MOVSS:
16410   case X86ISD::MOVSD:
16411   case X86ISD::VPERMILP:
16412   case X86ISD::VPERM2X128:
16413   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16414   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16415   }
16416
16417   return SDValue();
16418 }
16419
16420 /// isTypeDesirableForOp - Return true if the target has native support for
16421 /// the specified value type and it is 'desirable' to use the type for the
16422 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16423 /// instruction encodings are longer and some i16 instructions are slow.
16424 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16425   if (!isTypeLegal(VT))
16426     return false;
16427   if (VT != MVT::i16)
16428     return true;
16429
16430   switch (Opc) {
16431   default:
16432     return true;
16433   case ISD::LOAD:
16434   case ISD::SIGN_EXTEND:
16435   case ISD::ZERO_EXTEND:
16436   case ISD::ANY_EXTEND:
16437   case ISD::SHL:
16438   case ISD::SRL:
16439   case ISD::SUB:
16440   case ISD::ADD:
16441   case ISD::MUL:
16442   case ISD::AND:
16443   case ISD::OR:
16444   case ISD::XOR:
16445     return false;
16446   }
16447 }
16448
16449 /// IsDesirableToPromoteOp - This method query the target whether it is
16450 /// beneficial for dag combiner to promote the specified node. If true, it
16451 /// should return the desired promotion type by reference.
16452 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16453   EVT VT = Op.getValueType();
16454   if (VT != MVT::i16)
16455     return false;
16456
16457   bool Promote = false;
16458   bool Commute = false;
16459   switch (Op.getOpcode()) {
16460   default: break;
16461   case ISD::LOAD: {
16462     LoadSDNode *LD = cast<LoadSDNode>(Op);
16463     // If the non-extending load has a single use and it's not live out, then it
16464     // might be folded.
16465     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16466                                                      Op.hasOneUse()*/) {
16467       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16468              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16469         // The only case where we'd want to promote LOAD (rather then it being
16470         // promoted as an operand is when it's only use is liveout.
16471         if (UI->getOpcode() != ISD::CopyToReg)
16472           return false;
16473       }
16474     }
16475     Promote = true;
16476     break;
16477   }
16478   case ISD::SIGN_EXTEND:
16479   case ISD::ZERO_EXTEND:
16480   case ISD::ANY_EXTEND:
16481     Promote = true;
16482     break;
16483   case ISD::SHL:
16484   case ISD::SRL: {
16485     SDValue N0 = Op.getOperand(0);
16486     // Look out for (store (shl (load), x)).
16487     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16488       return false;
16489     Promote = true;
16490     break;
16491   }
16492   case ISD::ADD:
16493   case ISD::MUL:
16494   case ISD::AND:
16495   case ISD::OR:
16496   case ISD::XOR:
16497     Commute = true;
16498     // fallthrough
16499   case ISD::SUB: {
16500     SDValue N0 = Op.getOperand(0);
16501     SDValue N1 = Op.getOperand(1);
16502     if (!Commute && MayFoldLoad(N1))
16503       return false;
16504     // Avoid disabling potential load folding opportunities.
16505     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16506       return false;
16507     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16508       return false;
16509     Promote = true;
16510   }
16511   }
16512
16513   PVT = MVT::i32;
16514   return Promote;
16515 }
16516
16517 //===----------------------------------------------------------------------===//
16518 //                           X86 Inline Assembly Support
16519 //===----------------------------------------------------------------------===//
16520
16521 namespace {
16522   // Helper to match a string separated by whitespace.
16523   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16524     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16525
16526     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16527       StringRef piece(*args[i]);
16528       if (!s.startswith(piece)) // Check if the piece matches.
16529         return false;
16530
16531       s = s.substr(piece.size());
16532       StringRef::size_type pos = s.find_first_not_of(" \t");
16533       if (pos == 0) // We matched a prefix.
16534         return false;
16535
16536       s = s.substr(pos);
16537     }
16538
16539     return s.empty();
16540   }
16541   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16542 }
16543
16544 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16545   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16546
16547   std::string AsmStr = IA->getAsmString();
16548
16549   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16550   if (!Ty || Ty->getBitWidth() % 16 != 0)
16551     return false;
16552
16553   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16554   SmallVector<StringRef, 4> AsmPieces;
16555   SplitString(AsmStr, AsmPieces, ";\n");
16556
16557   switch (AsmPieces.size()) {
16558   default: return false;
16559   case 1:
16560     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16561     // we will turn this bswap into something that will be lowered to logical
16562     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16563     // lower so don't worry about this.
16564     // bswap $0
16565     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16566         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16567         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16568         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16569         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16570         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16571       // No need to check constraints, nothing other than the equivalent of
16572       // "=r,0" would be valid here.
16573       return IntrinsicLowering::LowerToByteSwap(CI);
16574     }
16575
16576     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16577     if (CI->getType()->isIntegerTy(16) &&
16578         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16579         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16580          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16581       AsmPieces.clear();
16582       const std::string &ConstraintsStr = IA->getConstraintString();
16583       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16584       std::sort(AsmPieces.begin(), AsmPieces.end());
16585       if (AsmPieces.size() == 4 &&
16586           AsmPieces[0] == "~{cc}" &&
16587           AsmPieces[1] == "~{dirflag}" &&
16588           AsmPieces[2] == "~{flags}" &&
16589           AsmPieces[3] == "~{fpsr}")
16590       return IntrinsicLowering::LowerToByteSwap(CI);
16591     }
16592     break;
16593   case 3:
16594     if (CI->getType()->isIntegerTy(32) &&
16595         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16596         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16597         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16598         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16599       AsmPieces.clear();
16600       const std::string &ConstraintsStr = IA->getConstraintString();
16601       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16602       std::sort(AsmPieces.begin(), AsmPieces.end());
16603       if (AsmPieces.size() == 4 &&
16604           AsmPieces[0] == "~{cc}" &&
16605           AsmPieces[1] == "~{dirflag}" &&
16606           AsmPieces[2] == "~{flags}" &&
16607           AsmPieces[3] == "~{fpsr}")
16608         return IntrinsicLowering::LowerToByteSwap(CI);
16609     }
16610
16611     if (CI->getType()->isIntegerTy(64)) {
16612       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16613       if (Constraints.size() >= 2 &&
16614           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16615           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16616         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16617         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16618             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16619             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16620           return IntrinsicLowering::LowerToByteSwap(CI);
16621       }
16622     }
16623     break;
16624   }
16625   return false;
16626 }
16627
16628
16629
16630 /// getConstraintType - Given a constraint letter, return the type of
16631 /// constraint it is for this target.
16632 X86TargetLowering::ConstraintType
16633 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16634   if (Constraint.size() == 1) {
16635     switch (Constraint[0]) {
16636     case 'R':
16637     case 'q':
16638     case 'Q':
16639     case 'f':
16640     case 't':
16641     case 'u':
16642     case 'y':
16643     case 'x':
16644     case 'Y':
16645     case 'l':
16646       return C_RegisterClass;
16647     case 'a':
16648     case 'b':
16649     case 'c':
16650     case 'd':
16651     case 'S':
16652     case 'D':
16653     case 'A':
16654       return C_Register;
16655     case 'I':
16656     case 'J':
16657     case 'K':
16658     case 'L':
16659     case 'M':
16660     case 'N':
16661     case 'G':
16662     case 'C':
16663     case 'e':
16664     case 'Z':
16665       return C_Other;
16666     default:
16667       break;
16668     }
16669   }
16670   return TargetLowering::getConstraintType(Constraint);
16671 }
16672
16673 /// Examine constraint type and operand type and determine a weight value.
16674 /// This object must already have been set up with the operand type
16675 /// and the current alternative constraint selected.
16676 TargetLowering::ConstraintWeight
16677   X86TargetLowering::getSingleConstraintMatchWeight(
16678     AsmOperandInfo &info, const char *constraint) const {
16679   ConstraintWeight weight = CW_Invalid;
16680   Value *CallOperandVal = info.CallOperandVal;
16681     // If we don't have a value, we can't do a match,
16682     // but allow it at the lowest weight.
16683   if (CallOperandVal == NULL)
16684     return CW_Default;
16685   Type *type = CallOperandVal->getType();
16686   // Look at the constraint type.
16687   switch (*constraint) {
16688   default:
16689     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16690   case 'R':
16691   case 'q':
16692   case 'Q':
16693   case 'a':
16694   case 'b':
16695   case 'c':
16696   case 'd':
16697   case 'S':
16698   case 'D':
16699   case 'A':
16700     if (CallOperandVal->getType()->isIntegerTy())
16701       weight = CW_SpecificReg;
16702     break;
16703   case 'f':
16704   case 't':
16705   case 'u':
16706       if (type->isFloatingPointTy())
16707         weight = CW_SpecificReg;
16708       break;
16709   case 'y':
16710       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16711         weight = CW_SpecificReg;
16712       break;
16713   case 'x':
16714   case 'Y':
16715     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16716         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16717       weight = CW_Register;
16718     break;
16719   case 'I':
16720     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16721       if (C->getZExtValue() <= 31)
16722         weight = CW_Constant;
16723     }
16724     break;
16725   case 'J':
16726     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16727       if (C->getZExtValue() <= 63)
16728         weight = CW_Constant;
16729     }
16730     break;
16731   case 'K':
16732     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16733       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16734         weight = CW_Constant;
16735     }
16736     break;
16737   case 'L':
16738     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16739       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16740         weight = CW_Constant;
16741     }
16742     break;
16743   case 'M':
16744     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16745       if (C->getZExtValue() <= 3)
16746         weight = CW_Constant;
16747     }
16748     break;
16749   case 'N':
16750     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16751       if (C->getZExtValue() <= 0xff)
16752         weight = CW_Constant;
16753     }
16754     break;
16755   case 'G':
16756   case 'C':
16757     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16758       weight = CW_Constant;
16759     }
16760     break;
16761   case 'e':
16762     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16763       if ((C->getSExtValue() >= -0x80000000LL) &&
16764           (C->getSExtValue() <= 0x7fffffffLL))
16765         weight = CW_Constant;
16766     }
16767     break;
16768   case 'Z':
16769     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16770       if (C->getZExtValue() <= 0xffffffff)
16771         weight = CW_Constant;
16772     }
16773     break;
16774   }
16775   return weight;
16776 }
16777
16778 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16779 /// with another that has more specific requirements based on the type of the
16780 /// corresponding operand.
16781 const char *X86TargetLowering::
16782 LowerXConstraint(EVT ConstraintVT) const {
16783   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16784   // 'f' like normal targets.
16785   if (ConstraintVT.isFloatingPoint()) {
16786     if (Subtarget->hasSSE2())
16787       return "Y";
16788     if (Subtarget->hasSSE1())
16789       return "x";
16790   }
16791
16792   return TargetLowering::LowerXConstraint(ConstraintVT);
16793 }
16794
16795 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16796 /// vector.  If it is invalid, don't add anything to Ops.
16797 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16798                                                      std::string &Constraint,
16799                                                      std::vector<SDValue>&Ops,
16800                                                      SelectionDAG &DAG) const {
16801   SDValue Result(0, 0);
16802
16803   // Only support length 1 constraints for now.
16804   if (Constraint.length() > 1) return;
16805
16806   char ConstraintLetter = Constraint[0];
16807   switch (ConstraintLetter) {
16808   default: break;
16809   case 'I':
16810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16811       if (C->getZExtValue() <= 31) {
16812         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16813         break;
16814       }
16815     }
16816     return;
16817   case 'J':
16818     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16819       if (C->getZExtValue() <= 63) {
16820         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16821         break;
16822       }
16823     }
16824     return;
16825   case 'K':
16826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16827       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16828         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16829         break;
16830       }
16831     }
16832     return;
16833   case 'N':
16834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16835       if (C->getZExtValue() <= 255) {
16836         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16837         break;
16838       }
16839     }
16840     return;
16841   case 'e': {
16842     // 32-bit signed value
16843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16844       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16845                                            C->getSExtValue())) {
16846         // Widen to 64 bits here to get it sign extended.
16847         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16848         break;
16849       }
16850     // FIXME gcc accepts some relocatable values here too, but only in certain
16851     // memory models; it's complicated.
16852     }
16853     return;
16854   }
16855   case 'Z': {
16856     // 32-bit unsigned value
16857     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16858       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16859                                            C->getZExtValue())) {
16860         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16861         break;
16862       }
16863     }
16864     // FIXME gcc accepts some relocatable values here too, but only in certain
16865     // memory models; it's complicated.
16866     return;
16867   }
16868   case 'i': {
16869     // Literal immediates are always ok.
16870     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16871       // Widen to 64 bits here to get it sign extended.
16872       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16873       break;
16874     }
16875
16876     // In any sort of PIC mode addresses need to be computed at runtime by
16877     // adding in a register or some sort of table lookup.  These can't
16878     // be used as immediates.
16879     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16880       return;
16881
16882     // If we are in non-pic codegen mode, we allow the address of a global (with
16883     // an optional displacement) to be used with 'i'.
16884     GlobalAddressSDNode *GA = 0;
16885     int64_t Offset = 0;
16886
16887     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16888     while (1) {
16889       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16890         Offset += GA->getOffset();
16891         break;
16892       } else if (Op.getOpcode() == ISD::ADD) {
16893         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16894           Offset += C->getZExtValue();
16895           Op = Op.getOperand(0);
16896           continue;
16897         }
16898       } else if (Op.getOpcode() == ISD::SUB) {
16899         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16900           Offset += -C->getZExtValue();
16901           Op = Op.getOperand(0);
16902           continue;
16903         }
16904       }
16905
16906       // Otherwise, this isn't something we can handle, reject it.
16907       return;
16908     }
16909
16910     const GlobalValue *GV = GA->getGlobal();
16911     // If we require an extra load to get this address, as in PIC mode, we
16912     // can't accept it.
16913     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16914                                                         getTargetMachine())))
16915       return;
16916
16917     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16918                                         GA->getValueType(0), Offset);
16919     break;
16920   }
16921   }
16922
16923   if (Result.getNode()) {
16924     Ops.push_back(Result);
16925     return;
16926   }
16927   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16928 }
16929
16930 std::pair<unsigned, const TargetRegisterClass*>
16931 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16932                                                 EVT VT) const {
16933   // First, see if this is a constraint that directly corresponds to an LLVM
16934   // register class.
16935   if (Constraint.size() == 1) {
16936     // GCC Constraint Letters
16937     switch (Constraint[0]) {
16938     default: break;
16939       // TODO: Slight differences here in allocation order and leaving
16940       // RIP in the class. Do they matter any more here than they do
16941       // in the normal allocation?
16942     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16943       if (Subtarget->is64Bit()) {
16944         if (VT == MVT::i32 || VT == MVT::f32)
16945           return std::make_pair(0U, &X86::GR32RegClass);
16946         if (VT == MVT::i16)
16947           return std::make_pair(0U, &X86::GR16RegClass);
16948         if (VT == MVT::i8 || VT == MVT::i1)
16949           return std::make_pair(0U, &X86::GR8RegClass);
16950         if (VT == MVT::i64 || VT == MVT::f64)
16951           return std::make_pair(0U, &X86::GR64RegClass);
16952         break;
16953       }
16954       // 32-bit fallthrough
16955     case 'Q':   // Q_REGS
16956       if (VT == MVT::i32 || VT == MVT::f32)
16957         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16958       if (VT == MVT::i16)
16959         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16960       if (VT == MVT::i8 || VT == MVT::i1)
16961         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16962       if (VT == MVT::i64)
16963         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16964       break;
16965     case 'r':   // GENERAL_REGS
16966     case 'l':   // INDEX_REGS
16967       if (VT == MVT::i8 || VT == MVT::i1)
16968         return std::make_pair(0U, &X86::GR8RegClass);
16969       if (VT == MVT::i16)
16970         return std::make_pair(0U, &X86::GR16RegClass);
16971       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16972         return std::make_pair(0U, &X86::GR32RegClass);
16973       return std::make_pair(0U, &X86::GR64RegClass);
16974     case 'R':   // LEGACY_REGS
16975       if (VT == MVT::i8 || VT == MVT::i1)
16976         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16977       if (VT == MVT::i16)
16978         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16979       if (VT == MVT::i32 || !Subtarget->is64Bit())
16980         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16981       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16982     case 'f':  // FP Stack registers.
16983       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16984       // value to the correct fpstack register class.
16985       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16986         return std::make_pair(0U, &X86::RFP32RegClass);
16987       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16988         return std::make_pair(0U, &X86::RFP64RegClass);
16989       return std::make_pair(0U, &X86::RFP80RegClass);
16990     case 'y':   // MMX_REGS if MMX allowed.
16991       if (!Subtarget->hasMMX()) break;
16992       return std::make_pair(0U, &X86::VR64RegClass);
16993     case 'Y':   // SSE_REGS if SSE2 allowed
16994       if (!Subtarget->hasSSE2()) break;
16995       // FALL THROUGH.
16996     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16997       if (!Subtarget->hasSSE1()) break;
16998
16999       switch (VT.getSimpleVT().SimpleTy) {
17000       default: break;
17001       // Scalar SSE types.
17002       case MVT::f32:
17003       case MVT::i32:
17004         return std::make_pair(0U, &X86::FR32RegClass);
17005       case MVT::f64:
17006       case MVT::i64:
17007         return std::make_pair(0U, &X86::FR64RegClass);
17008       // Vector types.
17009       case MVT::v16i8:
17010       case MVT::v8i16:
17011       case MVT::v4i32:
17012       case MVT::v2i64:
17013       case MVT::v4f32:
17014       case MVT::v2f64:
17015         return std::make_pair(0U, &X86::VR128RegClass);
17016       // AVX types.
17017       case MVT::v32i8:
17018       case MVT::v16i16:
17019       case MVT::v8i32:
17020       case MVT::v4i64:
17021       case MVT::v8f32:
17022       case MVT::v4f64:
17023         return std::make_pair(0U, &X86::VR256RegClass);
17024       }
17025       break;
17026     }
17027   }
17028
17029   // Use the default implementation in TargetLowering to convert the register
17030   // constraint into a member of a register class.
17031   std::pair<unsigned, const TargetRegisterClass*> Res;
17032   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17033
17034   // Not found as a standard register?
17035   if (Res.second == 0) {
17036     // Map st(0) -> st(7) -> ST0
17037     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17038         tolower(Constraint[1]) == 's' &&
17039         tolower(Constraint[2]) == 't' &&
17040         Constraint[3] == '(' &&
17041         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17042         Constraint[5] == ')' &&
17043         Constraint[6] == '}') {
17044
17045       Res.first = X86::ST0+Constraint[4]-'0';
17046       Res.second = &X86::RFP80RegClass;
17047       return Res;
17048     }
17049
17050     // GCC allows "st(0)" to be called just plain "st".
17051     if (StringRef("{st}").equals_lower(Constraint)) {
17052       Res.first = X86::ST0;
17053       Res.second = &X86::RFP80RegClass;
17054       return Res;
17055     }
17056
17057     // flags -> EFLAGS
17058     if (StringRef("{flags}").equals_lower(Constraint)) {
17059       Res.first = X86::EFLAGS;
17060       Res.second = &X86::CCRRegClass;
17061       return Res;
17062     }
17063
17064     // 'A' means EAX + EDX.
17065     if (Constraint == "A") {
17066       Res.first = X86::EAX;
17067       Res.second = &X86::GR32_ADRegClass;
17068       return Res;
17069     }
17070     return Res;
17071   }
17072
17073   // Otherwise, check to see if this is a register class of the wrong value
17074   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17075   // turn into {ax},{dx}.
17076   if (Res.second->hasType(VT))
17077     return Res;   // Correct type already, nothing to do.
17078
17079   // All of the single-register GCC register classes map their values onto
17080   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17081   // really want an 8-bit or 32-bit register, map to the appropriate register
17082   // class and return the appropriate register.
17083   if (Res.second == &X86::GR16RegClass) {
17084     if (VT == MVT::i8) {
17085       unsigned DestReg = 0;
17086       switch (Res.first) {
17087       default: break;
17088       case X86::AX: DestReg = X86::AL; break;
17089       case X86::DX: DestReg = X86::DL; break;
17090       case X86::CX: DestReg = X86::CL; break;
17091       case X86::BX: DestReg = X86::BL; break;
17092       }
17093       if (DestReg) {
17094         Res.first = DestReg;
17095         Res.second = &X86::GR8RegClass;
17096       }
17097     } else if (VT == MVT::i32) {
17098       unsigned DestReg = 0;
17099       switch (Res.first) {
17100       default: break;
17101       case X86::AX: DestReg = X86::EAX; break;
17102       case X86::DX: DestReg = X86::EDX; break;
17103       case X86::CX: DestReg = X86::ECX; break;
17104       case X86::BX: DestReg = X86::EBX; break;
17105       case X86::SI: DestReg = X86::ESI; break;
17106       case X86::DI: DestReg = X86::EDI; break;
17107       case X86::BP: DestReg = X86::EBP; break;
17108       case X86::SP: DestReg = X86::ESP; break;
17109       }
17110       if (DestReg) {
17111         Res.first = DestReg;
17112         Res.second = &X86::GR32RegClass;
17113       }
17114     } else if (VT == MVT::i64) {
17115       unsigned DestReg = 0;
17116       switch (Res.first) {
17117       default: break;
17118       case X86::AX: DestReg = X86::RAX; break;
17119       case X86::DX: DestReg = X86::RDX; break;
17120       case X86::CX: DestReg = X86::RCX; break;
17121       case X86::BX: DestReg = X86::RBX; break;
17122       case X86::SI: DestReg = X86::RSI; break;
17123       case X86::DI: DestReg = X86::RDI; break;
17124       case X86::BP: DestReg = X86::RBP; break;
17125       case X86::SP: DestReg = X86::RSP; break;
17126       }
17127       if (DestReg) {
17128         Res.first = DestReg;
17129         Res.second = &X86::GR64RegClass;
17130       }
17131     }
17132   } else if (Res.second == &X86::FR32RegClass ||
17133              Res.second == &X86::FR64RegClass ||
17134              Res.second == &X86::VR128RegClass) {
17135     // Handle references to XMM physical registers that got mapped into the
17136     // wrong class.  This can happen with constraints like {xmm0} where the
17137     // target independent register mapper will just pick the first match it can
17138     // find, ignoring the required type.
17139
17140     if (VT == MVT::f32 || VT == MVT::i32)
17141       Res.second = &X86::FR32RegClass;
17142     else if (VT == MVT::f64 || VT == MVT::i64)
17143       Res.second = &X86::FR64RegClass;
17144     else if (X86::VR128RegClass.hasType(VT))
17145       Res.second = &X86::VR128RegClass;
17146     else if (X86::VR256RegClass.hasType(VT))
17147       Res.second = &X86::VR256RegClass;
17148   }
17149
17150   return Res;
17151 }