When a return struct pointer is passed in registers, the called has nothing
[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 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   // Inserting UNDEF is Result
103   if (Vec.getOpcode() == ISD::UNDEF)
104     return Result;
105
106   EVT VT = Vec.getValueType();
107   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
108
109   EVT ElVT = VT.getVectorElementType();
110   EVT ResultVT = Result.getValueType();
111
112   // Insert the relevant 128 bits.
113   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
114
115   // This is the index of the first element of the 128-bit chunk
116   // we want.
117   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
118                                * ElemsPerChunk);
119
120   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
121   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
122                      VecIdx);
123 }
124
125 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
126 /// instructions. This is used because creating CONCAT_VECTOR nodes of
127 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
128 /// large BUILD_VECTORS.
129 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
130                                    unsigned NumElems, SelectionDAG &DAG,
131                                    DebugLoc dl) {
132   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
133   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
134 }
135
136 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
137   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
138   bool is64Bit = Subtarget->is64Bit();
139
140   if (Subtarget->isTargetEnvMacho()) {
141     if (is64Bit)
142       return new X86_64MachoTargetObjectFile();
143     return new TargetLoweringObjectFileMachO();
144   }
145
146   if (Subtarget->isTargetLinux())
147     return new X86LinuxTargetObjectFile();
148   if (Subtarget->isTargetELF())
149     return new TargetLoweringObjectFileELF();
150   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
151     return new TargetLoweringObjectFileCOFF();
152   llvm_unreachable("unknown subtarget type");
153 }
154
155 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
156   : TargetLowering(TM, createTLOF(TM)) {
157   Subtarget = &TM.getSubtarget<X86Subtarget>();
158   X86ScalarSSEf64 = Subtarget->hasSSE2();
159   X86ScalarSSEf32 = Subtarget->hasSSE1();
160   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
161
162   RegInfo = TM.getRegisterInfo();
163   TD = getTargetData();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom()) 
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(X86StackPtr);
183
184   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
185     // Setup Windows compiler runtime calls.
186     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
187     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
188     setLibcallName(RTLIB::SREM_I64, "_allrem");
189     setLibcallName(RTLIB::UREM_I64, "_aullrem");
190     setLibcallName(RTLIB::MUL_I64, "_allmul");
191     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
192     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
196
197     // The _ftol2 runtime function has an unusual calling conv, which
198     // is modeled by a special pseudo-instruction.
199     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
200     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
202     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
203   }
204
205   if (Subtarget->isTargetDarwin()) {
206     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
207     setUseUnderscoreSetJmp(false);
208     setUseUnderscoreLongJmp(false);
209   } else if (Subtarget->isTargetMingw()) {
210     // MS runtime is weird: it exports _setjmp, but longjmp!
211     setUseUnderscoreSetJmp(true);
212     setUseUnderscoreLongJmp(false);
213   } else {
214     setUseUnderscoreSetJmp(true);
215     setUseUnderscoreLongJmp(true);
216   }
217
218   // Set up the register classes.
219   addRegisterClass(MVT::i8, &X86::GR8RegClass);
220   addRegisterClass(MVT::i16, &X86::GR16RegClass);
221   addRegisterClass(MVT::i32, &X86::GR32RegClass);
222   if (Subtarget->is64Bit())
223     addRegisterClass(MVT::i64, &X86::GR64RegClass);
224
225   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
226
227   // We don't accept any truncstore of integer registers.
228   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
229   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
231   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
232   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
233   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
234
235   // SETOEQ and SETUNE require checking two conditions.
236   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
237   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
239   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
242
243   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
244   // operation.
245   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
248
249   if (Subtarget->is64Bit()) {
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
252   } else if (!TM.Options.UseSoftFloat) {
253     // We have an algorithm for SSE2->double, and we turn this into a
254     // 64-bit FILD followed by conditional FADD for other targets.
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256     // We have an algorithm for SSE2, and we turn this into a 64-bit
257     // FILD for other targets.
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
259   }
260
261   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
262   // this operation.
263   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
265
266   if (!TM.Options.UseSoftFloat) {
267     // SSE has no i16 to fp conversion, only i32
268     if (X86ScalarSSEf32) {
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
270       // f32 and f64 cases are Legal, f80 case is not
271       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
272     } else {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
275     }
276   } else {
277     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
279   }
280
281   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
282   // are Legal, f80 is custom lowered.
283   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
284   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
285
286   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
287   // this operation.
288   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
290
291   if (X86ScalarSSEf32) {
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
293     // f32 and f64 cases are Legal, f80 case is not
294     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
295   } else {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
298   }
299
300   // Handle FP_TO_UINT by promoting the destination to a larger signed
301   // conversion.
302   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
305
306   if (Subtarget->is64Bit()) {
307     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
309   } else if (!TM.Options.UseSoftFloat) {
310     // Since AVX is a superset of SSE3, only check for SSE here.
311     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
312       // Expand FP_TO_UINT into a select.
313       // FIXME: We would like to use a Custom expander here eventually to do
314       // the optimal thing for SSE vs. the default expansion in the legalizer.
315       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
316     else
317       // With SSE3 we can use fisttpll to convert to a signed i64; without
318       // SSE, we're stuck with a fistpll.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
320   }
321
322   if (isTargetFTOL()) {
323     // Use the _ftol2 runtime function, which has a pseudo-instruction
324     // to handle its weird calling convention.
325     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
326   }
327
328   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
329   if (!X86ScalarSSEf64) {
330     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
331     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
332     if (Subtarget->is64Bit()) {
333       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
334       // Without SSE, i64->f64 goes through memory.
335       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
336     }
337   }
338
339   // Scalar integer divide and remainder are lowered to use operations that
340   // produce two results, to match the available instructions. This exposes
341   // the two-result form to trivial CSE, which is able to combine x/y and x%y
342   // into a single instruction.
343   //
344   // Scalar integer multiply-high is also lowered to use two-result
345   // operations, to match the available instructions. However, plain multiply
346   // (low) operations are left as Legal, as there are single-result
347   // instructions for this in x86. Using the two-result multiply instructions
348   // when both high and low results are needed must be arranged by dagcombine.
349   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
350     MVT VT = IntVTs[i];
351     setOperationAction(ISD::MULHS, VT, Expand);
352     setOperationAction(ISD::MULHU, VT, Expand);
353     setOperationAction(ISD::SDIV, VT, Expand);
354     setOperationAction(ISD::UDIV, VT, Expand);
355     setOperationAction(ISD::SREM, VT, Expand);
356     setOperationAction(ISD::UREM, VT, Expand);
357
358     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
359     setOperationAction(ISD::ADDC, VT, Custom);
360     setOperationAction(ISD::ADDE, VT, Custom);
361     setOperationAction(ISD::SUBC, VT, Custom);
362     setOperationAction(ISD::SUBE, VT, Custom);
363   }
364
365   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
366   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
367   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
368   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
369   if (Subtarget->is64Bit())
370     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
371   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
374   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
375   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
378   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
379
380   // Promote the i8 variants and force them on up to i32 which has a shorter
381   // encoding.
382   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
383   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
384   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
385   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
386   if (Subtarget->hasBMI()) {
387     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
391   } else {
392     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
393     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
396   }
397
398   if (Subtarget->hasLZCNT()) {
399     // When promoting the i8 variants, force them to i32 for a shorter
400     // encoding.
401     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
402     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
403     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
404     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
405     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
409   } else {
410     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
411     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
413     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
418       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
419     }
420   }
421
422   if (Subtarget->hasPOPCNT()) {
423     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
424   } else {
425     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
426     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
428     if (Subtarget->is64Bit())
429       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
430   }
431
432   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
433   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
434
435   // These should be promoted to a larger select which is supported.
436   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
437   // X86 wants to expand cmov itself.
438   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
439   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
450   if (Subtarget->is64Bit()) {
451     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
452     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
453   }
454   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
455
456   // Darwin ABI issue.
457   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
458   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
459   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
461   if (Subtarget->is64Bit())
462     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
463   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
464   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
465   if (Subtarget->is64Bit()) {
466     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
467     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
468     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
469     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
470     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
471   }
472   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
473   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
474   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
476   if (Subtarget->is64Bit()) {
477     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
478     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasSSE1())
483     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
484
485   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
486   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
487
488   // On X86 and X86-64, atomic operations are lowered to locked instructions.
489   // Locked instructions, in turn, have implicit fence semantics (all memory
490   // operations are flushed before issuing the locked instruction, and they
491   // are not buffered), so we can fold away the common pattern of
492   // fence-atomic-fence.
493   setShouldFoldAtomicFences(true);
494
495   // Expand certain atomics
496   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
497     MVT VT = IntVTs[i];
498     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
499     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
500     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
501   }
502
503   if (!Subtarget->is64Bit()) {
504     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
512   }
513
514   if (Subtarget->hasCmpxchg16b()) {
515     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
516   }
517
518   // FIXME - use subtarget debug flags
519   if (!Subtarget->isTargetDarwin() &&
520       !Subtarget->isTargetELF() &&
521       !Subtarget->isTargetCygMing()) {
522     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
523   }
524
525   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
526   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
527   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
528   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
529   if (Subtarget->is64Bit()) {
530     setExceptionPointerRegister(X86::RAX);
531     setExceptionSelectorRegister(X86::RDX);
532   } else {
533     setExceptionPointerRegister(X86::EAX);
534     setExceptionSelectorRegister(X86::EDX);
535   }
536   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
538
539   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
540   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
541
542   setOperationAction(ISD::TRAP, MVT::Other, Legal);
543
544   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
545   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
546   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
547   if (Subtarget->is64Bit()) {
548     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
549     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
550   } else {
551     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
552     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
553   }
554
555   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
556   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
557
558   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
559     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
560                        MVT::i64 : MVT::i32, Custom);
561   else if (TM.Options.EnableSegmentedStacks)
562     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
563                        MVT::i64 : MVT::i32, Custom);
564   else
565     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
566                        MVT::i64 : MVT::i32, Expand);
567
568   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
569     // f32 and f64 use SSE.
570     // Set up the FP register classes.
571     addRegisterClass(MVT::f32, &X86::FR32RegClass);
572     addRegisterClass(MVT::f64, &X86::FR64RegClass);
573
574     // Use ANDPD to simulate FABS.
575     setOperationAction(ISD::FABS , MVT::f64, Custom);
576     setOperationAction(ISD::FABS , MVT::f32, Custom);
577
578     // Use XORP to simulate FNEG.
579     setOperationAction(ISD::FNEG , MVT::f64, Custom);
580     setOperationAction(ISD::FNEG , MVT::f32, Custom);
581
582     // Use ANDPD and ORPD to simulate FCOPYSIGN.
583     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
584     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
585
586     // Lower this to FGETSIGNx86 plus an AND.
587     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
588     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
589
590     // We don't support sin/cos/fmod
591     setOperationAction(ISD::FSIN , MVT::f64, Expand);
592     setOperationAction(ISD::FCOS , MVT::f64, Expand);
593     setOperationAction(ISD::FSIN , MVT::f32, Expand);
594     setOperationAction(ISD::FCOS , MVT::f32, Expand);
595
596     // Expand FP immediates into loads from the stack, except for the special
597     // cases we handle.
598     addLegalFPImmediate(APFloat(+0.0)); // xorpd
599     addLegalFPImmediate(APFloat(+0.0f)); // xorps
600   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
601     // Use SSE for f32, x87 for f64.
602     // Set up the FP register classes.
603     addRegisterClass(MVT::f32, &X86::FR32RegClass);
604     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
605
606     // Use ANDPS to simulate FABS.
607     setOperationAction(ISD::FABS , MVT::f32, Custom);
608
609     // Use XORP to simulate FNEG.
610     setOperationAction(ISD::FNEG , MVT::f32, Custom);
611
612     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
613
614     // Use ANDPS and ORPS to simulate FCOPYSIGN.
615     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
617
618     // We don't support sin/cos/fmod
619     setOperationAction(ISD::FSIN , MVT::f32, Expand);
620     setOperationAction(ISD::FCOS , MVT::f32, Expand);
621
622     // Special cases we handle for FP constants.
623     addLegalFPImmediate(APFloat(+0.0f)); // xorps
624     addLegalFPImmediate(APFloat(+0.0)); // FLD0
625     addLegalFPImmediate(APFloat(+1.0)); // FLD1
626     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
627     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
628
629     if (!TM.Options.UnsafeFPMath) {
630       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
631       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
632     }
633   } else if (!TM.Options.UseSoftFloat) {
634     // f32 and f64 in x87.
635     // Set up the FP register classes.
636     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
637     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
638
639     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
640     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
641     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
643
644     if (!TM.Options.UnsafeFPMath) {
645       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
646       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
647     }
648     addLegalFPImmediate(APFloat(+0.0)); // FLD0
649     addLegalFPImmediate(APFloat(+1.0)); // FLD1
650     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
651     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
652     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
653     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
654     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
655     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
656   }
657
658   // We don't support FMA.
659   setOperationAction(ISD::FMA, MVT::f64, Expand);
660   setOperationAction(ISD::FMA, MVT::f32, Expand);
661
662   // Long double always uses X87.
663   if (!TM.Options.UseSoftFloat) {
664     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
665     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
666     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
667     {
668       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
669       addLegalFPImmediate(TmpFlt);  // FLD0
670       TmpFlt.changeSign();
671       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
672
673       bool ignored;
674       APFloat TmpFlt2(+1.0);
675       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
676                       &ignored);
677       addLegalFPImmediate(TmpFlt2);  // FLD1
678       TmpFlt2.changeSign();
679       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
680     }
681
682     if (!TM.Options.UnsafeFPMath) {
683       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
684       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
685     }
686
687     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
688     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
689     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
690     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
691     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
692     setOperationAction(ISD::FMA, MVT::f80, Expand);
693   }
694
695   // Always use a library call for pow.
696   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
697   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
699
700   setOperationAction(ISD::FLOG, MVT::f80, Expand);
701   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
703   setOperationAction(ISD::FEXP, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
705
706   // First set operation action for all vector types to either promote
707   // (for widening) or expand (for scalarization). Then we will selectively
708   // turn on ones that can be effectively codegen'd.
709   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
710            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
711     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
726     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
728     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
763     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
768     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
769              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
770       setTruncStoreAction((MVT::SimpleValueType)VT,
771                           (MVT::SimpleValueType)InnerVT, Expand);
772     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
773     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
774     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
775   }
776
777   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
778   // with -msoft-float, disable use of MMX as well.
779   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
780     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
781     // No operations on x86mmx supported, everything uses intrinsics.
782   }
783
784   // MMX-sized vectors (other than x86mmx) are expected to be expanded
785   // into smaller operations.
786   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
787   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
788   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
789   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
790   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
791   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
792   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
793   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
794   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
795   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
796   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
797   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
798   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
799   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
800   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
801   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
802   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
803   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
806   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
807   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
808   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
810   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
811   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
812   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
815
816   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
817     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
818
819     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
820     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
821     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
824     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
825     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
826     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
827     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
828     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
831   }
832
833   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
834     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
835
836     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
837     // registers cannot be used even for integer operations.
838     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
839     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
840     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
841     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
842
843     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
844     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
845     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
846     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
848     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
849     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
850     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
851     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
852     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
853     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
854     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
855     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
858     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
859
860     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
861     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
862     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
864
865     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
866     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
867     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
868     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
870
871     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
872     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
873     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
874     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
875     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
879       EVT VT = (MVT::SimpleValueType)i;
880       // Do not attempt to custom lower non-power-of-2 vectors
881       if (!isPowerOf2_32(VT.getVectorNumElements()))
882         continue;
883       // Do not attempt to custom lower non-128-bit vectors
884       if (!VT.is128BitVector())
885         continue;
886       setOperationAction(ISD::BUILD_VECTOR,
887                          VT.getSimpleVT().SimpleTy, Custom);
888       setOperationAction(ISD::VECTOR_SHUFFLE,
889                          VT.getSimpleVT().SimpleTy, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
891                          VT.getSimpleVT().SimpleTy, Custom);
892     }
893
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
898     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
899     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
900
901     if (Subtarget->is64Bit()) {
902       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
903       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
904     }
905
906     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
907     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
908       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
909       EVT VT = SVT;
910
911       // Do not attempt to promote non-128-bit vectors
912       if (!VT.is128BitVector())
913         continue;
914
915       setOperationAction(ISD::AND,    SVT, Promote);
916       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
917       setOperationAction(ISD::OR,     SVT, Promote);
918       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
919       setOperationAction(ISD::XOR,    SVT, Promote);
920       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
921       setOperationAction(ISD::LOAD,   SVT, Promote);
922       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
923       setOperationAction(ISD::SELECT, SVT, Promote);
924       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
925     }
926
927     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937   }
938
939   if (Subtarget->hasSSE41()) {
940     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
945     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
946     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
947     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
948     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
949     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
950
951     // FIXME: Do we need to handle scalar-to-vector here?
952     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
953
954     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
956     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
957     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
958     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
959
960     // i8 and i16 vectors are custom , because the source register and source
961     // source memory operand types are not the same width.  f32 vectors are
962     // custom since the immediate controlling the insert encodes additional
963     // information.
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
968
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
970     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
971     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
973
974     // FIXME: these should be Legal but thats only for the case where
975     // the index is constant.  For now custom expand to deal with that.
976     if (Subtarget->is64Bit()) {
977       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
979     }
980   }
981
982   if (Subtarget->hasSSE2()) {
983     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
984     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
985
986     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
987     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
988
989     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
990     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
991
992     if (Subtarget->hasAVX2()) {
993       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
994       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
995
996       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
997       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
998
999       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1000     } else {
1001       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1002       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1003
1004       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1005       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1006
1007       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1008     }
1009   }
1010
1011   if (Subtarget->hasSSE42())
1012     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1013
1014   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1016     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1019     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1021
1022     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1025
1026     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1028     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1031     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1035     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1036     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1038     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1039
1040     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1041     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1042     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1043
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1045     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1046     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1047     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1048     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1049     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1050
1051     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1052     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1053
1054     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1055     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1056
1057     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1058     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1059
1060     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1061     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1062     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1063     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1064
1065     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1066     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1067     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1068
1069     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1070     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1071     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1072     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1073
1074     if (Subtarget->hasAVX2()) {
1075       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1081       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1083       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1084
1085       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1086       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1087       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1088       // Don't lower v32i8 because there is no 128-bit byte mul
1089
1090       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1091
1092       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1093       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1094
1095       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1096       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1097
1098       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1099     } else {
1100       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1108       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1109
1110       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1112       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1113       // Don't lower v32i8 because there is no 128-bit byte mul
1114
1115       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1117
1118       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1119       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1120
1121       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1122     }
1123
1124     // Custom lower several nodes for 256-bit types.
1125     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1126              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1127       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1128       EVT VT = SVT;
1129
1130       // Extract subvector is special because the value type
1131       // (result) is 128-bit but the source is 256-bit wide.
1132       if (VT.is128BitVector())
1133         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1134
1135       // Do not attempt to custom lower other non-256-bit vectors
1136       if (!VT.is256BitVector())
1137         continue;
1138
1139       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1140       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1141       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1142       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1143       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1144       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1145     }
1146
1147     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1148     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1149       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1150       EVT VT = SVT;
1151
1152       // Do not attempt to promote non-256-bit vectors
1153       if (!VT.is256BitVector())
1154         continue;
1155
1156       setOperationAction(ISD::AND,    SVT, Promote);
1157       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1158       setOperationAction(ISD::OR,     SVT, Promote);
1159       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1160       setOperationAction(ISD::XOR,    SVT, Promote);
1161       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1162       setOperationAction(ISD::LOAD,   SVT, Promote);
1163       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1164       setOperationAction(ISD::SELECT, SVT, Promote);
1165       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1166     }
1167   }
1168
1169   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1170   // of this type with custom code.
1171   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1172            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1173     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1174                        Custom);
1175   }
1176
1177   // We want to custom lower some of our intrinsics.
1178   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1179   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1180
1181
1182   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1183   // handle type legalization for these operations here.
1184   //
1185   // FIXME: We really should do custom legalization for addition and
1186   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1187   // than generic legalization for 64-bit multiplication-with-overflow, though.
1188   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1189     // Add/Sub/Mul with overflow operations are custom lowered.
1190     MVT VT = IntVTs[i];
1191     setOperationAction(ISD::SADDO, VT, Custom);
1192     setOperationAction(ISD::UADDO, VT, Custom);
1193     setOperationAction(ISD::SSUBO, VT, Custom);
1194     setOperationAction(ISD::USUBO, VT, Custom);
1195     setOperationAction(ISD::SMULO, VT, Custom);
1196     setOperationAction(ISD::UMULO, VT, Custom);
1197   }
1198
1199   // There are no 8-bit 3-address imul/mul instructions
1200   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1201   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1202
1203   if (!Subtarget->is64Bit()) {
1204     // These libcalls are not available in 32-bit.
1205     setLibcallName(RTLIB::SHL_I128, 0);
1206     setLibcallName(RTLIB::SRL_I128, 0);
1207     setLibcallName(RTLIB::SRA_I128, 0);
1208   }
1209
1210   // We have target-specific dag combine patterns for the following nodes:
1211   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1212   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1213   setTargetDAGCombine(ISD::VSELECT);
1214   setTargetDAGCombine(ISD::SELECT);
1215   setTargetDAGCombine(ISD::SHL);
1216   setTargetDAGCombine(ISD::SRA);
1217   setTargetDAGCombine(ISD::SRL);
1218   setTargetDAGCombine(ISD::OR);
1219   setTargetDAGCombine(ISD::AND);
1220   setTargetDAGCombine(ISD::ADD);
1221   setTargetDAGCombine(ISD::FADD);
1222   setTargetDAGCombine(ISD::FSUB);
1223   setTargetDAGCombine(ISD::SUB);
1224   setTargetDAGCombine(ISD::LOAD);
1225   setTargetDAGCombine(ISD::STORE);
1226   setTargetDAGCombine(ISD::ZERO_EXTEND);
1227   setTargetDAGCombine(ISD::ANY_EXTEND);
1228   setTargetDAGCombine(ISD::SIGN_EXTEND);
1229   setTargetDAGCombine(ISD::TRUNCATE);
1230   setTargetDAGCombine(ISD::UINT_TO_FP);
1231   setTargetDAGCombine(ISD::SINT_TO_FP);
1232   setTargetDAGCombine(ISD::SETCC);
1233   setTargetDAGCombine(ISD::FP_TO_SINT);
1234   if (Subtarget->is64Bit())
1235     setTargetDAGCombine(ISD::MUL);
1236   setTargetDAGCombine(ISD::XOR);
1237
1238   computeRegisterProperties();
1239
1240   // On Darwin, -Os means optimize for size without hurting performance,
1241   // do not reduce the limit.
1242   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1243   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1244   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1245   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1246   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1247   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1248   setPrefLoopAlignment(4); // 2^4 bytes.
1249   benefitFromCodePlacementOpt = true;
1250
1251   // Predictable cmov don't hurt on atom because it's in-order.
1252   predictableSelectIsExpensive = !Subtarget->isAtom();
1253
1254   setPrefFunctionAlignment(4); // 2^4 bytes.
1255 }
1256
1257
1258 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1259   if (!VT.isVector()) return MVT::i8;
1260   return VT.changeVectorElementTypeToInteger();
1261 }
1262
1263
1264 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1265 /// the desired ByVal argument alignment.
1266 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1267   if (MaxAlign == 16)
1268     return;
1269   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1270     if (VTy->getBitWidth() == 128)
1271       MaxAlign = 16;
1272   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1273     unsigned EltAlign = 0;
1274     getMaxByValAlign(ATy->getElementType(), EltAlign);
1275     if (EltAlign > MaxAlign)
1276       MaxAlign = EltAlign;
1277   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1278     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1279       unsigned EltAlign = 0;
1280       getMaxByValAlign(STy->getElementType(i), EltAlign);
1281       if (EltAlign > MaxAlign)
1282         MaxAlign = EltAlign;
1283       if (MaxAlign == 16)
1284         break;
1285     }
1286   }
1287 }
1288
1289 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1290 /// function arguments in the caller parameter area. For X86, aggregates
1291 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1292 /// are at 4-byte boundaries.
1293 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1294   if (Subtarget->is64Bit()) {
1295     // Max of 8 and alignment of type.
1296     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1297     if (TyAlign > 8)
1298       return TyAlign;
1299     return 8;
1300   }
1301
1302   unsigned Align = 4;
1303   if (Subtarget->hasSSE1())
1304     getMaxByValAlign(Ty, Align);
1305   return Align;
1306 }
1307
1308 /// getOptimalMemOpType - Returns the target specific optimal type for load
1309 /// and store operations as a result of memset, memcpy, and memmove
1310 /// lowering. If DstAlign is zero that means it's safe to destination
1311 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1312 /// means there isn't a need to check it against alignment requirement,
1313 /// probably because the source does not need to be loaded. If
1314 /// 'IsZeroVal' is true, that means it's safe to return a
1315 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1316 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1317 /// constant so it does not need to be loaded.
1318 /// It returns EVT::Other if the type should be determined using generic
1319 /// target-independent logic.
1320 EVT
1321 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1322                                        unsigned DstAlign, unsigned SrcAlign,
1323                                        bool IsZeroVal,
1324                                        bool MemcpyStrSrc,
1325                                        MachineFunction &MF) const {
1326   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1327   // linux.  This is because the stack realignment code can't handle certain
1328   // cases like PR2962.  This should be removed when PR2962 is fixed.
1329   const Function *F = MF.getFunction();
1330   if (IsZeroVal &&
1331       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1332     if (Size >= 16 &&
1333         (Subtarget->isUnalignedMemAccessFast() ||
1334          ((DstAlign == 0 || DstAlign >= 16) &&
1335           (SrcAlign == 0 || SrcAlign >= 16))) &&
1336         Subtarget->getStackAlignment() >= 16) {
1337       if (Subtarget->getStackAlignment() >= 32) {
1338         if (Subtarget->hasAVX2())
1339           return MVT::v8i32;
1340         if (Subtarget->hasAVX())
1341           return MVT::v8f32;
1342       }
1343       if (Subtarget->hasSSE2())
1344         return MVT::v4i32;
1345       if (Subtarget->hasSSE1())
1346         return MVT::v4f32;
1347     } else if (!MemcpyStrSrc && Size >= 8 &&
1348                !Subtarget->is64Bit() &&
1349                Subtarget->getStackAlignment() >= 8 &&
1350                Subtarget->hasSSE2()) {
1351       // Do not use f64 to lower memcpy if source is string constant. It's
1352       // better to use i32 to avoid the loads.
1353       return MVT::f64;
1354     }
1355   }
1356   if (Subtarget->is64Bit() && Size >= 8)
1357     return MVT::i64;
1358   return MVT::i32;
1359 }
1360
1361 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1362 /// current function.  The returned value is a member of the
1363 /// MachineJumpTableInfo::JTEntryKind enum.
1364 unsigned X86TargetLowering::getJumpTableEncoding() const {
1365   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1366   // symbol.
1367   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1368       Subtarget->isPICStyleGOT())
1369     return MachineJumpTableInfo::EK_Custom32;
1370
1371   // Otherwise, use the normal jump table encoding heuristics.
1372   return TargetLowering::getJumpTableEncoding();
1373 }
1374
1375 const MCExpr *
1376 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1377                                              const MachineBasicBlock *MBB,
1378                                              unsigned uid,MCContext &Ctx) const{
1379   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1380          Subtarget->isPICStyleGOT());
1381   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1382   // entries.
1383   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1384                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1385 }
1386
1387 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1388 /// jumptable.
1389 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1390                                                     SelectionDAG &DAG) const {
1391   if (!Subtarget->is64Bit())
1392     // This doesn't have DebugLoc associated with it, but is not really the
1393     // same as a Register.
1394     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1395   return Table;
1396 }
1397
1398 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1399 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1400 /// MCExpr.
1401 const MCExpr *X86TargetLowering::
1402 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1403                              MCContext &Ctx) const {
1404   // X86-64 uses RIP relative addressing based on the jump table label.
1405   if (Subtarget->isPICStyleRIPRel())
1406     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1407
1408   // Otherwise, the reference is relative to the PIC base.
1409   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1410 }
1411
1412 // FIXME: Why this routine is here? Move to RegInfo!
1413 std::pair<const TargetRegisterClass*, uint8_t>
1414 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1415   const TargetRegisterClass *RRC = 0;
1416   uint8_t Cost = 1;
1417   switch (VT.getSimpleVT().SimpleTy) {
1418   default:
1419     return TargetLowering::findRepresentativeClass(VT);
1420   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1421     RRC = Subtarget->is64Bit() ?
1422       (const TargetRegisterClass*)&X86::GR64RegClass :
1423       (const TargetRegisterClass*)&X86::GR32RegClass;
1424     break;
1425   case MVT::x86mmx:
1426     RRC = &X86::VR64RegClass;
1427     break;
1428   case MVT::f32: case MVT::f64:
1429   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1430   case MVT::v4f32: case MVT::v2f64:
1431   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1432   case MVT::v4f64:
1433     RRC = &X86::VR128RegClass;
1434     break;
1435   }
1436   return std::make_pair(RRC, Cost);
1437 }
1438
1439 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1440                                                unsigned &Offset) const {
1441   if (!Subtarget->isTargetLinux())
1442     return false;
1443
1444   if (Subtarget->is64Bit()) {
1445     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1446     Offset = 0x28;
1447     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1448       AddressSpace = 256;
1449     else
1450       AddressSpace = 257;
1451   } else {
1452     // %gs:0x14 on i386
1453     Offset = 0x14;
1454     AddressSpace = 256;
1455   }
1456   return true;
1457 }
1458
1459
1460 //===----------------------------------------------------------------------===//
1461 //               Return Value Calling Convention Implementation
1462 //===----------------------------------------------------------------------===//
1463
1464 #include "X86GenCallingConv.inc"
1465
1466 bool
1467 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1468                                   MachineFunction &MF, bool isVarArg,
1469                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1470                         LLVMContext &Context) const {
1471   SmallVector<CCValAssign, 16> RVLocs;
1472   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1473                  RVLocs, Context);
1474   return CCInfo.CheckReturn(Outs, RetCC_X86);
1475 }
1476
1477 SDValue
1478 X86TargetLowering::LowerReturn(SDValue Chain,
1479                                CallingConv::ID CallConv, bool isVarArg,
1480                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1481                                const SmallVectorImpl<SDValue> &OutVals,
1482                                DebugLoc dl, SelectionDAG &DAG) const {
1483   MachineFunction &MF = DAG.getMachineFunction();
1484   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1485
1486   SmallVector<CCValAssign, 16> RVLocs;
1487   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1488                  RVLocs, *DAG.getContext());
1489   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1490
1491   // Add the regs to the liveout set for the function.
1492   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1493   for (unsigned i = 0; i != RVLocs.size(); ++i)
1494     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1495       MRI.addLiveOut(RVLocs[i].getLocReg());
1496
1497   SDValue Flag;
1498
1499   SmallVector<SDValue, 6> RetOps;
1500   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1501   // Operand #1 = Bytes To Pop
1502   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1503                    MVT::i16));
1504
1505   // Copy the result values into the output registers.
1506   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1507     CCValAssign &VA = RVLocs[i];
1508     assert(VA.isRegLoc() && "Can only return in registers!");
1509     SDValue ValToCopy = OutVals[i];
1510     EVT ValVT = ValToCopy.getValueType();
1511
1512     // Promote values to the appropriate types
1513     if (VA.getLocInfo() == CCValAssign::SExt)
1514       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1515     else if (VA.getLocInfo() == CCValAssign::ZExt)
1516       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1517     else if (VA.getLocInfo() == CCValAssign::AExt)
1518       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1519     else if (VA.getLocInfo() == CCValAssign::BCvt)
1520       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1521
1522     // If this is x86-64, and we disabled SSE, we can't return FP values,
1523     // or SSE or MMX vectors.
1524     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1525          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1526           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1527       report_fatal_error("SSE register return with SSE disabled");
1528     }
1529     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1530     // llvm-gcc has never done it right and no one has noticed, so this
1531     // should be OK for now.
1532     if (ValVT == MVT::f64 &&
1533         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1534       report_fatal_error("SSE2 register return with SSE2 disabled");
1535
1536     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1537     // the RET instruction and handled by the FP Stackifier.
1538     if (VA.getLocReg() == X86::ST0 ||
1539         VA.getLocReg() == X86::ST1) {
1540       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1541       // change the value to the FP stack register class.
1542       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1543         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1544       RetOps.push_back(ValToCopy);
1545       // Don't emit a copytoreg.
1546       continue;
1547     }
1548
1549     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1550     // which is returned in RAX / RDX.
1551     if (Subtarget->is64Bit()) {
1552       if (ValVT == MVT::x86mmx) {
1553         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1554           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1555           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1556                                   ValToCopy);
1557           // If we don't have SSE2 available, convert to v4f32 so the generated
1558           // register is legal.
1559           if (!Subtarget->hasSSE2())
1560             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1561         }
1562       }
1563     }
1564
1565     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1566     Flag = Chain.getValue(1);
1567   }
1568
1569   // The x86-64 ABI for returning structs by value requires that we copy
1570   // the sret argument into %rax for the return. We saved the argument into
1571   // a virtual register in the entry block, so now we copy the value out
1572   // and into %rax.
1573   if (Subtarget->is64Bit() &&
1574       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1575     MachineFunction &MF = DAG.getMachineFunction();
1576     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1577     unsigned Reg = FuncInfo->getSRetReturnReg();
1578     assert(Reg &&
1579            "SRetReturnReg should have been set in LowerFormalArguments().");
1580     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1581
1582     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1583     Flag = Chain.getValue(1);
1584
1585     // RAX now acts like a return value.
1586     MRI.addLiveOut(X86::RAX);
1587   }
1588
1589   RetOps[0] = Chain;  // Update chain.
1590
1591   // Add the flag if we have it.
1592   if (Flag.getNode())
1593     RetOps.push_back(Flag);
1594
1595   return DAG.getNode(X86ISD::RET_FLAG, dl,
1596                      MVT::Other, &RetOps[0], RetOps.size());
1597 }
1598
1599 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1600   if (N->getNumValues() != 1)
1601     return false;
1602   if (!N->hasNUsesOfValue(1, 0))
1603     return false;
1604
1605   SDValue TCChain = Chain;
1606   SDNode *Copy = *N->use_begin();
1607   if (Copy->getOpcode() == ISD::CopyToReg) {
1608     // If the copy has a glue operand, we conservatively assume it isn't safe to
1609     // perform a tail call.
1610     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1611       return false;
1612     TCChain = Copy->getOperand(0);
1613   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1614     return false;
1615
1616   bool HasRet = false;
1617   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1618        UI != UE; ++UI) {
1619     if (UI->getOpcode() != X86ISD::RET_FLAG)
1620       return false;
1621     HasRet = true;
1622   }
1623
1624   if (!HasRet)
1625     return false;
1626
1627   Chain = TCChain;
1628   return true;
1629 }
1630
1631 EVT
1632 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1633                                             ISD::NodeType ExtendKind) const {
1634   MVT ReturnMVT;
1635   // TODO: Is this also valid on 32-bit?
1636   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1637     ReturnMVT = MVT::i8;
1638   else
1639     ReturnMVT = MVT::i32;
1640
1641   EVT MinVT = getRegisterType(Context, ReturnMVT);
1642   return VT.bitsLT(MinVT) ? MinVT : VT;
1643 }
1644
1645 /// LowerCallResult - Lower the result values of a call into the
1646 /// appropriate copies out of appropriate physical registers.
1647 ///
1648 SDValue
1649 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1650                                    CallingConv::ID CallConv, bool isVarArg,
1651                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1652                                    DebugLoc dl, SelectionDAG &DAG,
1653                                    SmallVectorImpl<SDValue> &InVals) const {
1654
1655   // Assign locations to each value returned by this call.
1656   SmallVector<CCValAssign, 16> RVLocs;
1657   bool Is64Bit = Subtarget->is64Bit();
1658   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1659                  getTargetMachine(), RVLocs, *DAG.getContext());
1660   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1661
1662   // Copy all of the result registers out of their specified physreg.
1663   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1664     CCValAssign &VA = RVLocs[i];
1665     EVT CopyVT = VA.getValVT();
1666
1667     // If this is x86-64, and we disabled SSE, we can't return FP values
1668     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1669         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1670       report_fatal_error("SSE register return with SSE disabled");
1671     }
1672
1673     SDValue Val;
1674
1675     // If this is a call to a function that returns an fp value on the floating
1676     // point stack, we must guarantee the value is popped from the stack, so
1677     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1678     // if the return value is not used. We use the FpPOP_RETVAL instruction
1679     // instead.
1680     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1681       // If we prefer to use the value in xmm registers, copy it out as f80 and
1682       // use a truncate to move it from fp stack reg to xmm reg.
1683       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1684       SDValue Ops[] = { Chain, InFlag };
1685       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1686                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1687       Val = Chain.getValue(0);
1688
1689       // Round the f80 to the right size, which also moves it to the appropriate
1690       // xmm register.
1691       if (CopyVT != VA.getValVT())
1692         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1693                           // This truncation won't change the value.
1694                           DAG.getIntPtrConstant(1));
1695     } else {
1696       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1697                                  CopyVT, InFlag).getValue(1);
1698       Val = Chain.getValue(0);
1699     }
1700     InFlag = Chain.getValue(2);
1701     InVals.push_back(Val);
1702   }
1703
1704   return Chain;
1705 }
1706
1707
1708 //===----------------------------------------------------------------------===//
1709 //                C & StdCall & Fast Calling Convention implementation
1710 //===----------------------------------------------------------------------===//
1711 //  StdCall calling convention seems to be standard for many Windows' API
1712 //  routines and around. It differs from C calling convention just a little:
1713 //  callee should clean up the stack, not caller. Symbols should be also
1714 //  decorated in some fancy way :) It doesn't support any vector arguments.
1715 //  For info on fast calling convention see Fast Calling Convention (tail call)
1716 //  implementation LowerX86_32FastCCCallTo.
1717
1718 /// CallIsStructReturn - Determines whether a call uses struct return
1719 /// semantics.
1720 enum StructReturnType {
1721   NotStructReturn,
1722   RegStructReturn,
1723   StackStructReturn
1724 };
1725 static StructReturnType
1726 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1727   if (Outs.empty())
1728     return NotStructReturn;
1729
1730   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1731   if (!Flags.isSRet())
1732     return NotStructReturn;
1733   if (Flags.isInReg())
1734     return RegStructReturn;
1735   return StackStructReturn;
1736 }
1737
1738 /// ArgsAreStructReturn - Determines whether a function uses struct
1739 /// return semantics.
1740 static StructReturnType
1741 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1742   if (Ins.empty())
1743     return NotStructReturn;
1744
1745   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1746   if (!Flags.isSRet())
1747     return NotStructReturn;
1748   if (Flags.isInReg())
1749     return RegStructReturn;
1750   return StackStructReturn;
1751 }
1752
1753 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1754 /// by "Src" to address "Dst" with size and alignment information specified by
1755 /// the specific parameter attribute. The copy will be passed as a byval
1756 /// function parameter.
1757 static SDValue
1758 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1759                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1760                           DebugLoc dl) {
1761   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1762
1763   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1764                        /*isVolatile*/false, /*AlwaysInline=*/true,
1765                        MachinePointerInfo(), MachinePointerInfo());
1766 }
1767
1768 /// IsTailCallConvention - Return true if the calling convention is one that
1769 /// supports tail call optimization.
1770 static bool IsTailCallConvention(CallingConv::ID CC) {
1771   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1772 }
1773
1774 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1775   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1776     return false;
1777
1778   CallSite CS(CI);
1779   CallingConv::ID CalleeCC = CS.getCallingConv();
1780   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1781     return false;
1782
1783   return true;
1784 }
1785
1786 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1787 /// a tailcall target by changing its ABI.
1788 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1789                                    bool GuaranteedTailCallOpt) {
1790   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1791 }
1792
1793 SDValue
1794 X86TargetLowering::LowerMemArgument(SDValue Chain,
1795                                     CallingConv::ID CallConv,
1796                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1797                                     DebugLoc dl, SelectionDAG &DAG,
1798                                     const CCValAssign &VA,
1799                                     MachineFrameInfo *MFI,
1800                                     unsigned i) const {
1801   // Create the nodes corresponding to a load from this parameter slot.
1802   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1803   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1804                               getTargetMachine().Options.GuaranteedTailCallOpt);
1805   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1806   EVT ValVT;
1807
1808   // If value is passed by pointer we have address passed instead of the value
1809   // itself.
1810   if (VA.getLocInfo() == CCValAssign::Indirect)
1811     ValVT = VA.getLocVT();
1812   else
1813     ValVT = VA.getValVT();
1814
1815   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1816   // changed with more analysis.
1817   // In case of tail call optimization mark all arguments mutable. Since they
1818   // could be overwritten by lowering of arguments in case of a tail call.
1819   if (Flags.isByVal()) {
1820     unsigned Bytes = Flags.getByValSize();
1821     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1822     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1823     return DAG.getFrameIndex(FI, getPointerTy());
1824   } else {
1825     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1826                                     VA.getLocMemOffset(), isImmutable);
1827     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1828     return DAG.getLoad(ValVT, dl, Chain, FIN,
1829                        MachinePointerInfo::getFixedStack(FI),
1830                        false, false, false, 0);
1831   }
1832 }
1833
1834 SDValue
1835 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1836                                         CallingConv::ID CallConv,
1837                                         bool isVarArg,
1838                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1839                                         DebugLoc dl,
1840                                         SelectionDAG &DAG,
1841                                         SmallVectorImpl<SDValue> &InVals)
1842                                           const {
1843   MachineFunction &MF = DAG.getMachineFunction();
1844   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1845
1846   const Function* Fn = MF.getFunction();
1847   if (Fn->hasExternalLinkage() &&
1848       Subtarget->isTargetCygMing() &&
1849       Fn->getName() == "main")
1850     FuncInfo->setForceFramePointer(true);
1851
1852   MachineFrameInfo *MFI = MF.getFrameInfo();
1853   bool Is64Bit = Subtarget->is64Bit();
1854   bool IsWindows = Subtarget->isTargetWindows();
1855   bool IsWin64 = Subtarget->isTargetWin64();
1856
1857   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1858          "Var args not supported with calling convention fastcc or ghc");
1859
1860   // Assign locations to all of the incoming arguments.
1861   SmallVector<CCValAssign, 16> ArgLocs;
1862   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1863                  ArgLocs, *DAG.getContext());
1864
1865   // Allocate shadow area for Win64
1866   if (IsWin64) {
1867     CCInfo.AllocateStack(32, 8);
1868   }
1869
1870   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1871
1872   unsigned LastVal = ~0U;
1873   SDValue ArgValue;
1874   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1875     CCValAssign &VA = ArgLocs[i];
1876     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1877     // places.
1878     assert(VA.getValNo() != LastVal &&
1879            "Don't support value assigned to multiple locs yet");
1880     (void)LastVal;
1881     LastVal = VA.getValNo();
1882
1883     if (VA.isRegLoc()) {
1884       EVT RegVT = VA.getLocVT();
1885       const TargetRegisterClass *RC;
1886       if (RegVT == MVT::i32)
1887         RC = &X86::GR32RegClass;
1888       else if (Is64Bit && RegVT == MVT::i64)
1889         RC = &X86::GR64RegClass;
1890       else if (RegVT == MVT::f32)
1891         RC = &X86::FR32RegClass;
1892       else if (RegVT == MVT::f64)
1893         RC = &X86::FR64RegClass;
1894       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1895         RC = &X86::VR256RegClass;
1896       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1897         RC = &X86::VR128RegClass;
1898       else if (RegVT == MVT::x86mmx)
1899         RC = &X86::VR64RegClass;
1900       else
1901         llvm_unreachable("Unknown argument type!");
1902
1903       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1904       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1905
1906       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1907       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1908       // right size.
1909       if (VA.getLocInfo() == CCValAssign::SExt)
1910         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1911                                DAG.getValueType(VA.getValVT()));
1912       else if (VA.getLocInfo() == CCValAssign::ZExt)
1913         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1914                                DAG.getValueType(VA.getValVT()));
1915       else if (VA.getLocInfo() == CCValAssign::BCvt)
1916         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1917
1918       if (VA.isExtInLoc()) {
1919         // Handle MMX values passed in XMM regs.
1920         if (RegVT.isVector()) {
1921           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1922                                  ArgValue);
1923         } else
1924           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1925       }
1926     } else {
1927       assert(VA.isMemLoc());
1928       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1929     }
1930
1931     // If value is passed via pointer - do a load.
1932     if (VA.getLocInfo() == CCValAssign::Indirect)
1933       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1934                              MachinePointerInfo(), false, false, false, 0);
1935
1936     InVals.push_back(ArgValue);
1937   }
1938
1939   // The x86-64 ABI for returning structs by value requires that we copy
1940   // the sret argument into %rax for the return. Save the argument into
1941   // a virtual register so that we can access it from the return points.
1942   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1943     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1944     unsigned Reg = FuncInfo->getSRetReturnReg();
1945     if (!Reg) {
1946       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1947       FuncInfo->setSRetReturnReg(Reg);
1948     }
1949     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1950     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1951   }
1952
1953   unsigned StackSize = CCInfo.getNextStackOffset();
1954   // Align stack specially for tail calls.
1955   if (FuncIsMadeTailCallSafe(CallConv,
1956                              MF.getTarget().Options.GuaranteedTailCallOpt))
1957     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1958
1959   // If the function takes variable number of arguments, make a frame index for
1960   // the start of the first vararg value... for expansion of llvm.va_start.
1961   if (isVarArg) {
1962     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1963                     CallConv != CallingConv::X86_ThisCall)) {
1964       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1965     }
1966     if (Is64Bit) {
1967       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1968
1969       // FIXME: We should really autogenerate these arrays
1970       static const uint16_t GPR64ArgRegsWin64[] = {
1971         X86::RCX, X86::RDX, X86::R8,  X86::R9
1972       };
1973       static const uint16_t GPR64ArgRegs64Bit[] = {
1974         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1975       };
1976       static const uint16_t XMMArgRegs64Bit[] = {
1977         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1978         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1979       };
1980       const uint16_t *GPR64ArgRegs;
1981       unsigned NumXMMRegs = 0;
1982
1983       if (IsWin64) {
1984         // The XMM registers which might contain var arg parameters are shadowed
1985         // in their paired GPR.  So we only need to save the GPR to their home
1986         // slots.
1987         TotalNumIntRegs = 4;
1988         GPR64ArgRegs = GPR64ArgRegsWin64;
1989       } else {
1990         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1991         GPR64ArgRegs = GPR64ArgRegs64Bit;
1992
1993         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1994                                                 TotalNumXMMRegs);
1995       }
1996       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1997                                                        TotalNumIntRegs);
1998
1999       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2000       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2001              "SSE register cannot be used when SSE is disabled!");
2002       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2003                NoImplicitFloatOps) &&
2004              "SSE register cannot be used when SSE is disabled!");
2005       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2006           !Subtarget->hasSSE1())
2007         // Kernel mode asks for SSE to be disabled, so don't push them
2008         // on the stack.
2009         TotalNumXMMRegs = 0;
2010
2011       if (IsWin64) {
2012         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2013         // Get to the caller-allocated home save location.  Add 8 to account
2014         // for the return address.
2015         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2016         FuncInfo->setRegSaveFrameIndex(
2017           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2018         // Fixup to set vararg frame on shadow area (4 x i64).
2019         if (NumIntRegs < 4)
2020           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2021       } else {
2022         // For X86-64, if there are vararg parameters that are passed via
2023         // registers, then we must store them to their spots on the stack so
2024         // they may be loaded by deferencing the result of va_next.
2025         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2026         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2027         FuncInfo->setRegSaveFrameIndex(
2028           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2029                                false));
2030       }
2031
2032       // Store the integer parameter registers.
2033       SmallVector<SDValue, 8> MemOps;
2034       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2035                                         getPointerTy());
2036       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2037       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2038         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2039                                   DAG.getIntPtrConstant(Offset));
2040         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2041                                      &X86::GR64RegClass);
2042         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2043         SDValue Store =
2044           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2045                        MachinePointerInfo::getFixedStack(
2046                          FuncInfo->getRegSaveFrameIndex(), Offset),
2047                        false, false, 0);
2048         MemOps.push_back(Store);
2049         Offset += 8;
2050       }
2051
2052       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2053         // Now store the XMM (fp + vector) parameter registers.
2054         SmallVector<SDValue, 11> SaveXMMOps;
2055         SaveXMMOps.push_back(Chain);
2056
2057         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2058         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2059         SaveXMMOps.push_back(ALVal);
2060
2061         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2062                                FuncInfo->getRegSaveFrameIndex()));
2063         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2064                                FuncInfo->getVarArgsFPOffset()));
2065
2066         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2067           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2068                                        &X86::VR128RegClass);
2069           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2070           SaveXMMOps.push_back(Val);
2071         }
2072         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2073                                      MVT::Other,
2074                                      &SaveXMMOps[0], SaveXMMOps.size()));
2075       }
2076
2077       if (!MemOps.empty())
2078         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2079                             &MemOps[0], MemOps.size());
2080     }
2081   }
2082
2083   // Some CCs need callee pop.
2084   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2085                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2086     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2087   } else {
2088     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2089     // If this is an sret function, the return should pop the hidden pointer.
2090     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2091         argsAreStructReturn(Ins) == StackStructReturn)
2092       FuncInfo->setBytesToPopOnReturn(4);
2093   }
2094
2095   if (!Is64Bit) {
2096     // RegSaveFrameIndex is X86-64 only.
2097     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2098     if (CallConv == CallingConv::X86_FastCall ||
2099         CallConv == CallingConv::X86_ThisCall)
2100       // fastcc functions can't have varargs.
2101       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2102   }
2103
2104   FuncInfo->setArgumentStackSize(StackSize);
2105
2106   return Chain;
2107 }
2108
2109 SDValue
2110 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2111                                     SDValue StackPtr, SDValue Arg,
2112                                     DebugLoc dl, SelectionDAG &DAG,
2113                                     const CCValAssign &VA,
2114                                     ISD::ArgFlagsTy Flags) const {
2115   unsigned LocMemOffset = VA.getLocMemOffset();
2116   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2117   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2118   if (Flags.isByVal())
2119     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2120
2121   return DAG.getStore(Chain, dl, Arg, PtrOff,
2122                       MachinePointerInfo::getStack(LocMemOffset),
2123                       false, false, 0);
2124 }
2125
2126 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2127 /// optimization is performed and it is required.
2128 SDValue
2129 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2130                                            SDValue &OutRetAddr, SDValue Chain,
2131                                            bool IsTailCall, bool Is64Bit,
2132                                            int FPDiff, DebugLoc dl) const {
2133   // Adjust the Return address stack slot.
2134   EVT VT = getPointerTy();
2135   OutRetAddr = getReturnAddressFrameIndex(DAG);
2136
2137   // Load the "old" Return address.
2138   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2139                            false, false, false, 0);
2140   return SDValue(OutRetAddr.getNode(), 1);
2141 }
2142
2143 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2144 /// optimization is performed and it is required (FPDiff!=0).
2145 static SDValue
2146 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2147                          SDValue Chain, SDValue RetAddrFrIdx,
2148                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2149   // Store the return address to the appropriate stack slot.
2150   if (!FPDiff) return Chain;
2151   // Calculate the new stack slot for the return address.
2152   int SlotSize = Is64Bit ? 8 : 4;
2153   int NewReturnAddrFI =
2154     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2155   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2156   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2157   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2158                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2159                        false, false, 0);
2160   return Chain;
2161 }
2162
2163 SDValue
2164 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2165                              SmallVectorImpl<SDValue> &InVals) const {
2166   SelectionDAG &DAG                     = CLI.DAG;
2167   DebugLoc &dl                          = CLI.DL;
2168   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2169   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2170   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2171   SDValue Chain                         = CLI.Chain;
2172   SDValue Callee                        = CLI.Callee;
2173   CallingConv::ID CallConv              = CLI.CallConv;
2174   bool &isTailCall                      = CLI.IsTailCall;
2175   bool isVarArg                         = CLI.IsVarArg;
2176
2177   MachineFunction &MF = DAG.getMachineFunction();
2178   bool Is64Bit        = Subtarget->is64Bit();
2179   bool IsWin64        = Subtarget->isTargetWin64();
2180   bool IsWindows      = Subtarget->isTargetWindows();
2181   StructReturnType SR = callIsStructReturn(Outs);
2182   bool IsSibcall      = false;
2183
2184   if (MF.getTarget().Options.DisableTailCalls)
2185     isTailCall = false;
2186
2187   if (isTailCall) {
2188     // Check if it's really possible to do a tail call.
2189     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2190                     isVarArg, SR != NotStructReturn,
2191                     MF.getFunction()->hasStructRetAttr(),
2192                     Outs, OutVals, Ins, DAG);
2193
2194     // Sibcalls are automatically detected tailcalls which do not require
2195     // ABI changes.
2196     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2197       IsSibcall = true;
2198
2199     if (isTailCall)
2200       ++NumTailCalls;
2201   }
2202
2203   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204          "Var args not supported with calling convention fastcc or ghc");
2205
2206   // Analyze operands of the call, assigning locations to each operand.
2207   SmallVector<CCValAssign, 16> ArgLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209                  ArgLocs, *DAG.getContext());
2210
2211   // Allocate shadow area for Win64
2212   if (IsWin64) {
2213     CCInfo.AllocateStack(32, 8);
2214   }
2215
2216   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2217
2218   // Get a count of how many bytes are to be pushed on the stack.
2219   unsigned NumBytes = CCInfo.getNextStackOffset();
2220   if (IsSibcall)
2221     // This is a sibcall. The memory operands are available in caller's
2222     // own caller's stack.
2223     NumBytes = 0;
2224   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2225            IsTailCallConvention(CallConv))
2226     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2227
2228   int FPDiff = 0;
2229   if (isTailCall && !IsSibcall) {
2230     // Lower arguments at fp - stackoffset + fpdiff.
2231     unsigned NumBytesCallerPushed =
2232       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2233     FPDiff = NumBytesCallerPushed - NumBytes;
2234
2235     // Set the delta of movement of the returnaddr stackslot.
2236     // But only set if delta is greater than previous delta.
2237     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2238       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2239   }
2240
2241   if (!IsSibcall)
2242     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2243
2244   SDValue RetAddrFrIdx;
2245   // Load return address for tail calls.
2246   if (isTailCall && FPDiff)
2247     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2248                                     Is64Bit, FPDiff, dl);
2249
2250   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2251   SmallVector<SDValue, 8> MemOpChains;
2252   SDValue StackPtr;
2253
2254   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2255   // of tail call optimization arguments are handle later.
2256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2257     CCValAssign &VA = ArgLocs[i];
2258     EVT RegVT = VA.getLocVT();
2259     SDValue Arg = OutVals[i];
2260     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2261     bool isByVal = Flags.isByVal();
2262
2263     // Promote the value if needed.
2264     switch (VA.getLocInfo()) {
2265     default: llvm_unreachable("Unknown loc info!");
2266     case CCValAssign::Full: break;
2267     case CCValAssign::SExt:
2268       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2269       break;
2270     case CCValAssign::ZExt:
2271       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2272       break;
2273     case CCValAssign::AExt:
2274       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2275         // Special case: passing MMX values in XMM registers.
2276         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2277         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2278         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2279       } else
2280         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2281       break;
2282     case CCValAssign::BCvt:
2283       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2284       break;
2285     case CCValAssign::Indirect: {
2286       // Store the argument.
2287       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2288       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2289       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2290                            MachinePointerInfo::getFixedStack(FI),
2291                            false, false, 0);
2292       Arg = SpillSlot;
2293       break;
2294     }
2295     }
2296
2297     if (VA.isRegLoc()) {
2298       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2299       if (isVarArg && IsWin64) {
2300         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2301         // shadow reg if callee is a varargs function.
2302         unsigned ShadowReg = 0;
2303         switch (VA.getLocReg()) {
2304         case X86::XMM0: ShadowReg = X86::RCX; break;
2305         case X86::XMM1: ShadowReg = X86::RDX; break;
2306         case X86::XMM2: ShadowReg = X86::R8; break;
2307         case X86::XMM3: ShadowReg = X86::R9; break;
2308         }
2309         if (ShadowReg)
2310           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2311       }
2312     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2313       assert(VA.isMemLoc());
2314       if (StackPtr.getNode() == 0)
2315         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2316       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2317                                              dl, DAG, VA, Flags));
2318     }
2319   }
2320
2321   if (!MemOpChains.empty())
2322     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2323                         &MemOpChains[0], MemOpChains.size());
2324
2325   if (Subtarget->isPICStyleGOT()) {
2326     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2327     // GOT pointer.
2328     if (!isTailCall) {
2329       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2330                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2331     } else {
2332       // If we are tail calling and generating PIC/GOT style code load the
2333       // address of the callee into ECX. The value in ecx is used as target of
2334       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2335       // for tail calls on PIC/GOT architectures. Normally we would just put the
2336       // address of GOT into ebx and then call target@PLT. But for tail calls
2337       // ebx would be restored (since ebx is callee saved) before jumping to the
2338       // target@PLT.
2339
2340       // Note: The actual moving to ECX is done further down.
2341       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2342       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2343           !G->getGlobal()->hasProtectedVisibility())
2344         Callee = LowerGlobalAddress(Callee, DAG);
2345       else if (isa<ExternalSymbolSDNode>(Callee))
2346         Callee = LowerExternalSymbol(Callee, DAG);
2347     }
2348   }
2349
2350   if (Is64Bit && isVarArg && !IsWin64) {
2351     // From AMD64 ABI document:
2352     // For calls that may call functions that use varargs or stdargs
2353     // (prototype-less calls or calls to functions containing ellipsis (...) in
2354     // the declaration) %al is used as hidden argument to specify the number
2355     // of SSE registers used. The contents of %al do not need to match exactly
2356     // the number of registers, but must be an ubound on the number of SSE
2357     // registers used and is in the range 0 - 8 inclusive.
2358
2359     // Count the number of XMM registers allocated.
2360     static const uint16_t XMMArgRegs[] = {
2361       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2362       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2363     };
2364     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2365     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2366            && "SSE registers cannot be used when SSE is disabled");
2367
2368     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2369                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2370   }
2371
2372   // For tail calls lower the arguments to the 'real' stack slot.
2373   if (isTailCall) {
2374     // Force all the incoming stack arguments to be loaded from the stack
2375     // before any new outgoing arguments are stored to the stack, because the
2376     // outgoing stack slots may alias the incoming argument stack slots, and
2377     // the alias isn't otherwise explicit. This is slightly more conservative
2378     // than necessary, because it means that each store effectively depends
2379     // on every argument instead of just those arguments it would clobber.
2380     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2381
2382     SmallVector<SDValue, 8> MemOpChains2;
2383     SDValue FIN;
2384     int FI = 0;
2385     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2386       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2387         CCValAssign &VA = ArgLocs[i];
2388         if (VA.isRegLoc())
2389           continue;
2390         assert(VA.isMemLoc());
2391         SDValue Arg = OutVals[i];
2392         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2393         // Create frame index.
2394         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2395         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2396         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2397         FIN = DAG.getFrameIndex(FI, getPointerTy());
2398
2399         if (Flags.isByVal()) {
2400           // Copy relative to framepointer.
2401           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2402           if (StackPtr.getNode() == 0)
2403             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2404                                           getPointerTy());
2405           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2406
2407           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2408                                                            ArgChain,
2409                                                            Flags, DAG, dl));
2410         } else {
2411           // Store relative to framepointer.
2412           MemOpChains2.push_back(
2413             DAG.getStore(ArgChain, dl, Arg, FIN,
2414                          MachinePointerInfo::getFixedStack(FI),
2415                          false, false, 0));
2416         }
2417       }
2418     }
2419
2420     if (!MemOpChains2.empty())
2421       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2422                           &MemOpChains2[0], MemOpChains2.size());
2423
2424     // Store the return address to the appropriate stack slot.
2425     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2426                                      FPDiff, dl);
2427   }
2428
2429   // Build a sequence of copy-to-reg nodes chained together with token chain
2430   // and flag operands which copy the outgoing args into registers.
2431   SDValue InFlag;
2432   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2433     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2434                              RegsToPass[i].second, InFlag);
2435     InFlag = Chain.getValue(1);
2436   }
2437
2438   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2439     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2440     // In the 64-bit large code model, we have to make all calls
2441     // through a register, since the call instruction's 32-bit
2442     // pc-relative offset may not be large enough to hold the whole
2443     // address.
2444   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2445     // If the callee is a GlobalAddress node (quite common, every direct call
2446     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2447     // it.
2448
2449     // We should use extra load for direct calls to dllimported functions in
2450     // non-JIT mode.
2451     const GlobalValue *GV = G->getGlobal();
2452     if (!GV->hasDLLImportLinkage()) {
2453       unsigned char OpFlags = 0;
2454       bool ExtraLoad = false;
2455       unsigned WrapperKind = ISD::DELETED_NODE;
2456
2457       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2458       // external symbols most go through the PLT in PIC mode.  If the symbol
2459       // has hidden or protected visibility, or if it is static or local, then
2460       // we don't need to use the PLT - we can directly call it.
2461       if (Subtarget->isTargetELF() &&
2462           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2463           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2464         OpFlags = X86II::MO_PLT;
2465       } else if (Subtarget->isPICStyleStubAny() &&
2466                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2467                  (!Subtarget->getTargetTriple().isMacOSX() ||
2468                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2469         // PC-relative references to external symbols should go through $stub,
2470         // unless we're building with the leopard linker or later, which
2471         // automatically synthesizes these stubs.
2472         OpFlags = X86II::MO_DARWIN_STUB;
2473       } else if (Subtarget->isPICStyleRIPRel() &&
2474                  isa<Function>(GV) &&
2475                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2476         // If the function is marked as non-lazy, generate an indirect call
2477         // which loads from the GOT directly. This avoids runtime overhead
2478         // at the cost of eager binding (and one extra byte of encoding).
2479         OpFlags = X86II::MO_GOTPCREL;
2480         WrapperKind = X86ISD::WrapperRIP;
2481         ExtraLoad = true;
2482       }
2483
2484       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2485                                           G->getOffset(), OpFlags);
2486
2487       // Add a wrapper if needed.
2488       if (WrapperKind != ISD::DELETED_NODE)
2489         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2490       // Add extra indirection if needed.
2491       if (ExtraLoad)
2492         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2493                              MachinePointerInfo::getGOT(),
2494                              false, false, false, 0);
2495     }
2496   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2497     unsigned char OpFlags = 0;
2498
2499     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2500     // external symbols should go through the PLT.
2501     if (Subtarget->isTargetELF() &&
2502         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2503       OpFlags = X86II::MO_PLT;
2504     } else if (Subtarget->isPICStyleStubAny() &&
2505                (!Subtarget->getTargetTriple().isMacOSX() ||
2506                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2507       // PC-relative references to external symbols should go through $stub,
2508       // unless we're building with the leopard linker or later, which
2509       // automatically synthesizes these stubs.
2510       OpFlags = X86II::MO_DARWIN_STUB;
2511     }
2512
2513     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2514                                          OpFlags);
2515   }
2516
2517   // Returns a chain & a flag for retval copy to use.
2518   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2519   SmallVector<SDValue, 8> Ops;
2520
2521   if (!IsSibcall && isTailCall) {
2522     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2523                            DAG.getIntPtrConstant(0, true), InFlag);
2524     InFlag = Chain.getValue(1);
2525   }
2526
2527   Ops.push_back(Chain);
2528   Ops.push_back(Callee);
2529
2530   if (isTailCall)
2531     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2532
2533   // Add argument registers to the end of the list so that they are known live
2534   // into the call.
2535   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2536     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2537                                   RegsToPass[i].second.getValueType()));
2538
2539   // Add a register mask operand representing the call-preserved registers.
2540   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2541   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2542   assert(Mask && "Missing call preserved mask for calling convention");
2543   Ops.push_back(DAG.getRegisterMask(Mask));
2544
2545   if (InFlag.getNode())
2546     Ops.push_back(InFlag);
2547
2548   if (isTailCall) {
2549     // We used to do:
2550     //// If this is the first return lowered for this function, add the regs
2551     //// to the liveout set for the function.
2552     // This isn't right, although it's probably harmless on x86; liveouts
2553     // should be computed from returns not tail calls.  Consider a void
2554     // function making a tail call to a function returning int.
2555     return DAG.getNode(X86ISD::TC_RETURN, dl,
2556                        NodeTys, &Ops[0], Ops.size());
2557   }
2558
2559   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2560   InFlag = Chain.getValue(1);
2561
2562   // Create the CALLSEQ_END node.
2563   unsigned NumBytesForCalleeToPush;
2564   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2565                        getTargetMachine().Options.GuaranteedTailCallOpt))
2566     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2567   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2568            SR == StackStructReturn)
2569     // If this is a call to a struct-return function, the callee
2570     // pops the hidden struct pointer, so we have to push it back.
2571     // This is common for Darwin/X86, Linux & Mingw32 targets.
2572     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2573     NumBytesForCalleeToPush = 4;
2574   else
2575     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2576
2577   // Returns a flag for retval copy to use.
2578   if (!IsSibcall) {
2579     Chain = DAG.getCALLSEQ_END(Chain,
2580                                DAG.getIntPtrConstant(NumBytes, true),
2581                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2582                                                      true),
2583                                InFlag);
2584     InFlag = Chain.getValue(1);
2585   }
2586
2587   // Handle result values, copying them out of physregs into vregs that we
2588   // return.
2589   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2590                          Ins, dl, DAG, InVals);
2591 }
2592
2593
2594 //===----------------------------------------------------------------------===//
2595 //                Fast Calling Convention (tail call) implementation
2596 //===----------------------------------------------------------------------===//
2597
2598 //  Like std call, callee cleans arguments, convention except that ECX is
2599 //  reserved for storing the tail called function address. Only 2 registers are
2600 //  free for argument passing (inreg). Tail call optimization is performed
2601 //  provided:
2602 //                * tailcallopt is enabled
2603 //                * caller/callee are fastcc
2604 //  On X86_64 architecture with GOT-style position independent code only local
2605 //  (within module) calls are supported at the moment.
2606 //  To keep the stack aligned according to platform abi the function
2607 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2608 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2609 //  If a tail called function callee has more arguments than the caller the
2610 //  caller needs to make sure that there is room to move the RETADDR to. This is
2611 //  achieved by reserving an area the size of the argument delta right after the
2612 //  original REtADDR, but before the saved framepointer or the spilled registers
2613 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2614 //  stack layout:
2615 //    arg1
2616 //    arg2
2617 //    RETADDR
2618 //    [ new RETADDR
2619 //      move area ]
2620 //    (possible EBP)
2621 //    ESI
2622 //    EDI
2623 //    local1 ..
2624
2625 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2626 /// for a 16 byte align requirement.
2627 unsigned
2628 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2629                                                SelectionDAG& DAG) const {
2630   MachineFunction &MF = DAG.getMachineFunction();
2631   const TargetMachine &TM = MF.getTarget();
2632   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2633   unsigned StackAlignment = TFI.getStackAlignment();
2634   uint64_t AlignMask = StackAlignment - 1;
2635   int64_t Offset = StackSize;
2636   uint64_t SlotSize = TD->getPointerSize();
2637   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2638     // Number smaller than 12 so just add the difference.
2639     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2640   } else {
2641     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2642     Offset = ((~AlignMask) & Offset) + StackAlignment +
2643       (StackAlignment-SlotSize);
2644   }
2645   return Offset;
2646 }
2647
2648 /// MatchingStackOffset - Return true if the given stack call argument is
2649 /// already available in the same position (relatively) of the caller's
2650 /// incoming argument stack.
2651 static
2652 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2653                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2654                          const X86InstrInfo *TII) {
2655   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2656   int FI = INT_MAX;
2657   if (Arg.getOpcode() == ISD::CopyFromReg) {
2658     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2659     if (!TargetRegisterInfo::isVirtualRegister(VR))
2660       return false;
2661     MachineInstr *Def = MRI->getVRegDef(VR);
2662     if (!Def)
2663       return false;
2664     if (!Flags.isByVal()) {
2665       if (!TII->isLoadFromStackSlot(Def, FI))
2666         return false;
2667     } else {
2668       unsigned Opcode = Def->getOpcode();
2669       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2670           Def->getOperand(1).isFI()) {
2671         FI = Def->getOperand(1).getIndex();
2672         Bytes = Flags.getByValSize();
2673       } else
2674         return false;
2675     }
2676   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2677     if (Flags.isByVal())
2678       // ByVal argument is passed in as a pointer but it's now being
2679       // dereferenced. e.g.
2680       // define @foo(%struct.X* %A) {
2681       //   tail call @bar(%struct.X* byval %A)
2682       // }
2683       return false;
2684     SDValue Ptr = Ld->getBasePtr();
2685     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2686     if (!FINode)
2687       return false;
2688     FI = FINode->getIndex();
2689   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2690     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2691     FI = FINode->getIndex();
2692     Bytes = Flags.getByValSize();
2693   } else
2694     return false;
2695
2696   assert(FI != INT_MAX);
2697   if (!MFI->isFixedObjectIndex(FI))
2698     return false;
2699   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2700 }
2701
2702 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2703 /// for tail call optimization. Targets which want to do tail call
2704 /// optimization should implement this function.
2705 bool
2706 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2707                                                      CallingConv::ID CalleeCC,
2708                                                      bool isVarArg,
2709                                                      bool isCalleeStructRet,
2710                                                      bool isCallerStructRet,
2711                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2712                                     const SmallVectorImpl<SDValue> &OutVals,
2713                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2714                                                      SelectionDAG& DAG) const {
2715   if (!IsTailCallConvention(CalleeCC) &&
2716       CalleeCC != CallingConv::C)
2717     return false;
2718
2719   // If -tailcallopt is specified, make fastcc functions tail-callable.
2720   const MachineFunction &MF = DAG.getMachineFunction();
2721   const Function *CallerF = DAG.getMachineFunction().getFunction();
2722   CallingConv::ID CallerCC = CallerF->getCallingConv();
2723   bool CCMatch = CallerCC == CalleeCC;
2724
2725   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2726     if (IsTailCallConvention(CalleeCC) && CCMatch)
2727       return true;
2728     return false;
2729   }
2730
2731   // Look for obvious safe cases to perform tail call optimization that do not
2732   // require ABI changes. This is what gcc calls sibcall.
2733
2734   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2735   // emit a special epilogue.
2736   if (RegInfo->needsStackRealignment(MF))
2737     return false;
2738
2739   // Also avoid sibcall optimization if either caller or callee uses struct
2740   // return semantics.
2741   if (isCalleeStructRet || isCallerStructRet)
2742     return false;
2743
2744   // An stdcall caller is expected to clean up its arguments; the callee
2745   // isn't going to do that.
2746   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2747     return false;
2748
2749   // Do not sibcall optimize vararg calls unless all arguments are passed via
2750   // registers.
2751   if (isVarArg && !Outs.empty()) {
2752
2753     // Optimizing for varargs on Win64 is unlikely to be safe without
2754     // additional testing.
2755     if (Subtarget->isTargetWin64())
2756       return false;
2757
2758     SmallVector<CCValAssign, 16> ArgLocs;
2759     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2760                    getTargetMachine(), ArgLocs, *DAG.getContext());
2761
2762     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2763     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2764       if (!ArgLocs[i].isRegLoc())
2765         return false;
2766   }
2767
2768   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2769   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2770   // this into a sibcall.
2771   bool Unused = false;
2772   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2773     if (!Ins[i].Used) {
2774       Unused = true;
2775       break;
2776     }
2777   }
2778   if (Unused) {
2779     SmallVector<CCValAssign, 16> RVLocs;
2780     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2781                    getTargetMachine(), RVLocs, *DAG.getContext());
2782     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2783     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2784       CCValAssign &VA = RVLocs[i];
2785       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2786         return false;
2787     }
2788   }
2789
2790   // If the calling conventions do not match, then we'd better make sure the
2791   // results are returned in the same way as what the caller expects.
2792   if (!CCMatch) {
2793     SmallVector<CCValAssign, 16> RVLocs1;
2794     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2795                     getTargetMachine(), RVLocs1, *DAG.getContext());
2796     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2797
2798     SmallVector<CCValAssign, 16> RVLocs2;
2799     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2800                     getTargetMachine(), RVLocs2, *DAG.getContext());
2801     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2802
2803     if (RVLocs1.size() != RVLocs2.size())
2804       return false;
2805     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2806       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2807         return false;
2808       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2809         return false;
2810       if (RVLocs1[i].isRegLoc()) {
2811         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2812           return false;
2813       } else {
2814         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2815           return false;
2816       }
2817     }
2818   }
2819
2820   // If the callee takes no arguments then go on to check the results of the
2821   // call.
2822   if (!Outs.empty()) {
2823     // Check if stack adjustment is needed. For now, do not do this if any
2824     // argument is passed on the stack.
2825     SmallVector<CCValAssign, 16> ArgLocs;
2826     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2827                    getTargetMachine(), ArgLocs, *DAG.getContext());
2828
2829     // Allocate shadow area for Win64
2830     if (Subtarget->isTargetWin64()) {
2831       CCInfo.AllocateStack(32, 8);
2832     }
2833
2834     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2835     if (CCInfo.getNextStackOffset()) {
2836       MachineFunction &MF = DAG.getMachineFunction();
2837       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2838         return false;
2839
2840       // Check if the arguments are already laid out in the right way as
2841       // the caller's fixed stack objects.
2842       MachineFrameInfo *MFI = MF.getFrameInfo();
2843       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2844       const X86InstrInfo *TII =
2845         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2846       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847         CCValAssign &VA = ArgLocs[i];
2848         SDValue Arg = OutVals[i];
2849         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2850         if (VA.getLocInfo() == CCValAssign::Indirect)
2851           return false;
2852         if (!VA.isRegLoc()) {
2853           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2854                                    MFI, MRI, TII))
2855             return false;
2856         }
2857       }
2858     }
2859
2860     // If the tailcall address may be in a register, then make sure it's
2861     // possible to register allocate for it. In 32-bit, the call address can
2862     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2863     // callee-saved registers are restored. These happen to be the same
2864     // registers used to pass 'inreg' arguments so watch out for those.
2865     if (!Subtarget->is64Bit() &&
2866         !isa<GlobalAddressSDNode>(Callee) &&
2867         !isa<ExternalSymbolSDNode>(Callee)) {
2868       unsigned NumInRegs = 0;
2869       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2870         CCValAssign &VA = ArgLocs[i];
2871         if (!VA.isRegLoc())
2872           continue;
2873         unsigned Reg = VA.getLocReg();
2874         switch (Reg) {
2875         default: break;
2876         case X86::EAX: case X86::EDX: case X86::ECX:
2877           if (++NumInRegs == 3)
2878             return false;
2879           break;
2880         }
2881       }
2882     }
2883   }
2884
2885   return true;
2886 }
2887
2888 FastISel *
2889 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2890   return X86::createFastISel(funcInfo);
2891 }
2892
2893
2894 //===----------------------------------------------------------------------===//
2895 //                           Other Lowering Hooks
2896 //===----------------------------------------------------------------------===//
2897
2898 static bool MayFoldLoad(SDValue Op) {
2899   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2900 }
2901
2902 static bool MayFoldIntoStore(SDValue Op) {
2903   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2904 }
2905
2906 static bool isTargetShuffle(unsigned Opcode) {
2907   switch(Opcode) {
2908   default: return false;
2909   case X86ISD::PSHUFD:
2910   case X86ISD::PSHUFHW:
2911   case X86ISD::PSHUFLW:
2912   case X86ISD::SHUFP:
2913   case X86ISD::PALIGN:
2914   case X86ISD::MOVLHPS:
2915   case X86ISD::MOVLHPD:
2916   case X86ISD::MOVHLPS:
2917   case X86ISD::MOVLPS:
2918   case X86ISD::MOVLPD:
2919   case X86ISD::MOVSHDUP:
2920   case X86ISD::MOVSLDUP:
2921   case X86ISD::MOVDDUP:
2922   case X86ISD::MOVSS:
2923   case X86ISD::MOVSD:
2924   case X86ISD::UNPCKL:
2925   case X86ISD::UNPCKH:
2926   case X86ISD::VPERMILP:
2927   case X86ISD::VPERM2X128:
2928   case X86ISD::VPERMI:
2929     return true;
2930   }
2931 }
2932
2933 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2934                                     SDValue V1, SelectionDAG &DAG) {
2935   switch(Opc) {
2936   default: llvm_unreachable("Unknown x86 shuffle node");
2937   case X86ISD::MOVSHDUP:
2938   case X86ISD::MOVSLDUP:
2939   case X86ISD::MOVDDUP:
2940     return DAG.getNode(Opc, dl, VT, V1);
2941   }
2942 }
2943
2944 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2945                                     SDValue V1, unsigned TargetMask,
2946                                     SelectionDAG &DAG) {
2947   switch(Opc) {
2948   default: llvm_unreachable("Unknown x86 shuffle node");
2949   case X86ISD::PSHUFD:
2950   case X86ISD::PSHUFHW:
2951   case X86ISD::PSHUFLW:
2952   case X86ISD::VPERMILP:
2953   case X86ISD::VPERMI:
2954     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2955   }
2956 }
2957
2958 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2959                                     SDValue V1, SDValue V2, unsigned TargetMask,
2960                                     SelectionDAG &DAG) {
2961   switch(Opc) {
2962   default: llvm_unreachable("Unknown x86 shuffle node");
2963   case X86ISD::PALIGN:
2964   case X86ISD::SHUFP:
2965   case X86ISD::VPERM2X128:
2966     return DAG.getNode(Opc, dl, VT, V1, V2,
2967                        DAG.getConstant(TargetMask, MVT::i8));
2968   }
2969 }
2970
2971 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2972                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2973   switch(Opc) {
2974   default: llvm_unreachable("Unknown x86 shuffle node");
2975   case X86ISD::MOVLHPS:
2976   case X86ISD::MOVLHPD:
2977   case X86ISD::MOVHLPS:
2978   case X86ISD::MOVLPS:
2979   case X86ISD::MOVLPD:
2980   case X86ISD::MOVSS:
2981   case X86ISD::MOVSD:
2982   case X86ISD::UNPCKL:
2983   case X86ISD::UNPCKH:
2984     return DAG.getNode(Opc, dl, VT, V1, V2);
2985   }
2986 }
2987
2988 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2989   MachineFunction &MF = DAG.getMachineFunction();
2990   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2991   int ReturnAddrIndex = FuncInfo->getRAIndex();
2992
2993   if (ReturnAddrIndex == 0) {
2994     // Set up a frame object for the return address.
2995     uint64_t SlotSize = TD->getPointerSize();
2996     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2997                                                            false);
2998     FuncInfo->setRAIndex(ReturnAddrIndex);
2999   }
3000
3001   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3002 }
3003
3004
3005 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3006                                        bool hasSymbolicDisplacement) {
3007   // Offset should fit into 32 bit immediate field.
3008   if (!isInt<32>(Offset))
3009     return false;
3010
3011   // If we don't have a symbolic displacement - we don't have any extra
3012   // restrictions.
3013   if (!hasSymbolicDisplacement)
3014     return true;
3015
3016   // FIXME: Some tweaks might be needed for medium code model.
3017   if (M != CodeModel::Small && M != CodeModel::Kernel)
3018     return false;
3019
3020   // For small code model we assume that latest object is 16MB before end of 31
3021   // bits boundary. We may also accept pretty large negative constants knowing
3022   // that all objects are in the positive half of address space.
3023   if (M == CodeModel::Small && Offset < 16*1024*1024)
3024     return true;
3025
3026   // For kernel code model we know that all object resist in the negative half
3027   // of 32bits address space. We may not accept negative offsets, since they may
3028   // be just off and we may accept pretty large positive ones.
3029   if (M == CodeModel::Kernel && Offset > 0)
3030     return true;
3031
3032   return false;
3033 }
3034
3035 /// isCalleePop - Determines whether the callee is required to pop its
3036 /// own arguments. Callee pop is necessary to support tail calls.
3037 bool X86::isCalleePop(CallingConv::ID CallingConv,
3038                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3039   if (IsVarArg)
3040     return false;
3041
3042   switch (CallingConv) {
3043   default:
3044     return false;
3045   case CallingConv::X86_StdCall:
3046     return !is64Bit;
3047   case CallingConv::X86_FastCall:
3048     return !is64Bit;
3049   case CallingConv::X86_ThisCall:
3050     return !is64Bit;
3051   case CallingConv::Fast:
3052     return TailCallOpt;
3053   case CallingConv::GHC:
3054     return TailCallOpt;
3055   }
3056 }
3057
3058 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3059 /// specific condition code, returning the condition code and the LHS/RHS of the
3060 /// comparison to make.
3061 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3062                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3063   if (!isFP) {
3064     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3065       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3066         // X > -1   -> X == 0, jump !sign.
3067         RHS = DAG.getConstant(0, RHS.getValueType());
3068         return X86::COND_NS;
3069       }
3070       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3071         // X < 0   -> X == 0, jump on sign.
3072         return X86::COND_S;
3073       }
3074       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3075         // X < 1   -> X <= 0
3076         RHS = DAG.getConstant(0, RHS.getValueType());
3077         return X86::COND_LE;
3078       }
3079     }
3080
3081     switch (SetCCOpcode) {
3082     default: llvm_unreachable("Invalid integer condition!");
3083     case ISD::SETEQ:  return X86::COND_E;
3084     case ISD::SETGT:  return X86::COND_G;
3085     case ISD::SETGE:  return X86::COND_GE;
3086     case ISD::SETLT:  return X86::COND_L;
3087     case ISD::SETLE:  return X86::COND_LE;
3088     case ISD::SETNE:  return X86::COND_NE;
3089     case ISD::SETULT: return X86::COND_B;
3090     case ISD::SETUGT: return X86::COND_A;
3091     case ISD::SETULE: return X86::COND_BE;
3092     case ISD::SETUGE: return X86::COND_AE;
3093     }
3094   }
3095
3096   // First determine if it is required or is profitable to flip the operands.
3097
3098   // If LHS is a foldable load, but RHS is not, flip the condition.
3099   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3100       !ISD::isNON_EXTLoad(RHS.getNode())) {
3101     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3102     std::swap(LHS, RHS);
3103   }
3104
3105   switch (SetCCOpcode) {
3106   default: break;
3107   case ISD::SETOLT:
3108   case ISD::SETOLE:
3109   case ISD::SETUGT:
3110   case ISD::SETUGE:
3111     std::swap(LHS, RHS);
3112     break;
3113   }
3114
3115   // On a floating point condition, the flags are set as follows:
3116   // ZF  PF  CF   op
3117   //  0 | 0 | 0 | X > Y
3118   //  0 | 0 | 1 | X < Y
3119   //  1 | 0 | 0 | X == Y
3120   //  1 | 1 | 1 | unordered
3121   switch (SetCCOpcode) {
3122   default: llvm_unreachable("Condcode should be pre-legalized away");
3123   case ISD::SETUEQ:
3124   case ISD::SETEQ:   return X86::COND_E;
3125   case ISD::SETOLT:              // flipped
3126   case ISD::SETOGT:
3127   case ISD::SETGT:   return X86::COND_A;
3128   case ISD::SETOLE:              // flipped
3129   case ISD::SETOGE:
3130   case ISD::SETGE:   return X86::COND_AE;
3131   case ISD::SETUGT:              // flipped
3132   case ISD::SETULT:
3133   case ISD::SETLT:   return X86::COND_B;
3134   case ISD::SETUGE:              // flipped
3135   case ISD::SETULE:
3136   case ISD::SETLE:   return X86::COND_BE;
3137   case ISD::SETONE:
3138   case ISD::SETNE:   return X86::COND_NE;
3139   case ISD::SETUO:   return X86::COND_P;
3140   case ISD::SETO:    return X86::COND_NP;
3141   case ISD::SETOEQ:
3142   case ISD::SETUNE:  return X86::COND_INVALID;
3143   }
3144 }
3145
3146 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3147 /// code. Current x86 isa includes the following FP cmov instructions:
3148 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3149 static bool hasFPCMov(unsigned X86CC) {
3150   switch (X86CC) {
3151   default:
3152     return false;
3153   case X86::COND_B:
3154   case X86::COND_BE:
3155   case X86::COND_E:
3156   case X86::COND_P:
3157   case X86::COND_A:
3158   case X86::COND_AE:
3159   case X86::COND_NE:
3160   case X86::COND_NP:
3161     return true;
3162   }
3163 }
3164
3165 /// isFPImmLegal - Returns true if the target can instruction select the
3166 /// specified FP immediate natively. If false, the legalizer will
3167 /// materialize the FP immediate as a load from a constant pool.
3168 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3169   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3170     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3171       return true;
3172   }
3173   return false;
3174 }
3175
3176 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3177 /// the specified range (L, H].
3178 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3179   return (Val < 0) || (Val >= Low && Val < Hi);
3180 }
3181
3182 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3183 /// specified value.
3184 static bool isUndefOrEqual(int Val, int CmpVal) {
3185   if (Val < 0 || Val == CmpVal)
3186     return true;
3187   return false;
3188 }
3189
3190 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3191 /// from position Pos and ending in Pos+Size, falls within the specified
3192 /// sequential range (L, L+Pos]. or is undef.
3193 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3194                                        unsigned Pos, unsigned Size, int Low) {
3195   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3196     if (!isUndefOrEqual(Mask[i], Low))
3197       return false;
3198   return true;
3199 }
3200
3201 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3202 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3203 /// the second operand.
3204 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3205   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3206     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3207   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3208     return (Mask[0] < 2 && Mask[1] < 2);
3209   return false;
3210 }
3211
3212 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFHW.
3214 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3215   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3216     return false;
3217
3218   // Lower quadword copied in order or undef.
3219   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3220     return false;
3221
3222   // Upper quadword shuffled.
3223   for (unsigned i = 4; i != 8; ++i)
3224     if (!isUndefOrInRange(Mask[i], 4, 8))
3225       return false;
3226
3227   if (VT == MVT::v16i16) {
3228     // Lower quadword copied in order or undef.
3229     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3230       return false;
3231
3232     // Upper quadword shuffled.
3233     for (unsigned i = 12; i != 16; ++i)
3234       if (!isUndefOrInRange(Mask[i], 12, 16))
3235         return false;
3236   }
3237
3238   return true;
3239 }
3240
3241 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3242 /// is suitable for input to PSHUFLW.
3243 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3244   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3245     return false;
3246
3247   // Upper quadword copied in order.
3248   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3249     return false;
3250
3251   // Lower quadword shuffled.
3252   for (unsigned i = 0; i != 4; ++i)
3253     if (!isUndefOrInRange(Mask[i], 0, 4))
3254       return false;
3255
3256   if (VT == MVT::v16i16) {
3257     // Upper quadword copied in order.
3258     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3259       return false;
3260
3261     // Lower quadword shuffled.
3262     for (unsigned i = 8; i != 12; ++i)
3263       if (!isUndefOrInRange(Mask[i], 8, 12))
3264         return false;
3265   }
3266
3267   return true;
3268 }
3269
3270 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3271 /// is suitable for input to PALIGNR.
3272 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3273                           const X86Subtarget *Subtarget) {
3274   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3275       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3276     return false;
3277
3278   unsigned NumElts = VT.getVectorNumElements();
3279   unsigned NumLanes = VT.getSizeInBits()/128;
3280   unsigned NumLaneElts = NumElts/NumLanes;
3281
3282   // Do not handle 64-bit element shuffles with palignr.
3283   if (NumLaneElts == 2)
3284     return false;
3285
3286   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3287     unsigned i;
3288     for (i = 0; i != NumLaneElts; ++i) {
3289       if (Mask[i+l] >= 0)
3290         break;
3291     }
3292
3293     // Lane is all undef, go to next lane
3294     if (i == NumLaneElts)
3295       continue;
3296
3297     int Start = Mask[i+l];
3298
3299     // Make sure its in this lane in one of the sources
3300     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3301         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3302       return false;
3303
3304     // If not lane 0, then we must match lane 0
3305     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3306       return false;
3307
3308     // Correct second source to be contiguous with first source
3309     if (Start >= (int)NumElts)
3310       Start -= NumElts - NumLaneElts;
3311
3312     // Make sure we're shifting in the right direction.
3313     if (Start <= (int)(i+l))
3314       return false;
3315
3316     Start -= i;
3317
3318     // Check the rest of the elements to see if they are consecutive.
3319     for (++i; i != NumLaneElts; ++i) {
3320       int Idx = Mask[i+l];
3321
3322       // Make sure its in this lane
3323       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3324           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3325         return false;
3326
3327       // If not lane 0, then we must match lane 0
3328       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3329         return false;
3330
3331       if (Idx >= (int)NumElts)
3332         Idx -= NumElts - NumLaneElts;
3333
3334       if (!isUndefOrEqual(Idx, Start+i))
3335         return false;
3336
3337     }
3338   }
3339
3340   return true;
3341 }
3342
3343 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3344 /// the two vector operands have swapped position.
3345 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3346                                      unsigned NumElems) {
3347   for (unsigned i = 0; i != NumElems; ++i) {
3348     int idx = Mask[i];
3349     if (idx < 0)
3350       continue;
3351     else if (idx < (int)NumElems)
3352       Mask[i] = idx + NumElems;
3353     else
3354       Mask[i] = idx - NumElems;
3355   }
3356 }
3357
3358 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3359 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3360 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3361 /// reverse of what x86 shuffles want.
3362 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3363                         bool Commuted = false) {
3364   if (!HasAVX && VT.getSizeInBits() == 256)
3365     return false;
3366
3367   unsigned NumElems = VT.getVectorNumElements();
3368   unsigned NumLanes = VT.getSizeInBits()/128;
3369   unsigned NumLaneElems = NumElems/NumLanes;
3370
3371   if (NumLaneElems != 2 && NumLaneElems != 4)
3372     return false;
3373
3374   // VSHUFPSY divides the resulting vector into 4 chunks.
3375   // The sources are also splitted into 4 chunks, and each destination
3376   // chunk must come from a different source chunk.
3377   //
3378   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3379   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3380   //
3381   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3382   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3383   //
3384   // VSHUFPDY divides the resulting vector into 4 chunks.
3385   // The sources are also splitted into 4 chunks, and each destination
3386   // chunk must come from a different source chunk.
3387   //
3388   //  SRC1 =>      X3       X2       X1       X0
3389   //  SRC2 =>      Y3       Y2       Y1       Y0
3390   //
3391   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3392   //
3393   unsigned HalfLaneElems = NumLaneElems/2;
3394   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3395     for (unsigned i = 0; i != NumLaneElems; ++i) {
3396       int Idx = Mask[i+l];
3397       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3398       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3399         return false;
3400       // For VSHUFPSY, the mask of the second half must be the same as the
3401       // first but with the appropriate offsets. This works in the same way as
3402       // VPERMILPS works with masks.
3403       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3404         continue;
3405       if (!isUndefOrEqual(Idx, Mask[i]+l))
3406         return false;
3407     }
3408   }
3409
3410   return true;
3411 }
3412
3413 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3414 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3415 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3416   unsigned NumElems = VT.getVectorNumElements();
3417
3418   if (VT.getSizeInBits() != 128)
3419     return false;
3420
3421   if (NumElems != 4)
3422     return false;
3423
3424   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3425   return isUndefOrEqual(Mask[0], 6) &&
3426          isUndefOrEqual(Mask[1], 7) &&
3427          isUndefOrEqual(Mask[2], 2) &&
3428          isUndefOrEqual(Mask[3], 3);
3429 }
3430
3431 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3432 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3433 /// <2, 3, 2, 3>
3434 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3435   unsigned NumElems = VT.getVectorNumElements();
3436
3437   if (VT.getSizeInBits() != 128)
3438     return false;
3439
3440   if (NumElems != 4)
3441     return false;
3442
3443   return isUndefOrEqual(Mask[0], 2) &&
3444          isUndefOrEqual(Mask[1], 3) &&
3445          isUndefOrEqual(Mask[2], 2) &&
3446          isUndefOrEqual(Mask[3], 3);
3447 }
3448
3449 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3450 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3451 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3452   if (VT.getSizeInBits() != 128)
3453     return false;
3454
3455   unsigned NumElems = VT.getVectorNumElements();
3456
3457   if (NumElems != 2 && NumElems != 4)
3458     return false;
3459
3460   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3461     if (!isUndefOrEqual(Mask[i], i + NumElems))
3462       return false;
3463
3464   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3465     if (!isUndefOrEqual(Mask[i], i))
3466       return false;
3467
3468   return true;
3469 }
3470
3471 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3472 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3473 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3474   unsigned NumElems = VT.getVectorNumElements();
3475
3476   if ((NumElems != 2 && NumElems != 4)
3477       || VT.getSizeInBits() > 128)
3478     return false;
3479
3480   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3481     if (!isUndefOrEqual(Mask[i], i))
3482       return false;
3483
3484   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3485     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3486       return false;
3487
3488   return true;
3489 }
3490
3491 //
3492 // Some special combinations that can be optimized.
3493 //
3494 static
3495 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3496                                SelectionDAG &DAG) {
3497   EVT VT = SVOp->getValueType(0);
3498   DebugLoc dl = SVOp->getDebugLoc();
3499
3500   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3501     return SDValue();
3502
3503   ArrayRef<int> Mask = SVOp->getMask();
3504
3505   // These are the special masks that may be optimized.
3506   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3507   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3508   bool MatchEvenMask = true;
3509   bool MatchOddMask  = true;
3510   for (int i=0; i<8; ++i) {
3511     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3512       MatchEvenMask = false;
3513     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3514       MatchOddMask = false;
3515   }
3516   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3517   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3518
3519   const int *CompactionMask;
3520   if (MatchEvenMask)
3521     CompactionMask = CompactionMaskEven;
3522   else if (MatchOddMask)
3523     CompactionMask = CompactionMaskOdd;
3524   else
3525     return SDValue();
3526
3527   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3528
3529   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3530                                      UndefNode, CompactionMask);
3531   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3532                                      UndefNode, CompactionMask);
3533   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3534   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3535 }
3536
3537 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3538 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3539 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3540                          bool HasAVX2, bool V2IsSplat = false) {
3541   unsigned NumElts = VT.getVectorNumElements();
3542
3543   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3544          "Unsupported vector type for unpckh");
3545
3546   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3547       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3548     return false;
3549
3550   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3551   // independently on 128-bit lanes.
3552   unsigned NumLanes = VT.getSizeInBits()/128;
3553   unsigned NumLaneElts = NumElts/NumLanes;
3554
3555   for (unsigned l = 0; l != NumLanes; ++l) {
3556     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3557          i != (l+1)*NumLaneElts;
3558          i += 2, ++j) {
3559       int BitI  = Mask[i];
3560       int BitI1 = Mask[i+1];
3561       if (!isUndefOrEqual(BitI, j))
3562         return false;
3563       if (V2IsSplat) {
3564         if (!isUndefOrEqual(BitI1, NumElts))
3565           return false;
3566       } else {
3567         if (!isUndefOrEqual(BitI1, j + NumElts))
3568           return false;
3569       }
3570     }
3571   }
3572
3573   return true;
3574 }
3575
3576 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3577 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3578 static bool isUNPCKHMask(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)+NumLaneElts/2;
3596          i != (l+1)*NumLaneElts; i += 2, ++j) {
3597       int BitI  = Mask[i];
3598       int BitI1 = Mask[i+1];
3599       if (!isUndefOrEqual(BitI, j))
3600         return false;
3601       if (V2IsSplat) {
3602         if (isUndefOrEqual(BitI1, NumElts))
3603           return false;
3604       } else {
3605         if (!isUndefOrEqual(BitI1, j+NumElts))
3606           return false;
3607       }
3608     }
3609   }
3610   return true;
3611 }
3612
3613 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3614 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3615 /// <0, 0, 1, 1>
3616 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3617                                   bool HasAVX2) {
3618   unsigned NumElts = VT.getVectorNumElements();
3619
3620   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3621          "Unsupported vector type for unpckh");
3622
3623   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3624       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3625     return false;
3626
3627   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3628   // FIXME: Need a better way to get rid of this, there's no latency difference
3629   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3630   // the former later. We should also remove the "_undef" special mask.
3631   if (NumElts == 4 && VT.getSizeInBits() == 256)
3632     return false;
3633
3634   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3635   // independently on 128-bit lanes.
3636   unsigned NumLanes = VT.getSizeInBits()/128;
3637   unsigned NumLaneElts = NumElts/NumLanes;
3638
3639   for (unsigned l = 0; l != NumLanes; ++l) {
3640     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3641          i != (l+1)*NumLaneElts;
3642          i += 2, ++j) {
3643       int BitI  = Mask[i];
3644       int BitI1 = Mask[i+1];
3645
3646       if (!isUndefOrEqual(BitI, j))
3647         return false;
3648       if (!isUndefOrEqual(BitI1, j))
3649         return false;
3650     }
3651   }
3652
3653   return true;
3654 }
3655
3656 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3657 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3658 /// <2, 2, 3, 3>
3659 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3660   unsigned NumElts = VT.getVectorNumElements();
3661
3662   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3663          "Unsupported vector type for unpckh");
3664
3665   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3666       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3667     return false;
3668
3669   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3670   // independently on 128-bit lanes.
3671   unsigned NumLanes = VT.getSizeInBits()/128;
3672   unsigned NumLaneElts = NumElts/NumLanes;
3673
3674   for (unsigned l = 0; l != NumLanes; ++l) {
3675     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3676          i != (l+1)*NumLaneElts; i += 2, ++j) {
3677       int BitI  = Mask[i];
3678       int BitI1 = Mask[i+1];
3679       if (!isUndefOrEqual(BitI, j))
3680         return false;
3681       if (!isUndefOrEqual(BitI1, j))
3682         return false;
3683     }
3684   }
3685   return true;
3686 }
3687
3688 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3689 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3690 /// MOVSD, and MOVD, i.e. setting the lowest element.
3691 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3692   if (VT.getVectorElementType().getSizeInBits() < 32)
3693     return false;
3694   if (VT.getSizeInBits() == 256)
3695     return false;
3696
3697   unsigned NumElts = VT.getVectorNumElements();
3698
3699   if (!isUndefOrEqual(Mask[0], NumElts))
3700     return false;
3701
3702   for (unsigned i = 1; i != NumElts; ++i)
3703     if (!isUndefOrEqual(Mask[i], i))
3704       return false;
3705
3706   return true;
3707 }
3708
3709 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3710 /// as permutations between 128-bit chunks or halves. As an example: this
3711 /// shuffle bellow:
3712 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3713 /// The first half comes from the second half of V1 and the second half from the
3714 /// the second half of V2.
3715 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3716   if (!HasAVX || VT.getSizeInBits() != 256)
3717     return false;
3718
3719   // The shuffle result is divided into half A and half B. In total the two
3720   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3721   // B must come from C, D, E or F.
3722   unsigned HalfSize = VT.getVectorNumElements()/2;
3723   bool MatchA = false, MatchB = false;
3724
3725   // Check if A comes from one of C, D, E, F.
3726   for (unsigned Half = 0; Half != 4; ++Half) {
3727     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3728       MatchA = true;
3729       break;
3730     }
3731   }
3732
3733   // Check if B comes from one of C, D, E, F.
3734   for (unsigned Half = 0; Half != 4; ++Half) {
3735     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3736       MatchB = true;
3737       break;
3738     }
3739   }
3740
3741   return MatchA && MatchB;
3742 }
3743
3744 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3745 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3746 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3747   EVT VT = SVOp->getValueType(0);
3748
3749   unsigned HalfSize = VT.getVectorNumElements()/2;
3750
3751   unsigned FstHalf = 0, SndHalf = 0;
3752   for (unsigned i = 0; i < HalfSize; ++i) {
3753     if (SVOp->getMaskElt(i) > 0) {
3754       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3755       break;
3756     }
3757   }
3758   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3759     if (SVOp->getMaskElt(i) > 0) {
3760       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3761       break;
3762     }
3763   }
3764
3765   return (FstHalf | (SndHalf << 4));
3766 }
3767
3768 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3769 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3770 /// Note that VPERMIL mask matching is different depending whether theunderlying
3771 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3772 /// to the same elements of the low, but to the higher half of the source.
3773 /// In VPERMILPD the two lanes could be shuffled independently of each other
3774 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3775 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3776   if (!HasAVX)
3777     return false;
3778
3779   unsigned NumElts = VT.getVectorNumElements();
3780   // Only match 256-bit with 32/64-bit types
3781   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3782     return false;
3783
3784   unsigned NumLanes = VT.getSizeInBits()/128;
3785   unsigned LaneSize = NumElts/NumLanes;
3786   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3787     for (unsigned i = 0; i != LaneSize; ++i) {
3788       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3789         return false;
3790       if (NumElts != 8 || l == 0)
3791         continue;
3792       // VPERMILPS handling
3793       if (Mask[i] < 0)
3794         continue;
3795       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3796         return false;
3797     }
3798   }
3799
3800   return true;
3801 }
3802
3803 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3804 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3805 /// element of vector 2 and the other elements to come from vector 1 in order.
3806 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3807                                bool V2IsSplat = false, bool V2IsUndef = false) {
3808   unsigned NumOps = VT.getVectorNumElements();
3809   if (VT.getSizeInBits() == 256)
3810     return false;
3811   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3812     return false;
3813
3814   if (!isUndefOrEqual(Mask[0], 0))
3815     return false;
3816
3817   for (unsigned i = 1; i != NumOps; ++i)
3818     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3819           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3820           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3821       return false;
3822
3823   return true;
3824 }
3825
3826 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3827 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3828 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3829 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3830                            const X86Subtarget *Subtarget) {
3831   if (!Subtarget->hasSSE3())
3832     return false;
3833
3834   unsigned NumElems = VT.getVectorNumElements();
3835
3836   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3837       (VT.getSizeInBits() == 256 && NumElems != 8))
3838     return false;
3839
3840   // "i+1" is the value the indexed mask element must have
3841   for (unsigned i = 0; i != NumElems; i += 2)
3842     if (!isUndefOrEqual(Mask[i], i+1) ||
3843         !isUndefOrEqual(Mask[i+1], i+1))
3844       return false;
3845
3846   return true;
3847 }
3848
3849 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3850 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3851 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3852 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3853                            const X86Subtarget *Subtarget) {
3854   if (!Subtarget->hasSSE3())
3855     return false;
3856
3857   unsigned NumElems = VT.getVectorNumElements();
3858
3859   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3860       (VT.getSizeInBits() == 256 && NumElems != 8))
3861     return false;
3862
3863   // "i" is the value the indexed mask element must have
3864   for (unsigned i = 0; i != NumElems; i += 2)
3865     if (!isUndefOrEqual(Mask[i], i) ||
3866         !isUndefOrEqual(Mask[i+1], i))
3867       return false;
3868
3869   return true;
3870 }
3871
3872 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3873 /// specifies a shuffle of elements that is suitable for input to 256-bit
3874 /// version of MOVDDUP.
3875 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3876   unsigned NumElts = VT.getVectorNumElements();
3877
3878   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3879     return false;
3880
3881   for (unsigned i = 0; i != NumElts/2; ++i)
3882     if (!isUndefOrEqual(Mask[i], 0))
3883       return false;
3884   for (unsigned i = NumElts/2; i != NumElts; ++i)
3885     if (!isUndefOrEqual(Mask[i], NumElts/2))
3886       return false;
3887   return true;
3888 }
3889
3890 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3891 /// specifies a shuffle of elements that is suitable for input to 128-bit
3892 /// version of MOVDDUP.
3893 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3894   if (VT.getSizeInBits() != 128)
3895     return false;
3896
3897   unsigned e = VT.getVectorNumElements() / 2;
3898   for (unsigned i = 0; i != e; ++i)
3899     if (!isUndefOrEqual(Mask[i], i))
3900       return false;
3901   for (unsigned i = 0; i != e; ++i)
3902     if (!isUndefOrEqual(Mask[e+i], i))
3903       return false;
3904   return true;
3905 }
3906
3907 /// isVEXTRACTF128Index - Return true if the specified
3908 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3909 /// suitable for input to VEXTRACTF128.
3910 bool X86::isVEXTRACTF128Index(SDNode *N) {
3911   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3912     return false;
3913
3914   // The index should be aligned on a 128-bit boundary.
3915   uint64_t Index =
3916     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3917
3918   unsigned VL = N->getValueType(0).getVectorNumElements();
3919   unsigned VBits = N->getValueType(0).getSizeInBits();
3920   unsigned ElSize = VBits / VL;
3921   bool Result = (Index * ElSize) % 128 == 0;
3922
3923   return Result;
3924 }
3925
3926 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3927 /// operand specifies a subvector insert that is suitable for input to
3928 /// VINSERTF128.
3929 bool X86::isVINSERTF128Index(SDNode *N) {
3930   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3931     return false;
3932
3933   // The index should be aligned on a 128-bit boundary.
3934   uint64_t Index =
3935     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3936
3937   unsigned VL = N->getValueType(0).getVectorNumElements();
3938   unsigned VBits = N->getValueType(0).getSizeInBits();
3939   unsigned ElSize = VBits / VL;
3940   bool Result = (Index * ElSize) % 128 == 0;
3941
3942   return Result;
3943 }
3944
3945 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3946 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3947 /// Handles 128-bit and 256-bit.
3948 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3949   EVT VT = N->getValueType(0);
3950
3951   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3952          "Unsupported vector type for PSHUF/SHUFP");
3953
3954   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3955   // independently on 128-bit lanes.
3956   unsigned NumElts = VT.getVectorNumElements();
3957   unsigned NumLanes = VT.getSizeInBits()/128;
3958   unsigned NumLaneElts = NumElts/NumLanes;
3959
3960   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3961          "Only supports 2 or 4 elements per lane");
3962
3963   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3964   unsigned Mask = 0;
3965   for (unsigned i = 0; i != NumElts; ++i) {
3966     int Elt = N->getMaskElt(i);
3967     if (Elt < 0) continue;
3968     Elt &= NumLaneElts - 1;
3969     unsigned ShAmt = (i << Shift) % 8;
3970     Mask |= Elt << ShAmt;
3971   }
3972
3973   return Mask;
3974 }
3975
3976 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3977 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3978 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3979   EVT VT = N->getValueType(0);
3980
3981   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3982          "Unsupported vector type for PSHUFHW");
3983
3984   unsigned NumElts = VT.getVectorNumElements();
3985
3986   unsigned Mask = 0;
3987   for (unsigned l = 0; l != NumElts; l += 8) {
3988     // 8 nodes per lane, but we only care about the last 4.
3989     for (unsigned i = 0; i < 4; ++i) {
3990       int Elt = N->getMaskElt(l+i+4);
3991       if (Elt < 0) continue;
3992       Elt &= 0x3; // only 2-bits.
3993       Mask |= Elt << (i * 2);
3994     }
3995   }
3996
3997   return Mask;
3998 }
3999
4000 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4001 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4002 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4003   EVT VT = N->getValueType(0);
4004
4005   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4006          "Unsupported vector type for PSHUFHW");
4007
4008   unsigned NumElts = VT.getVectorNumElements();
4009
4010   unsigned Mask = 0;
4011   for (unsigned l = 0; l != NumElts; l += 8) {
4012     // 8 nodes per lane, but we only care about the first 4.
4013     for (unsigned i = 0; i < 4; ++i) {
4014       int Elt = N->getMaskElt(l+i);
4015       if (Elt < 0) continue;
4016       Elt &= 0x3; // only 2-bits
4017       Mask |= Elt << (i * 2);
4018     }
4019   }
4020
4021   return Mask;
4022 }
4023
4024 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4025 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4026 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4027   EVT VT = SVOp->getValueType(0);
4028   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4029
4030   unsigned NumElts = VT.getVectorNumElements();
4031   unsigned NumLanes = VT.getSizeInBits()/128;
4032   unsigned NumLaneElts = NumElts/NumLanes;
4033
4034   int Val = 0;
4035   unsigned i;
4036   for (i = 0; i != NumElts; ++i) {
4037     Val = SVOp->getMaskElt(i);
4038     if (Val >= 0)
4039       break;
4040   }
4041   if (Val >= (int)NumElts)
4042     Val -= NumElts - NumLaneElts;
4043
4044   assert(Val - i > 0 && "PALIGNR imm should be positive");
4045   return (Val - i) * EltSize;
4046 }
4047
4048 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4049 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4050 /// instructions.
4051 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4052   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4053     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4054
4055   uint64_t Index =
4056     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4057
4058   EVT VecVT = N->getOperand(0).getValueType();
4059   EVT ElVT = VecVT.getVectorElementType();
4060
4061   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4062   return Index / NumElemsPerChunk;
4063 }
4064
4065 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4066 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4067 /// instructions.
4068 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4069   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4070     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4071
4072   uint64_t Index =
4073     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4074
4075   EVT VecVT = N->getValueType(0);
4076   EVT ElVT = VecVT.getVectorElementType();
4077
4078   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4079   return Index / NumElemsPerChunk;
4080 }
4081
4082 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4083 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4084 /// Handles 256-bit.
4085 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4086   EVT VT = N->getValueType(0);
4087
4088   unsigned NumElts = VT.getVectorNumElements();
4089
4090   assert((VT.is256BitVector() && NumElts == 4) &&
4091          "Unsupported vector type for VPERMQ/VPERMPD");
4092
4093   unsigned Mask = 0;
4094   for (unsigned i = 0; i != NumElts; ++i) {
4095     int Elt = N->getMaskElt(i);
4096     if (Elt < 0)
4097       continue;
4098     Mask |= Elt << (i*2);
4099   }
4100
4101   return Mask;
4102 }
4103 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4104 /// constant +0.0.
4105 bool X86::isZeroNode(SDValue Elt) {
4106   return ((isa<ConstantSDNode>(Elt) &&
4107            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4108           (isa<ConstantFPSDNode>(Elt) &&
4109            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4110 }
4111
4112 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4113 /// their permute mask.
4114 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4115                                     SelectionDAG &DAG) {
4116   EVT VT = SVOp->getValueType(0);
4117   unsigned NumElems = VT.getVectorNumElements();
4118   SmallVector<int, 8> MaskVec;
4119
4120   for (unsigned i = 0; i != NumElems; ++i) {
4121     int Idx = SVOp->getMaskElt(i);
4122     if (Idx >= 0) {
4123       if (Idx < (int)NumElems)
4124         Idx += NumElems;
4125       else
4126         Idx -= NumElems;
4127     }
4128     MaskVec.push_back(Idx);
4129   }
4130   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4131                               SVOp->getOperand(0), &MaskVec[0]);
4132 }
4133
4134 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4135 /// match movhlps. The lower half elements should come from upper half of
4136 /// V1 (and in order), and the upper half elements should come from the upper
4137 /// half of V2 (and in order).
4138 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4139   if (VT.getSizeInBits() != 128)
4140     return false;
4141   if (VT.getVectorNumElements() != 4)
4142     return false;
4143   for (unsigned i = 0, e = 2; i != e; ++i)
4144     if (!isUndefOrEqual(Mask[i], i+2))
4145       return false;
4146   for (unsigned i = 2; i != 4; ++i)
4147     if (!isUndefOrEqual(Mask[i], i+4))
4148       return false;
4149   return true;
4150 }
4151
4152 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4153 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4154 /// required.
4155 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4156   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4157     return false;
4158   N = N->getOperand(0).getNode();
4159   if (!ISD::isNON_EXTLoad(N))
4160     return false;
4161   if (LD)
4162     *LD = cast<LoadSDNode>(N);
4163   return true;
4164 }
4165
4166 // Test whether the given value is a vector value which will be legalized
4167 // into a load.
4168 static bool WillBeConstantPoolLoad(SDNode *N) {
4169   if (N->getOpcode() != ISD::BUILD_VECTOR)
4170     return false;
4171
4172   // Check for any non-constant elements.
4173   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4174     switch (N->getOperand(i).getNode()->getOpcode()) {
4175     case ISD::UNDEF:
4176     case ISD::ConstantFP:
4177     case ISD::Constant:
4178       break;
4179     default:
4180       return false;
4181     }
4182
4183   // Vectors of all-zeros and all-ones are materialized with special
4184   // instructions rather than being loaded.
4185   return !ISD::isBuildVectorAllZeros(N) &&
4186          !ISD::isBuildVectorAllOnes(N);
4187 }
4188
4189 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4190 /// match movlp{s|d}. The lower half elements should come from lower half of
4191 /// V1 (and in order), and the upper half elements should come from the upper
4192 /// half of V2 (and in order). And since V1 will become the source of the
4193 /// MOVLP, it must be either a vector load or a scalar load to vector.
4194 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4195                                ArrayRef<int> Mask, EVT VT) {
4196   if (VT.getSizeInBits() != 128)
4197     return false;
4198
4199   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4200     return false;
4201   // Is V2 is a vector load, don't do this transformation. We will try to use
4202   // load folding shufps op.
4203   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4204     return false;
4205
4206   unsigned NumElems = VT.getVectorNumElements();
4207
4208   if (NumElems != 2 && NumElems != 4)
4209     return false;
4210   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4211     if (!isUndefOrEqual(Mask[i], i))
4212       return false;
4213   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4214     if (!isUndefOrEqual(Mask[i], i+NumElems))
4215       return false;
4216   return true;
4217 }
4218
4219 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4220 /// all the same.
4221 static bool isSplatVector(SDNode *N) {
4222   if (N->getOpcode() != ISD::BUILD_VECTOR)
4223     return false;
4224
4225   SDValue SplatValue = N->getOperand(0);
4226   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4227     if (N->getOperand(i) != SplatValue)
4228       return false;
4229   return true;
4230 }
4231
4232 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4233 /// to an zero vector.
4234 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4235 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4236   SDValue V1 = N->getOperand(0);
4237   SDValue V2 = N->getOperand(1);
4238   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4239   for (unsigned i = 0; i != NumElems; ++i) {
4240     int Idx = N->getMaskElt(i);
4241     if (Idx >= (int)NumElems) {
4242       unsigned Opc = V2.getOpcode();
4243       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4244         continue;
4245       if (Opc != ISD::BUILD_VECTOR ||
4246           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4247         return false;
4248     } else if (Idx >= 0) {
4249       unsigned Opc = V1.getOpcode();
4250       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4251         continue;
4252       if (Opc != ISD::BUILD_VECTOR ||
4253           !X86::isZeroNode(V1.getOperand(Idx)))
4254         return false;
4255     }
4256   }
4257   return true;
4258 }
4259
4260 /// getZeroVector - Returns a vector of specified type with all zero elements.
4261 ///
4262 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4263                              SelectionDAG &DAG, DebugLoc dl) {
4264   assert(VT.isVector() && "Expected a vector type");
4265   unsigned Size = VT.getSizeInBits();
4266
4267   // Always build SSE zero vectors as <4 x i32> bitcasted
4268   // to their dest type. This ensures they get CSE'd.
4269   SDValue Vec;
4270   if (Size == 128) {  // SSE
4271     if (Subtarget->hasSSE2()) {  // SSE2
4272       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4273       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4274     } else { // SSE1
4275       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4276       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4277     }
4278   } else if (Size == 256) { // AVX
4279     if (Subtarget->hasAVX2()) { // AVX2
4280       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4281       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4282       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4283     } else {
4284       // 256-bit logic and arithmetic instructions in AVX are all
4285       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4286       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4287       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4288       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4289     }
4290   } else
4291     llvm_unreachable("Unexpected vector type");
4292
4293   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4294 }
4295
4296 /// getOnesVector - Returns a vector of specified type with all bits set.
4297 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4298 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4299 /// Then bitcast to their original type, ensuring they get CSE'd.
4300 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4301                              DebugLoc dl) {
4302   assert(VT.isVector() && "Expected a vector type");
4303   unsigned Size = VT.getSizeInBits();
4304
4305   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4306   SDValue Vec;
4307   if (Size == 256) {
4308     if (HasAVX2) { // AVX2
4309       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4310       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4311     } else { // AVX
4312       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4313       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4314     }
4315   } else if (Size == 128) {
4316     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4317   } else
4318     llvm_unreachable("Unexpected vector type");
4319
4320   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4321 }
4322
4323 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4324 /// that point to V2 points to its first element.
4325 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4326   for (unsigned i = 0; i != NumElems; ++i) {
4327     if (Mask[i] > (int)NumElems) {
4328       Mask[i] = NumElems;
4329     }
4330   }
4331 }
4332
4333 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4334 /// operation of specified width.
4335 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4336                        SDValue V2) {
4337   unsigned NumElems = VT.getVectorNumElements();
4338   SmallVector<int, 8> Mask;
4339   Mask.push_back(NumElems);
4340   for (unsigned i = 1; i != NumElems; ++i)
4341     Mask.push_back(i);
4342   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4343 }
4344
4345 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4346 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4347                           SDValue V2) {
4348   unsigned NumElems = VT.getVectorNumElements();
4349   SmallVector<int, 8> Mask;
4350   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4351     Mask.push_back(i);
4352     Mask.push_back(i + NumElems);
4353   }
4354   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4355 }
4356
4357 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4358 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4359                           SDValue V2) {
4360   unsigned NumElems = VT.getVectorNumElements();
4361   SmallVector<int, 8> Mask;
4362   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4363     Mask.push_back(i + Half);
4364     Mask.push_back(i + NumElems + Half);
4365   }
4366   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4367 }
4368
4369 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4370 // a generic shuffle instruction because the target has no such instructions.
4371 // Generate shuffles which repeat i16 and i8 several times until they can be
4372 // represented by v4f32 and then be manipulated by target suported shuffles.
4373 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4374   EVT VT = V.getValueType();
4375   int NumElems = VT.getVectorNumElements();
4376   DebugLoc dl = V.getDebugLoc();
4377
4378   while (NumElems > 4) {
4379     if (EltNo < NumElems/2) {
4380       V = getUnpackl(DAG, dl, VT, V, V);
4381     } else {
4382       V = getUnpackh(DAG, dl, VT, V, V);
4383       EltNo -= NumElems/2;
4384     }
4385     NumElems >>= 1;
4386   }
4387   return V;
4388 }
4389
4390 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4391 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4392   EVT VT = V.getValueType();
4393   DebugLoc dl = V.getDebugLoc();
4394   unsigned Size = VT.getSizeInBits();
4395
4396   if (Size == 128) {
4397     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4398     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4399     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4400                              &SplatMask[0]);
4401   } else if (Size == 256) {
4402     // To use VPERMILPS to splat scalars, the second half of indicies must
4403     // refer to the higher part, which is a duplication of the lower one,
4404     // because VPERMILPS can only handle in-lane permutations.
4405     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4406                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4407
4408     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4409     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4410                              &SplatMask[0]);
4411   } else
4412     llvm_unreachable("Vector size not supported");
4413
4414   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4415 }
4416
4417 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4418 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4419   EVT SrcVT = SV->getValueType(0);
4420   SDValue V1 = SV->getOperand(0);
4421   DebugLoc dl = SV->getDebugLoc();
4422
4423   int EltNo = SV->getSplatIndex();
4424   int NumElems = SrcVT.getVectorNumElements();
4425   unsigned Size = SrcVT.getSizeInBits();
4426
4427   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4428           "Unknown how to promote splat for type");
4429
4430   // Extract the 128-bit part containing the splat element and update
4431   // the splat element index when it refers to the higher register.
4432   if (Size == 256) {
4433     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4434     if (EltNo >= NumElems/2)
4435       EltNo -= NumElems/2;
4436   }
4437
4438   // All i16 and i8 vector types can't be used directly by a generic shuffle
4439   // instruction because the target has no such instruction. Generate shuffles
4440   // which repeat i16 and i8 several times until they fit in i32, and then can
4441   // be manipulated by target suported shuffles.
4442   EVT EltVT = SrcVT.getVectorElementType();
4443   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4444     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4445
4446   // Recreate the 256-bit vector and place the same 128-bit vector
4447   // into the low and high part. This is necessary because we want
4448   // to use VPERM* to shuffle the vectors
4449   if (Size == 256) {
4450     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4451   }
4452
4453   return getLegalSplat(DAG, V1, EltNo);
4454 }
4455
4456 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4457 /// vector of zero or undef vector.  This produces a shuffle where the low
4458 /// element of V2 is swizzled into the zero/undef vector, landing at element
4459 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4460 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4461                                            bool IsZero,
4462                                            const X86Subtarget *Subtarget,
4463                                            SelectionDAG &DAG) {
4464   EVT VT = V2.getValueType();
4465   SDValue V1 = IsZero
4466     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4467   unsigned NumElems = VT.getVectorNumElements();
4468   SmallVector<int, 16> MaskVec;
4469   for (unsigned i = 0; i != NumElems; ++i)
4470     // If this is the insertion idx, put the low elt of V2 here.
4471     MaskVec.push_back(i == Idx ? NumElems : i);
4472   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4473 }
4474
4475 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4476 /// target specific opcode. Returns true if the Mask could be calculated.
4477 /// Sets IsUnary to true if only uses one source.
4478 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4479                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4480   unsigned NumElems = VT.getVectorNumElements();
4481   SDValue ImmN;
4482
4483   IsUnary = false;
4484   switch(N->getOpcode()) {
4485   case X86ISD::SHUFP:
4486     ImmN = N->getOperand(N->getNumOperands()-1);
4487     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4488     break;
4489   case X86ISD::UNPCKH:
4490     DecodeUNPCKHMask(VT, Mask);
4491     break;
4492   case X86ISD::UNPCKL:
4493     DecodeUNPCKLMask(VT, Mask);
4494     break;
4495   case X86ISD::MOVHLPS:
4496     DecodeMOVHLPSMask(NumElems, Mask);
4497     break;
4498   case X86ISD::MOVLHPS:
4499     DecodeMOVLHPSMask(NumElems, Mask);
4500     break;
4501   case X86ISD::PSHUFD:
4502   case X86ISD::VPERMILP:
4503     ImmN = N->getOperand(N->getNumOperands()-1);
4504     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505     IsUnary = true;
4506     break;
4507   case X86ISD::PSHUFHW:
4508     ImmN = N->getOperand(N->getNumOperands()-1);
4509     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4510     IsUnary = true;
4511     break;
4512   case X86ISD::PSHUFLW:
4513     ImmN = N->getOperand(N->getNumOperands()-1);
4514     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4515     IsUnary = true;
4516     break;
4517   case X86ISD::VPERMI:
4518     ImmN = N->getOperand(N->getNumOperands()-1);
4519     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4520     IsUnary = true;
4521     break;
4522   case X86ISD::MOVSS:
4523   case X86ISD::MOVSD: {
4524     // The index 0 always comes from the first element of the second source,
4525     // this is why MOVSS and MOVSD are used in the first place. The other
4526     // elements come from the other positions of the first source vector
4527     Mask.push_back(NumElems);
4528     for (unsigned i = 1; i != NumElems; ++i) {
4529       Mask.push_back(i);
4530     }
4531     break;
4532   }
4533   case X86ISD::VPERM2X128:
4534     ImmN = N->getOperand(N->getNumOperands()-1);
4535     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4536     if (Mask.empty()) return false;
4537     break;
4538   case X86ISD::MOVDDUP:
4539   case X86ISD::MOVLHPD:
4540   case X86ISD::MOVLPD:
4541   case X86ISD::MOVLPS:
4542   case X86ISD::MOVSHDUP:
4543   case X86ISD::MOVSLDUP:
4544   case X86ISD::PALIGN:
4545     // Not yet implemented
4546     return false;
4547   default: llvm_unreachable("unknown target shuffle node");
4548   }
4549
4550   return true;
4551 }
4552
4553 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4554 /// element of the result of the vector shuffle.
4555 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4556                                    unsigned Depth) {
4557   if (Depth == 6)
4558     return SDValue();  // Limit search depth.
4559
4560   SDValue V = SDValue(N, 0);
4561   EVT VT = V.getValueType();
4562   unsigned Opcode = V.getOpcode();
4563
4564   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4565   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4566     int Elt = SV->getMaskElt(Index);
4567
4568     if (Elt < 0)
4569       return DAG.getUNDEF(VT.getVectorElementType());
4570
4571     unsigned NumElems = VT.getVectorNumElements();
4572     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4573                                          : SV->getOperand(1);
4574     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4575   }
4576
4577   // Recurse into target specific vector shuffles to find scalars.
4578   if (isTargetShuffle(Opcode)) {
4579     MVT ShufVT = V.getValueType().getSimpleVT();
4580     unsigned NumElems = ShufVT.getVectorNumElements();
4581     SmallVector<int, 16> ShuffleMask;
4582     SDValue ImmN;
4583     bool IsUnary;
4584
4585     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4586       return SDValue();
4587
4588     int Elt = ShuffleMask[Index];
4589     if (Elt < 0)
4590       return DAG.getUNDEF(ShufVT.getVectorElementType());
4591
4592     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4593                                          : N->getOperand(1);
4594     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4595                                Depth+1);
4596   }
4597
4598   // Actual nodes that may contain scalar elements
4599   if (Opcode == ISD::BITCAST) {
4600     V = V.getOperand(0);
4601     EVT SrcVT = V.getValueType();
4602     unsigned NumElems = VT.getVectorNumElements();
4603
4604     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4605       return SDValue();
4606   }
4607
4608   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4609     return (Index == 0) ? V.getOperand(0)
4610                         : DAG.getUNDEF(VT.getVectorElementType());
4611
4612   if (V.getOpcode() == ISD::BUILD_VECTOR)
4613     return V.getOperand(Index);
4614
4615   return SDValue();
4616 }
4617
4618 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4619 /// shuffle operation which come from a consecutively from a zero. The
4620 /// search can start in two different directions, from left or right.
4621 static
4622 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4623                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4624   unsigned i;
4625   for (i = 0; i != NumElems; ++i) {
4626     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4627     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4628     if (!(Elt.getNode() &&
4629          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4630       break;
4631   }
4632
4633   return i;
4634 }
4635
4636 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4637 /// correspond consecutively to elements from one of the vector operands,
4638 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4639 static
4640 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4641                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4642                               unsigned NumElems, unsigned &OpNum) {
4643   bool SeenV1 = false;
4644   bool SeenV2 = false;
4645
4646   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4647     int Idx = SVOp->getMaskElt(i);
4648     // Ignore undef indicies
4649     if (Idx < 0)
4650       continue;
4651
4652     if (Idx < (int)NumElems)
4653       SeenV1 = true;
4654     else
4655       SeenV2 = true;
4656
4657     // Only accept consecutive elements from the same vector
4658     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4659       return false;
4660   }
4661
4662   OpNum = SeenV1 ? 0 : 1;
4663   return true;
4664 }
4665
4666 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4667 /// logical left shift of a vector.
4668 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4669                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4670   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4671   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4672               false /* check zeros from right */, DAG);
4673   unsigned OpSrc;
4674
4675   if (!NumZeros)
4676     return false;
4677
4678   // Considering the elements in the mask that are not consecutive zeros,
4679   // check if they consecutively come from only one of the source vectors.
4680   //
4681   //               V1 = {X, A, B, C}     0
4682   //                         \  \  \    /
4683   //   vector_shuffle V1, V2 <1, 2, 3, X>
4684   //
4685   if (!isShuffleMaskConsecutive(SVOp,
4686             0,                   // Mask Start Index
4687             NumElems-NumZeros,   // Mask End Index(exclusive)
4688             NumZeros,            // Where to start looking in the src vector
4689             NumElems,            // Number of elements in vector
4690             OpSrc))              // Which source operand ?
4691     return false;
4692
4693   isLeft = false;
4694   ShAmt = NumZeros;
4695   ShVal = SVOp->getOperand(OpSrc);
4696   return true;
4697 }
4698
4699 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4700 /// logical left shift of a vector.
4701 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4702                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4703   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4704   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4705               true /* check zeros from left */, DAG);
4706   unsigned OpSrc;
4707
4708   if (!NumZeros)
4709     return false;
4710
4711   // Considering the elements in the mask that are not consecutive zeros,
4712   // check if they consecutively come from only one of the source vectors.
4713   //
4714   //                           0    { A, B, X, X } = V2
4715   //                          / \    /  /
4716   //   vector_shuffle V1, V2 <X, X, 4, 5>
4717   //
4718   if (!isShuffleMaskConsecutive(SVOp,
4719             NumZeros,     // Mask Start Index
4720             NumElems,     // Mask End Index(exclusive)
4721             0,            // Where to start looking in the src vector
4722             NumElems,     // Number of elements in vector
4723             OpSrc))       // Which source operand ?
4724     return false;
4725
4726   isLeft = true;
4727   ShAmt = NumZeros;
4728   ShVal = SVOp->getOperand(OpSrc);
4729   return true;
4730 }
4731
4732 /// isVectorShift - Returns true if the shuffle can be implemented as a
4733 /// logical left or right shift of a vector.
4734 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4735                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4736   // Although the logic below support any bitwidth size, there are no
4737   // shift instructions which handle more than 128-bit vectors.
4738   if (SVOp->getValueType(0).getSizeInBits() > 128)
4739     return false;
4740
4741   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4742       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4743     return true;
4744
4745   return false;
4746 }
4747
4748 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4749 ///
4750 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4751                                        unsigned NumNonZero, unsigned NumZero,
4752                                        SelectionDAG &DAG,
4753                                        const X86Subtarget* Subtarget,
4754                                        const TargetLowering &TLI) {
4755   if (NumNonZero > 8)
4756     return SDValue();
4757
4758   DebugLoc dl = Op.getDebugLoc();
4759   SDValue V(0, 0);
4760   bool First = true;
4761   for (unsigned i = 0; i < 16; ++i) {
4762     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4763     if (ThisIsNonZero && First) {
4764       if (NumZero)
4765         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4766       else
4767         V = DAG.getUNDEF(MVT::v8i16);
4768       First = false;
4769     }
4770
4771     if ((i & 1) != 0) {
4772       SDValue ThisElt(0, 0), LastElt(0, 0);
4773       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4774       if (LastIsNonZero) {
4775         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4776                               MVT::i16, Op.getOperand(i-1));
4777       }
4778       if (ThisIsNonZero) {
4779         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4780         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4781                               ThisElt, DAG.getConstant(8, MVT::i8));
4782         if (LastIsNonZero)
4783           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4784       } else
4785         ThisElt = LastElt;
4786
4787       if (ThisElt.getNode())
4788         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4789                         DAG.getIntPtrConstant(i/2));
4790     }
4791   }
4792
4793   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4794 }
4795
4796 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4797 ///
4798 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4799                                      unsigned NumNonZero, unsigned NumZero,
4800                                      SelectionDAG &DAG,
4801                                      const X86Subtarget* Subtarget,
4802                                      const TargetLowering &TLI) {
4803   if (NumNonZero > 4)
4804     return SDValue();
4805
4806   DebugLoc dl = Op.getDebugLoc();
4807   SDValue V(0, 0);
4808   bool First = true;
4809   for (unsigned i = 0; i < 8; ++i) {
4810     bool isNonZero = (NonZeros & (1 << i)) != 0;
4811     if (isNonZero) {
4812       if (First) {
4813         if (NumZero)
4814           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4815         else
4816           V = DAG.getUNDEF(MVT::v8i16);
4817         First = false;
4818       }
4819       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4820                       MVT::v8i16, V, Op.getOperand(i),
4821                       DAG.getIntPtrConstant(i));
4822     }
4823   }
4824
4825   return V;
4826 }
4827
4828 /// getVShift - Return a vector logical shift node.
4829 ///
4830 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4831                          unsigned NumBits, SelectionDAG &DAG,
4832                          const TargetLowering &TLI, DebugLoc dl) {
4833   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4834   EVT ShVT = MVT::v2i64;
4835   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4836   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4837   return DAG.getNode(ISD::BITCAST, dl, VT,
4838                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4839                              DAG.getConstant(NumBits,
4840                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4841 }
4842
4843 SDValue
4844 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4845                                           SelectionDAG &DAG) const {
4846
4847   // Check if the scalar load can be widened into a vector load. And if
4848   // the address is "base + cst" see if the cst can be "absorbed" into
4849   // the shuffle mask.
4850   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4851     SDValue Ptr = LD->getBasePtr();
4852     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4853       return SDValue();
4854     EVT PVT = LD->getValueType(0);
4855     if (PVT != MVT::i32 && PVT != MVT::f32)
4856       return SDValue();
4857
4858     int FI = -1;
4859     int64_t Offset = 0;
4860     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4861       FI = FINode->getIndex();
4862       Offset = 0;
4863     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4864                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4865       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4866       Offset = Ptr.getConstantOperandVal(1);
4867       Ptr = Ptr.getOperand(0);
4868     } else {
4869       return SDValue();
4870     }
4871
4872     // FIXME: 256-bit vector instructions don't require a strict alignment,
4873     // improve this code to support it better.
4874     unsigned RequiredAlign = VT.getSizeInBits()/8;
4875     SDValue Chain = LD->getChain();
4876     // Make sure the stack object alignment is at least 16 or 32.
4877     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4878     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4879       if (MFI->isFixedObjectIndex(FI)) {
4880         // Can't change the alignment. FIXME: It's possible to compute
4881         // the exact stack offset and reference FI + adjust offset instead.
4882         // If someone *really* cares about this. That's the way to implement it.
4883         return SDValue();
4884       } else {
4885         MFI->setObjectAlignment(FI, RequiredAlign);
4886       }
4887     }
4888
4889     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4890     // Ptr + (Offset & ~15).
4891     if (Offset < 0)
4892       return SDValue();
4893     if ((Offset % RequiredAlign) & 3)
4894       return SDValue();
4895     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4896     if (StartOffset)
4897       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4898                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4899
4900     int EltNo = (Offset - StartOffset) >> 2;
4901     unsigned NumElems = VT.getVectorNumElements();
4902
4903     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4904     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4905                              LD->getPointerInfo().getWithOffset(StartOffset),
4906                              false, false, false, 0);
4907
4908     SmallVector<int, 8> Mask;
4909     for (unsigned i = 0; i != NumElems; ++i)
4910       Mask.push_back(EltNo);
4911
4912     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4913   }
4914
4915   return SDValue();
4916 }
4917
4918 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4919 /// vector of type 'VT', see if the elements can be replaced by a single large
4920 /// load which has the same value as a build_vector whose operands are 'elts'.
4921 ///
4922 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4923 ///
4924 /// FIXME: we'd also like to handle the case where the last elements are zero
4925 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4926 /// There's even a handy isZeroNode for that purpose.
4927 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4928                                         DebugLoc &DL, SelectionDAG &DAG) {
4929   EVT EltVT = VT.getVectorElementType();
4930   unsigned NumElems = Elts.size();
4931
4932   LoadSDNode *LDBase = NULL;
4933   unsigned LastLoadedElt = -1U;
4934
4935   // For each element in the initializer, see if we've found a load or an undef.
4936   // If we don't find an initial load element, or later load elements are
4937   // non-consecutive, bail out.
4938   for (unsigned i = 0; i < NumElems; ++i) {
4939     SDValue Elt = Elts[i];
4940
4941     if (!Elt.getNode() ||
4942         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4943       return SDValue();
4944     if (!LDBase) {
4945       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4946         return SDValue();
4947       LDBase = cast<LoadSDNode>(Elt.getNode());
4948       LastLoadedElt = i;
4949       continue;
4950     }
4951     if (Elt.getOpcode() == ISD::UNDEF)
4952       continue;
4953
4954     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4955     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4956       return SDValue();
4957     LastLoadedElt = i;
4958   }
4959
4960   // If we have found an entire vector of loads and undefs, then return a large
4961   // load of the entire vector width starting at the base pointer.  If we found
4962   // consecutive loads for the low half, generate a vzext_load node.
4963   if (LastLoadedElt == NumElems - 1) {
4964     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4965       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4966                          LDBase->getPointerInfo(),
4967                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4968                          LDBase->isInvariant(), 0);
4969     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4970                        LDBase->getPointerInfo(),
4971                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4972                        LDBase->isInvariant(), LDBase->getAlignment());
4973   }
4974   if (NumElems == 4 && LastLoadedElt == 1 &&
4975       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4976     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4977     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4978     SDValue ResNode =
4979         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4980                                 LDBase->getPointerInfo(),
4981                                 LDBase->getAlignment(),
4982                                 false/*isVolatile*/, true/*ReadMem*/,
4983                                 false/*WriteMem*/);
4984     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4985   }
4986   return SDValue();
4987 }
4988
4989 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4990 /// to generate a splat value for the following cases:
4991 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4992 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4993 /// a scalar load, or a constant.
4994 /// The VBROADCAST node is returned when a pattern is found,
4995 /// or SDValue() otherwise.
4996 SDValue
4997 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4998   if (!Subtarget->hasAVX())
4999     return SDValue();
5000
5001   EVT VT = Op.getValueType();
5002   DebugLoc dl = Op.getDebugLoc();
5003
5004   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5005          "Unsupported vector type for broadcast.");
5006
5007   SDValue Ld;
5008   bool ConstSplatVal;
5009
5010   switch (Op.getOpcode()) {
5011     default:
5012       // Unknown pattern found.
5013       return SDValue();
5014
5015     case ISD::BUILD_VECTOR: {
5016       // The BUILD_VECTOR node must be a splat.
5017       if (!isSplatVector(Op.getNode()))
5018         return SDValue();
5019
5020       Ld = Op.getOperand(0);
5021       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5022                      Ld.getOpcode() == ISD::ConstantFP);
5023
5024       // The suspected load node has several users. Make sure that all
5025       // of its users are from the BUILD_VECTOR node.
5026       // Constants may have multiple users.
5027       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5028         return SDValue();
5029       break;
5030     }
5031
5032     case ISD::VECTOR_SHUFFLE: {
5033       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5034
5035       // Shuffles must have a splat mask where the first element is
5036       // broadcasted.
5037       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5038         return SDValue();
5039
5040       SDValue Sc = Op.getOperand(0);
5041       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5042           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5043
5044         if (!Subtarget->hasAVX2())
5045           return SDValue();
5046
5047         // Use the register form of the broadcast instruction available on AVX2.
5048         if (VT.is256BitVector())
5049           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5050         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5051       }
5052
5053       Ld = Sc.getOperand(0);
5054       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5055                        Ld.getOpcode() == ISD::ConstantFP);
5056
5057       // The scalar_to_vector node and the suspected
5058       // load node must have exactly one user.
5059       // Constants may have multiple users.
5060       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5061         return SDValue();
5062       break;
5063     }
5064   }
5065
5066   bool Is256 = VT.getSizeInBits() == 256;
5067
5068   // Handle the broadcasting a single constant scalar from the constant pool
5069   // into a vector. On Sandybridge it is still better to load a constant vector
5070   // from the constant pool and not to broadcast it from a scalar.
5071   if (ConstSplatVal && Subtarget->hasAVX2()) {
5072     EVT CVT = Ld.getValueType();
5073     assert(!CVT.isVector() && "Must not broadcast a vector type");
5074     unsigned ScalarSize = CVT.getSizeInBits();
5075
5076     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5077       const Constant *C = 0;
5078       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5079         C = CI->getConstantIntValue();
5080       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5081         C = CF->getConstantFPValue();
5082
5083       assert(C && "Invalid constant type");
5084
5085       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5086       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5087       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5088                        MachinePointerInfo::getConstantPool(),
5089                        false, false, false, Alignment);
5090
5091       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5092     }
5093   }
5094
5095   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5096   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5097
5098   // Handle AVX2 in-register broadcasts.
5099   if (!IsLoad && Subtarget->hasAVX2() &&
5100       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5101     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5102
5103   // The scalar source must be a normal load.
5104   if (!IsLoad)
5105     return SDValue();
5106
5107   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5108     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5109
5110   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5111   // double since there is no vbroadcastsd xmm
5112   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5113     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5114       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5115   }
5116
5117   // Unsupported broadcast.
5118   return SDValue();
5119 }
5120
5121 SDValue
5122 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5123   DebugLoc dl = Op.getDebugLoc();
5124
5125   EVT VT = Op.getValueType();
5126   EVT ExtVT = VT.getVectorElementType();
5127   unsigned NumElems = Op.getNumOperands();
5128
5129   // Vectors containing all zeros can be matched by pxor and xorps later
5130   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5131     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5132     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5133     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5134       return Op;
5135
5136     return getZeroVector(VT, Subtarget, DAG, dl);
5137   }
5138
5139   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5140   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5141   // vpcmpeqd on 256-bit vectors.
5142   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5143     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5144       return Op;
5145
5146     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5147   }
5148
5149   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5150   if (Broadcast.getNode())
5151     return Broadcast;
5152
5153   unsigned EVTBits = ExtVT.getSizeInBits();
5154
5155   unsigned NumZero  = 0;
5156   unsigned NumNonZero = 0;
5157   unsigned NonZeros = 0;
5158   bool IsAllConstants = true;
5159   SmallSet<SDValue, 8> Values;
5160   for (unsigned i = 0; i < NumElems; ++i) {
5161     SDValue Elt = Op.getOperand(i);
5162     if (Elt.getOpcode() == ISD::UNDEF)
5163       continue;
5164     Values.insert(Elt);
5165     if (Elt.getOpcode() != ISD::Constant &&
5166         Elt.getOpcode() != ISD::ConstantFP)
5167       IsAllConstants = false;
5168     if (X86::isZeroNode(Elt))
5169       NumZero++;
5170     else {
5171       NonZeros |= (1 << i);
5172       NumNonZero++;
5173     }
5174   }
5175
5176   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5177   if (NumNonZero == 0)
5178     return DAG.getUNDEF(VT);
5179
5180   // Special case for single non-zero, non-undef, element.
5181   if (NumNonZero == 1) {
5182     unsigned Idx = CountTrailingZeros_32(NonZeros);
5183     SDValue Item = Op.getOperand(Idx);
5184
5185     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5186     // the value are obviously zero, truncate the value to i32 and do the
5187     // insertion that way.  Only do this if the value is non-constant or if the
5188     // value is a constant being inserted into element 0.  It is cheaper to do
5189     // a constant pool load than it is to do a movd + shuffle.
5190     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5191         (!IsAllConstants || Idx == 0)) {
5192       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5193         // Handle SSE only.
5194         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5195         EVT VecVT = MVT::v4i32;
5196         unsigned VecElts = 4;
5197
5198         // Truncate the value (which may itself be a constant) to i32, and
5199         // convert it to a vector with movd (S2V+shuffle to zero extend).
5200         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5201         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5202         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5203
5204         // Now we have our 32-bit value zero extended in the low element of
5205         // a vector.  If Idx != 0, swizzle it into place.
5206         if (Idx != 0) {
5207           SmallVector<int, 4> Mask;
5208           Mask.push_back(Idx);
5209           for (unsigned i = 1; i != VecElts; ++i)
5210             Mask.push_back(i);
5211           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5212                                       &Mask[0]);
5213         }
5214         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5215       }
5216     }
5217
5218     // If we have a constant or non-constant insertion into the low element of
5219     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5220     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5221     // depending on what the source datatype is.
5222     if (Idx == 0) {
5223       if (NumZero == 0)
5224         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5225
5226       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5227           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5228         if (VT.getSizeInBits() == 256) {
5229           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5230           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5231                              Item, DAG.getIntPtrConstant(0));
5232         }
5233         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5234         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5235         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5236         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5237       }
5238
5239       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5240         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5241         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5242         if (VT.getSizeInBits() == 256) {
5243           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5244           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5245         } else {
5246           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5247           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5248         }
5249         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5250       }
5251     }
5252
5253     // Is it a vector logical left shift?
5254     if (NumElems == 2 && Idx == 1 &&
5255         X86::isZeroNode(Op.getOperand(0)) &&
5256         !X86::isZeroNode(Op.getOperand(1))) {
5257       unsigned NumBits = VT.getSizeInBits();
5258       return getVShift(true, VT,
5259                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5260                                    VT, Op.getOperand(1)),
5261                        NumBits/2, DAG, *this, dl);
5262     }
5263
5264     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5265       return SDValue();
5266
5267     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5268     // is a non-constant being inserted into an element other than the low one,
5269     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5270     // movd/movss) to move this into the low element, then shuffle it into
5271     // place.
5272     if (EVTBits == 32) {
5273       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5274
5275       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5276       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5277       SmallVector<int, 8> MaskVec;
5278       for (unsigned i = 0; i != NumElems; ++i)
5279         MaskVec.push_back(i == Idx ? 0 : 1);
5280       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5281     }
5282   }
5283
5284   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5285   if (Values.size() == 1) {
5286     if (EVTBits == 32) {
5287       // Instead of a shuffle like this:
5288       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5289       // Check if it's possible to issue this instead.
5290       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5291       unsigned Idx = CountTrailingZeros_32(NonZeros);
5292       SDValue Item = Op.getOperand(Idx);
5293       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5294         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5295     }
5296     return SDValue();
5297   }
5298
5299   // A vector full of immediates; various special cases are already
5300   // handled, so this is best done with a single constant-pool load.
5301   if (IsAllConstants)
5302     return SDValue();
5303
5304   // For AVX-length vectors, build the individual 128-bit pieces and use
5305   // shuffles to put them in place.
5306   if (VT.getSizeInBits() == 256) {
5307     SmallVector<SDValue, 32> V;
5308     for (unsigned i = 0; i != NumElems; ++i)
5309       V.push_back(Op.getOperand(i));
5310
5311     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5312
5313     // Build both the lower and upper subvector.
5314     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5315     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5316                                 NumElems/2);
5317
5318     // Recreate the wider vector with the lower and upper part.
5319     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5320   }
5321
5322   // Let legalizer expand 2-wide build_vectors.
5323   if (EVTBits == 64) {
5324     if (NumNonZero == 1) {
5325       // One half is zero or undef.
5326       unsigned Idx = CountTrailingZeros_32(NonZeros);
5327       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5328                                  Op.getOperand(Idx));
5329       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5330     }
5331     return SDValue();
5332   }
5333
5334   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5335   if (EVTBits == 8 && NumElems == 16) {
5336     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5337                                         Subtarget, *this);
5338     if (V.getNode()) return V;
5339   }
5340
5341   if (EVTBits == 16 && NumElems == 8) {
5342     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5343                                       Subtarget, *this);
5344     if (V.getNode()) return V;
5345   }
5346
5347   // If element VT is == 32 bits, turn it into a number of shuffles.
5348   SmallVector<SDValue, 8> V(NumElems);
5349   if (NumElems == 4 && NumZero > 0) {
5350     for (unsigned i = 0; i < 4; ++i) {
5351       bool isZero = !(NonZeros & (1 << i));
5352       if (isZero)
5353         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5354       else
5355         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5356     }
5357
5358     for (unsigned i = 0; i < 2; ++i) {
5359       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5360         default: break;
5361         case 0:
5362           V[i] = V[i*2];  // Must be a zero vector.
5363           break;
5364         case 1:
5365           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5366           break;
5367         case 2:
5368           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5369           break;
5370         case 3:
5371           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5372           break;
5373       }
5374     }
5375
5376     bool Reverse1 = (NonZeros & 0x3) == 2;
5377     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5378     int MaskVec[] = {
5379       Reverse1 ? 1 : 0,
5380       Reverse1 ? 0 : 1,
5381       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5382       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5383     };
5384     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5385   }
5386
5387   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5388     // Check for a build vector of consecutive loads.
5389     for (unsigned i = 0; i < NumElems; ++i)
5390       V[i] = Op.getOperand(i);
5391
5392     // Check for elements which are consecutive loads.
5393     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5394     if (LD.getNode())
5395       return LD;
5396
5397     // For SSE 4.1, use insertps to put the high elements into the low element.
5398     if (getSubtarget()->hasSSE41()) {
5399       SDValue Result;
5400       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5401         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5402       else
5403         Result = DAG.getUNDEF(VT);
5404
5405       for (unsigned i = 1; i < NumElems; ++i) {
5406         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5407         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5408                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5409       }
5410       return Result;
5411     }
5412
5413     // Otherwise, expand into a number of unpckl*, start by extending each of
5414     // our (non-undef) elements to the full vector width with the element in the
5415     // bottom slot of the vector (which generates no code for SSE).
5416     for (unsigned i = 0; i < NumElems; ++i) {
5417       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5418         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5419       else
5420         V[i] = DAG.getUNDEF(VT);
5421     }
5422
5423     // Next, we iteratively mix elements, e.g. for v4f32:
5424     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5425     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5426     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5427     unsigned EltStride = NumElems >> 1;
5428     while (EltStride != 0) {
5429       for (unsigned i = 0; i < EltStride; ++i) {
5430         // If V[i+EltStride] is undef and this is the first round of mixing,
5431         // then it is safe to just drop this shuffle: V[i] is already in the
5432         // right place, the one element (since it's the first round) being
5433         // inserted as undef can be dropped.  This isn't safe for successive
5434         // rounds because they will permute elements within both vectors.
5435         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5436             EltStride == NumElems/2)
5437           continue;
5438
5439         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5440       }
5441       EltStride >>= 1;
5442     }
5443     return V[0];
5444   }
5445   return SDValue();
5446 }
5447
5448 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5449 // them in a MMX register.  This is better than doing a stack convert.
5450 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5451   DebugLoc dl = Op.getDebugLoc();
5452   EVT ResVT = Op.getValueType();
5453
5454   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5455          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5456   int Mask[2];
5457   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5458   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5459   InVec = Op.getOperand(1);
5460   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5461     unsigned NumElts = ResVT.getVectorNumElements();
5462     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5463     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5464                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5465   } else {
5466     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5467     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5468     Mask[0] = 0; Mask[1] = 2;
5469     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5470   }
5471   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5472 }
5473
5474 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5475 // to create 256-bit vectors from two other 128-bit ones.
5476 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5477   DebugLoc dl = Op.getDebugLoc();
5478   EVT ResVT = Op.getValueType();
5479
5480   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5481
5482   SDValue V1 = Op.getOperand(0);
5483   SDValue V2 = Op.getOperand(1);
5484   unsigned NumElems = ResVT.getVectorNumElements();
5485
5486   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5487 }
5488
5489 SDValue
5490 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5491   EVT ResVT = Op.getValueType();
5492
5493   assert(Op.getNumOperands() == 2);
5494   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5495          "Unsupported CONCAT_VECTORS for value type");
5496
5497   // We support concatenate two MMX registers and place them in a MMX register.
5498   // This is better than doing a stack convert.
5499   if (ResVT.is128BitVector())
5500     return LowerMMXCONCAT_VECTORS(Op, DAG);
5501
5502   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5503   // from two other 128-bit ones.
5504   return LowerAVXCONCAT_VECTORS(Op, DAG);
5505 }
5506
5507 // Try to lower a shuffle node into a simple blend instruction.
5508 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5509                                           const X86Subtarget *Subtarget,
5510                                           SelectionDAG &DAG) {
5511   SDValue V1 = SVOp->getOperand(0);
5512   SDValue V2 = SVOp->getOperand(1);
5513   DebugLoc dl = SVOp->getDebugLoc();
5514   MVT VT = SVOp->getValueType(0).getSimpleVT();
5515   unsigned NumElems = VT.getVectorNumElements();
5516
5517   if (!Subtarget->hasSSE41())
5518     return SDValue();
5519
5520   unsigned ISDNo = 0;
5521   MVT OpTy;
5522
5523   switch (VT.SimpleTy) {
5524   default: return SDValue();
5525   case MVT::v8i16:
5526     ISDNo = X86ISD::BLENDPW;
5527     OpTy = MVT::v8i16;
5528     break;
5529   case MVT::v4i32:
5530   case MVT::v4f32:
5531     ISDNo = X86ISD::BLENDPS;
5532     OpTy = MVT::v4f32;
5533     break;
5534   case MVT::v2i64:
5535   case MVT::v2f64:
5536     ISDNo = X86ISD::BLENDPD;
5537     OpTy = MVT::v2f64;
5538     break;
5539   case MVT::v8i32:
5540   case MVT::v8f32:
5541     if (!Subtarget->hasAVX())
5542       return SDValue();
5543     ISDNo = X86ISD::BLENDPS;
5544     OpTy = MVT::v8f32;
5545     break;
5546   case MVT::v4i64:
5547   case MVT::v4f64:
5548     if (!Subtarget->hasAVX())
5549       return SDValue();
5550     ISDNo = X86ISD::BLENDPD;
5551     OpTy = MVT::v4f64;
5552     break;
5553   }
5554   assert(ISDNo && "Invalid Op Number");
5555
5556   unsigned MaskVals = 0;
5557
5558   for (unsigned i = 0; i != NumElems; ++i) {
5559     int EltIdx = SVOp->getMaskElt(i);
5560     if (EltIdx == (int)i || EltIdx < 0)
5561       MaskVals |= (1<<i);
5562     else if (EltIdx == (int)(i + NumElems))
5563       continue; // Bit is set to zero;
5564     else
5565       return SDValue();
5566   }
5567
5568   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5569   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5570   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5571                              DAG.getConstant(MaskVals, MVT::i32));
5572   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5573 }
5574
5575 // v8i16 shuffles - Prefer shuffles in the following order:
5576 // 1. [all]   pshuflw, pshufhw, optional move
5577 // 2. [ssse3] 1 x pshufb
5578 // 3. [ssse3] 2 x pshufb + 1 x por
5579 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5580 SDValue
5581 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5582                                             SelectionDAG &DAG) const {
5583   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5584   SDValue V1 = SVOp->getOperand(0);
5585   SDValue V2 = SVOp->getOperand(1);
5586   DebugLoc dl = SVOp->getDebugLoc();
5587   SmallVector<int, 8> MaskVals;
5588
5589   // Determine if more than 1 of the words in each of the low and high quadwords
5590   // of the result come from the same quadword of one of the two inputs.  Undef
5591   // mask values count as coming from any quadword, for better codegen.
5592   unsigned LoQuad[] = { 0, 0, 0, 0 };
5593   unsigned HiQuad[] = { 0, 0, 0, 0 };
5594   std::bitset<4> InputQuads;
5595   for (unsigned i = 0; i < 8; ++i) {
5596     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5597     int EltIdx = SVOp->getMaskElt(i);
5598     MaskVals.push_back(EltIdx);
5599     if (EltIdx < 0) {
5600       ++Quad[0];
5601       ++Quad[1];
5602       ++Quad[2];
5603       ++Quad[3];
5604       continue;
5605     }
5606     ++Quad[EltIdx / 4];
5607     InputQuads.set(EltIdx / 4);
5608   }
5609
5610   int BestLoQuad = -1;
5611   unsigned MaxQuad = 1;
5612   for (unsigned i = 0; i < 4; ++i) {
5613     if (LoQuad[i] > MaxQuad) {
5614       BestLoQuad = i;
5615       MaxQuad = LoQuad[i];
5616     }
5617   }
5618
5619   int BestHiQuad = -1;
5620   MaxQuad = 1;
5621   for (unsigned i = 0; i < 4; ++i) {
5622     if (HiQuad[i] > MaxQuad) {
5623       BestHiQuad = i;
5624       MaxQuad = HiQuad[i];
5625     }
5626   }
5627
5628   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5629   // of the two input vectors, shuffle them into one input vector so only a
5630   // single pshufb instruction is necessary. If There are more than 2 input
5631   // quads, disable the next transformation since it does not help SSSE3.
5632   bool V1Used = InputQuads[0] || InputQuads[1];
5633   bool V2Used = InputQuads[2] || InputQuads[3];
5634   if (Subtarget->hasSSSE3()) {
5635     if (InputQuads.count() == 2 && V1Used && V2Used) {
5636       BestLoQuad = InputQuads[0] ? 0 : 1;
5637       BestHiQuad = InputQuads[2] ? 2 : 3;
5638     }
5639     if (InputQuads.count() > 2) {
5640       BestLoQuad = -1;
5641       BestHiQuad = -1;
5642     }
5643   }
5644
5645   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5646   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5647   // words from all 4 input quadwords.
5648   SDValue NewV;
5649   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5650     int MaskV[] = {
5651       BestLoQuad < 0 ? 0 : BestLoQuad,
5652       BestHiQuad < 0 ? 1 : BestHiQuad
5653     };
5654     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5655                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5656                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5657     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5658
5659     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5660     // source words for the shuffle, to aid later transformations.
5661     bool AllWordsInNewV = true;
5662     bool InOrder[2] = { true, true };
5663     for (unsigned i = 0; i != 8; ++i) {
5664       int idx = MaskVals[i];
5665       if (idx != (int)i)
5666         InOrder[i/4] = false;
5667       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5668         continue;
5669       AllWordsInNewV = false;
5670       break;
5671     }
5672
5673     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5674     if (AllWordsInNewV) {
5675       for (int i = 0; i != 8; ++i) {
5676         int idx = MaskVals[i];
5677         if (idx < 0)
5678           continue;
5679         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5680         if ((idx != i) && idx < 4)
5681           pshufhw = false;
5682         if ((idx != i) && idx > 3)
5683           pshuflw = false;
5684       }
5685       V1 = NewV;
5686       V2Used = false;
5687       BestLoQuad = 0;
5688       BestHiQuad = 1;
5689     }
5690
5691     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5692     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5693     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5694       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5695       unsigned TargetMask = 0;
5696       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5697                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5698       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5699       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5700                              getShufflePSHUFLWImmediate(SVOp);
5701       V1 = NewV.getOperand(0);
5702       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5703     }
5704   }
5705
5706   // If we have SSSE3, and all words of the result are from 1 input vector,
5707   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5708   // is present, fall back to case 4.
5709   if (Subtarget->hasSSSE3()) {
5710     SmallVector<SDValue,16> pshufbMask;
5711
5712     // If we have elements from both input vectors, set the high bit of the
5713     // shuffle mask element to zero out elements that come from V2 in the V1
5714     // mask, and elements that come from V1 in the V2 mask, so that the two
5715     // results can be OR'd together.
5716     bool TwoInputs = V1Used && V2Used;
5717     for (unsigned i = 0; i != 8; ++i) {
5718       int EltIdx = MaskVals[i] * 2;
5719       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5720       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5721       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5722       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5723     }
5724     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5725     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5726                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5727                                  MVT::v16i8, &pshufbMask[0], 16));
5728     if (!TwoInputs)
5729       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5730
5731     // Calculate the shuffle mask for the second input, shuffle it, and
5732     // OR it with the first shuffled input.
5733     pshufbMask.clear();
5734     for (unsigned i = 0; i != 8; ++i) {
5735       int EltIdx = MaskVals[i] * 2;
5736       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5737       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5738       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5739       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5740     }
5741     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5742     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5743                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5744                                  MVT::v16i8, &pshufbMask[0], 16));
5745     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5746     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5747   }
5748
5749   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5750   // and update MaskVals with new element order.
5751   std::bitset<8> InOrder;
5752   if (BestLoQuad >= 0) {
5753     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5754     for (int i = 0; i != 4; ++i) {
5755       int idx = MaskVals[i];
5756       if (idx < 0) {
5757         InOrder.set(i);
5758       } else if ((idx / 4) == BestLoQuad) {
5759         MaskV[i] = idx & 3;
5760         InOrder.set(i);
5761       }
5762     }
5763     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5764                                 &MaskV[0]);
5765
5766     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5767       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5768       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5769                                   NewV.getOperand(0),
5770                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5771     }
5772   }
5773
5774   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5775   // and update MaskVals with the new element order.
5776   if (BestHiQuad >= 0) {
5777     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5778     for (unsigned i = 4; i != 8; ++i) {
5779       int idx = MaskVals[i];
5780       if (idx < 0) {
5781         InOrder.set(i);
5782       } else if ((idx / 4) == BestHiQuad) {
5783         MaskV[i] = (idx & 3) + 4;
5784         InOrder.set(i);
5785       }
5786     }
5787     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5788                                 &MaskV[0]);
5789
5790     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5791       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5792       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5793                                   NewV.getOperand(0),
5794                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5795     }
5796   }
5797
5798   // In case BestHi & BestLo were both -1, which means each quadword has a word
5799   // from each of the four input quadwords, calculate the InOrder bitvector now
5800   // before falling through to the insert/extract cleanup.
5801   if (BestLoQuad == -1 && BestHiQuad == -1) {
5802     NewV = V1;
5803     for (int i = 0; i != 8; ++i)
5804       if (MaskVals[i] < 0 || MaskVals[i] == i)
5805         InOrder.set(i);
5806   }
5807
5808   // The other elements are put in the right place using pextrw and pinsrw.
5809   for (unsigned i = 0; i != 8; ++i) {
5810     if (InOrder[i])
5811       continue;
5812     int EltIdx = MaskVals[i];
5813     if (EltIdx < 0)
5814       continue;
5815     SDValue ExtOp = (EltIdx < 8) ?
5816       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5817                   DAG.getIntPtrConstant(EltIdx)) :
5818       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5819                   DAG.getIntPtrConstant(EltIdx - 8));
5820     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5821                        DAG.getIntPtrConstant(i));
5822   }
5823   return NewV;
5824 }
5825
5826 // v16i8 shuffles - Prefer shuffles in the following order:
5827 // 1. [ssse3] 1 x pshufb
5828 // 2. [ssse3] 2 x pshufb + 1 x por
5829 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5830 static
5831 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5832                                  SelectionDAG &DAG,
5833                                  const X86TargetLowering &TLI) {
5834   SDValue V1 = SVOp->getOperand(0);
5835   SDValue V2 = SVOp->getOperand(1);
5836   DebugLoc dl = SVOp->getDebugLoc();
5837   ArrayRef<int> MaskVals = SVOp->getMask();
5838
5839   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5840
5841   // If we have SSSE3, case 1 is generated when all result bytes come from
5842   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5843   // present, fall back to case 3.
5844
5845   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5846   if (TLI.getSubtarget()->hasSSSE3()) {
5847     SmallVector<SDValue,16> pshufbMask;
5848
5849     // If all result elements are from one input vector, then only translate
5850     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5851     //
5852     // Otherwise, we have elements from both input vectors, and must zero out
5853     // elements that come from V2 in the first mask, and V1 in the second mask
5854     // so that we can OR them together.
5855     for (unsigned i = 0; i != 16; ++i) {
5856       int EltIdx = MaskVals[i];
5857       if (EltIdx < 0 || EltIdx >= 16)
5858         EltIdx = 0x80;
5859       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5860     }
5861     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5862                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5863                                  MVT::v16i8, &pshufbMask[0], 16));
5864     if (V2IsUndef)
5865       return V1;
5866
5867     // Calculate the shuffle mask for the second input, shuffle it, and
5868     // OR it with the first shuffled input.
5869     pshufbMask.clear();
5870     for (unsigned i = 0; i != 16; ++i) {
5871       int EltIdx = MaskVals[i];
5872       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5873       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5874     }
5875     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5876                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5877                                  MVT::v16i8, &pshufbMask[0], 16));
5878     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5879   }
5880
5881   // No SSSE3 - Calculate in place words and then fix all out of place words
5882   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5883   // the 16 different words that comprise the two doublequadword input vectors.
5884   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5885   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5886   SDValue NewV = V1;
5887   for (int i = 0; i != 8; ++i) {
5888     int Elt0 = MaskVals[i*2];
5889     int Elt1 = MaskVals[i*2+1];
5890
5891     // This word of the result is all undef, skip it.
5892     if (Elt0 < 0 && Elt1 < 0)
5893       continue;
5894
5895     // This word of the result is already in the correct place, skip it.
5896     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5897       continue;
5898
5899     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5900     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5901     SDValue InsElt;
5902
5903     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5904     // using a single extract together, load it and store it.
5905     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5906       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5907                            DAG.getIntPtrConstant(Elt1 / 2));
5908       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5909                         DAG.getIntPtrConstant(i));
5910       continue;
5911     }
5912
5913     // If Elt1 is defined, extract it from the appropriate source.  If the
5914     // source byte is not also odd, shift the extracted word left 8 bits
5915     // otherwise clear the bottom 8 bits if we need to do an or.
5916     if (Elt1 >= 0) {
5917       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5918                            DAG.getIntPtrConstant(Elt1 / 2));
5919       if ((Elt1 & 1) == 0)
5920         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5921                              DAG.getConstant(8,
5922                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5923       else if (Elt0 >= 0)
5924         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5925                              DAG.getConstant(0xFF00, MVT::i16));
5926     }
5927     // If Elt0 is defined, extract it from the appropriate source.  If the
5928     // source byte is not also even, shift the extracted word right 8 bits. If
5929     // Elt1 was also defined, OR the extracted values together before
5930     // inserting them in the result.
5931     if (Elt0 >= 0) {
5932       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5933                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5934       if ((Elt0 & 1) != 0)
5935         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5936                               DAG.getConstant(8,
5937                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5938       else if (Elt1 >= 0)
5939         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5940                              DAG.getConstant(0x00FF, MVT::i16));
5941       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5942                          : InsElt0;
5943     }
5944     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5945                        DAG.getIntPtrConstant(i));
5946   }
5947   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5948 }
5949
5950 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5951 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5952 /// done when every pair / quad of shuffle mask elements point to elements in
5953 /// the right sequence. e.g.
5954 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5955 static
5956 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5957                                  SelectionDAG &DAG, DebugLoc dl) {
5958   MVT VT = SVOp->getValueType(0).getSimpleVT();
5959   unsigned NumElems = VT.getVectorNumElements();
5960   MVT NewVT;
5961   unsigned Scale;
5962   switch (VT.SimpleTy) {
5963   default: llvm_unreachable("Unexpected!");
5964   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5965   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5966   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5967   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5968   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5969   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5970   }
5971
5972   SmallVector<int, 8> MaskVec;
5973   for (unsigned i = 0; i != NumElems; i += Scale) {
5974     int StartIdx = -1;
5975     for (unsigned j = 0; j != Scale; ++j) {
5976       int EltIdx = SVOp->getMaskElt(i+j);
5977       if (EltIdx < 0)
5978         continue;
5979       if (StartIdx < 0)
5980         StartIdx = (EltIdx / Scale);
5981       if (EltIdx != (int)(StartIdx*Scale + j))
5982         return SDValue();
5983     }
5984     MaskVec.push_back(StartIdx);
5985   }
5986
5987   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5988   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5989   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5990 }
5991
5992 /// getVZextMovL - Return a zero-extending vector move low node.
5993 ///
5994 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5995                             SDValue SrcOp, SelectionDAG &DAG,
5996                             const X86Subtarget *Subtarget, DebugLoc dl) {
5997   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5998     LoadSDNode *LD = NULL;
5999     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6000       LD = dyn_cast<LoadSDNode>(SrcOp);
6001     if (!LD) {
6002       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6003       // instead.
6004       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6005       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6006           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6007           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6008           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6009         // PR2108
6010         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6011         return DAG.getNode(ISD::BITCAST, dl, VT,
6012                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6013                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6014                                                    OpVT,
6015                                                    SrcOp.getOperand(0)
6016                                                           .getOperand(0))));
6017       }
6018     }
6019   }
6020
6021   return DAG.getNode(ISD::BITCAST, dl, VT,
6022                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6023                                  DAG.getNode(ISD::BITCAST, dl,
6024                                              OpVT, SrcOp)));
6025 }
6026
6027 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6028 /// which could not be matched by any known target speficic shuffle
6029 static SDValue
6030 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6031
6032   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6033   if (NewOp.getNode())
6034     return NewOp;
6035
6036   EVT VT = SVOp->getValueType(0);
6037
6038   unsigned NumElems = VT.getVectorNumElements();
6039   unsigned NumLaneElems = NumElems / 2;
6040
6041   DebugLoc dl = SVOp->getDebugLoc();
6042   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6043   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6044   SDValue Output[2];
6045
6046   SmallVector<int, 16> Mask;
6047   for (unsigned l = 0; l < 2; ++l) {
6048     // Build a shuffle mask for the output, discovering on the fly which
6049     // input vectors to use as shuffle operands (recorded in InputUsed).
6050     // If building a suitable shuffle vector proves too hard, then bail
6051     // out with UseBuildVector set.
6052     bool UseBuildVector = false;
6053     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6054     unsigned LaneStart = l * NumLaneElems;
6055     for (unsigned i = 0; i != NumLaneElems; ++i) {
6056       // The mask element.  This indexes into the input.
6057       int Idx = SVOp->getMaskElt(i+LaneStart);
6058       if (Idx < 0) {
6059         // the mask element does not index into any input vector.
6060         Mask.push_back(-1);
6061         continue;
6062       }
6063
6064       // The input vector this mask element indexes into.
6065       int Input = Idx / NumLaneElems;
6066
6067       // Turn the index into an offset from the start of the input vector.
6068       Idx -= Input * NumLaneElems;
6069
6070       // Find or create a shuffle vector operand to hold this input.
6071       unsigned OpNo;
6072       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6073         if (InputUsed[OpNo] == Input)
6074           // This input vector is already an operand.
6075           break;
6076         if (InputUsed[OpNo] < 0) {
6077           // Create a new operand for this input vector.
6078           InputUsed[OpNo] = Input;
6079           break;
6080         }
6081       }
6082
6083       if (OpNo >= array_lengthof(InputUsed)) {
6084         // More than two input vectors used!  Give up on trying to create a
6085         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6086         UseBuildVector = true;
6087         break;
6088       }
6089
6090       // Add the mask index for the new shuffle vector.
6091       Mask.push_back(Idx + OpNo * NumLaneElems);
6092     }
6093
6094     if (UseBuildVector) {
6095       SmallVector<SDValue, 16> SVOps;
6096       for (unsigned i = 0; i != NumLaneElems; ++i) {
6097         // The mask element.  This indexes into the input.
6098         int Idx = SVOp->getMaskElt(i+LaneStart);
6099         if (Idx < 0) {
6100           SVOps.push_back(DAG.getUNDEF(EltVT));
6101           continue;
6102         }
6103
6104         // The input vector this mask element indexes into.
6105         int Input = Idx / NumElems;
6106
6107         // Turn the index into an offset from the start of the input vector.
6108         Idx -= Input * NumElems;
6109
6110         // Extract the vector element by hand.
6111         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6112                                     SVOp->getOperand(Input),
6113                                     DAG.getIntPtrConstant(Idx)));
6114       }
6115
6116       // Construct the output using a BUILD_VECTOR.
6117       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6118                               SVOps.size());
6119     } else if (InputUsed[0] < 0) {
6120       // No input vectors were used! The result is undefined.
6121       Output[l] = DAG.getUNDEF(NVT);
6122     } else {
6123       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6124                                         (InputUsed[0] % 2) * NumLaneElems,
6125                                         DAG, dl);
6126       // If only one input was used, use an undefined vector for the other.
6127       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6128         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6129                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6130       // At least one input vector was used. Create a new shuffle vector.
6131       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6132     }
6133
6134     Mask.clear();
6135   }
6136
6137   // Concatenate the result back
6138   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6139 }
6140
6141 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6142 /// 4 elements, and match them with several different shuffle types.
6143 static SDValue
6144 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6145   SDValue V1 = SVOp->getOperand(0);
6146   SDValue V2 = SVOp->getOperand(1);
6147   DebugLoc dl = SVOp->getDebugLoc();
6148   EVT VT = SVOp->getValueType(0);
6149
6150   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6151
6152   std::pair<int, int> Locs[4];
6153   int Mask1[] = { -1, -1, -1, -1 };
6154   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6155
6156   unsigned NumHi = 0;
6157   unsigned NumLo = 0;
6158   for (unsigned i = 0; i != 4; ++i) {
6159     int Idx = PermMask[i];
6160     if (Idx < 0) {
6161       Locs[i] = std::make_pair(-1, -1);
6162     } else {
6163       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6164       if (Idx < 4) {
6165         Locs[i] = std::make_pair(0, NumLo);
6166         Mask1[NumLo] = Idx;
6167         NumLo++;
6168       } else {
6169         Locs[i] = std::make_pair(1, NumHi);
6170         if (2+NumHi < 4)
6171           Mask1[2+NumHi] = Idx;
6172         NumHi++;
6173       }
6174     }
6175   }
6176
6177   if (NumLo <= 2 && NumHi <= 2) {
6178     // If no more than two elements come from either vector. This can be
6179     // implemented with two shuffles. First shuffle gather the elements.
6180     // The second shuffle, which takes the first shuffle as both of its
6181     // vector operands, put the elements into the right order.
6182     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6183
6184     int Mask2[] = { -1, -1, -1, -1 };
6185
6186     for (unsigned i = 0; i != 4; ++i)
6187       if (Locs[i].first != -1) {
6188         unsigned Idx = (i < 2) ? 0 : 4;
6189         Idx += Locs[i].first * 2 + Locs[i].second;
6190         Mask2[i] = Idx;
6191       }
6192
6193     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6194   }
6195
6196   if (NumLo == 3 || NumHi == 3) {
6197     // Otherwise, we must have three elements from one vector, call it X, and
6198     // one element from the other, call it Y.  First, use a shufps to build an
6199     // intermediate vector with the one element from Y and the element from X
6200     // that will be in the same half in the final destination (the indexes don't
6201     // matter). Then, use a shufps to build the final vector, taking the half
6202     // containing the element from Y from the intermediate, and the other half
6203     // from X.
6204     if (NumHi == 3) {
6205       // Normalize it so the 3 elements come from V1.
6206       CommuteVectorShuffleMask(PermMask, 4);
6207       std::swap(V1, V2);
6208     }
6209
6210     // Find the element from V2.
6211     unsigned HiIndex;
6212     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6213       int Val = PermMask[HiIndex];
6214       if (Val < 0)
6215         continue;
6216       if (Val >= 4)
6217         break;
6218     }
6219
6220     Mask1[0] = PermMask[HiIndex];
6221     Mask1[1] = -1;
6222     Mask1[2] = PermMask[HiIndex^1];
6223     Mask1[3] = -1;
6224     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6225
6226     if (HiIndex >= 2) {
6227       Mask1[0] = PermMask[0];
6228       Mask1[1] = PermMask[1];
6229       Mask1[2] = HiIndex & 1 ? 6 : 4;
6230       Mask1[3] = HiIndex & 1 ? 4 : 6;
6231       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6232     }
6233
6234     Mask1[0] = HiIndex & 1 ? 2 : 0;
6235     Mask1[1] = HiIndex & 1 ? 0 : 2;
6236     Mask1[2] = PermMask[2];
6237     Mask1[3] = PermMask[3];
6238     if (Mask1[2] >= 0)
6239       Mask1[2] += 4;
6240     if (Mask1[3] >= 0)
6241       Mask1[3] += 4;
6242     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6243   }
6244
6245   // Break it into (shuffle shuffle_hi, shuffle_lo).
6246   int LoMask[] = { -1, -1, -1, -1 };
6247   int HiMask[] = { -1, -1, -1, -1 };
6248
6249   int *MaskPtr = LoMask;
6250   unsigned MaskIdx = 0;
6251   unsigned LoIdx = 0;
6252   unsigned HiIdx = 2;
6253   for (unsigned i = 0; i != 4; ++i) {
6254     if (i == 2) {
6255       MaskPtr = HiMask;
6256       MaskIdx = 1;
6257       LoIdx = 0;
6258       HiIdx = 2;
6259     }
6260     int Idx = PermMask[i];
6261     if (Idx < 0) {
6262       Locs[i] = std::make_pair(-1, -1);
6263     } else if (Idx < 4) {
6264       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6265       MaskPtr[LoIdx] = Idx;
6266       LoIdx++;
6267     } else {
6268       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6269       MaskPtr[HiIdx] = Idx;
6270       HiIdx++;
6271     }
6272   }
6273
6274   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6275   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6276   int MaskOps[] = { -1, -1, -1, -1 };
6277   for (unsigned i = 0; i != 4; ++i)
6278     if (Locs[i].first != -1)
6279       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6280   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6281 }
6282
6283 static bool MayFoldVectorLoad(SDValue V) {
6284   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6285     V = V.getOperand(0);
6286   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6287     V = V.getOperand(0);
6288   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6289       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6290     // BUILD_VECTOR (load), undef
6291     V = V.getOperand(0);
6292   if (MayFoldLoad(V))
6293     return true;
6294   return false;
6295 }
6296
6297 // FIXME: the version above should always be used. Since there's
6298 // a bug where several vector shuffles can't be folded because the
6299 // DAG is not updated during lowering and a node claims to have two
6300 // uses while it only has one, use this version, and let isel match
6301 // another instruction if the load really happens to have more than
6302 // one use. Remove this version after this bug get fixed.
6303 // rdar://8434668, PR8156
6304 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6305   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6306     V = V.getOperand(0);
6307   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6308     V = V.getOperand(0);
6309   if (ISD::isNormalLoad(V.getNode()))
6310     return true;
6311   return false;
6312 }
6313
6314 static
6315 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6316   EVT VT = Op.getValueType();
6317
6318   // Canonizalize to v2f64.
6319   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6320   return DAG.getNode(ISD::BITCAST, dl, VT,
6321                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6322                                           V1, DAG));
6323 }
6324
6325 static
6326 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6327                         bool HasSSE2) {
6328   SDValue V1 = Op.getOperand(0);
6329   SDValue V2 = Op.getOperand(1);
6330   EVT VT = Op.getValueType();
6331
6332   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6333
6334   if (HasSSE2 && VT == MVT::v2f64)
6335     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6336
6337   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6338   return DAG.getNode(ISD::BITCAST, dl, VT,
6339                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6340                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6341                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6342 }
6343
6344 static
6345 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6346   SDValue V1 = Op.getOperand(0);
6347   SDValue V2 = Op.getOperand(1);
6348   EVT VT = Op.getValueType();
6349
6350   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6351          "unsupported shuffle type");
6352
6353   if (V2.getOpcode() == ISD::UNDEF)
6354     V2 = V1;
6355
6356   // v4i32 or v4f32
6357   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6358 }
6359
6360 static
6361 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6362   SDValue V1 = Op.getOperand(0);
6363   SDValue V2 = Op.getOperand(1);
6364   EVT VT = Op.getValueType();
6365   unsigned NumElems = VT.getVectorNumElements();
6366
6367   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6368   // operand of these instructions is only memory, so check if there's a
6369   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6370   // same masks.
6371   bool CanFoldLoad = false;
6372
6373   // Trivial case, when V2 comes from a load.
6374   if (MayFoldVectorLoad(V2))
6375     CanFoldLoad = true;
6376
6377   // When V1 is a load, it can be folded later into a store in isel, example:
6378   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6379   //    turns into:
6380   //  (MOVLPSmr addr:$src1, VR128:$src2)
6381   // So, recognize this potential and also use MOVLPS or MOVLPD
6382   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6383     CanFoldLoad = true;
6384
6385   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6386   if (CanFoldLoad) {
6387     if (HasSSE2 && NumElems == 2)
6388       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6389
6390     if (NumElems == 4)
6391       // If we don't care about the second element, proceed to use movss.
6392       if (SVOp->getMaskElt(1) != -1)
6393         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6394   }
6395
6396   // movl and movlp will both match v2i64, but v2i64 is never matched by
6397   // movl earlier because we make it strict to avoid messing with the movlp load
6398   // folding logic (see the code above getMOVLP call). Match it here then,
6399   // this is horrible, but will stay like this until we move all shuffle
6400   // matching to x86 specific nodes. Note that for the 1st condition all
6401   // types are matched with movsd.
6402   if (HasSSE2) {
6403     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6404     // as to remove this logic from here, as much as possible
6405     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6406       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6407     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6408   }
6409
6410   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6411
6412   // Invert the operand order and use SHUFPS to match it.
6413   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6414                               getShuffleSHUFImmediate(SVOp), DAG);
6415 }
6416
6417 SDValue
6418 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6419   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6420   EVT VT = Op.getValueType();
6421   DebugLoc dl = Op.getDebugLoc();
6422   SDValue V1 = Op.getOperand(0);
6423   SDValue V2 = Op.getOperand(1);
6424
6425   if (isZeroShuffle(SVOp))
6426     return getZeroVector(VT, Subtarget, DAG, dl);
6427
6428   // Handle splat operations
6429   if (SVOp->isSplat()) {
6430     unsigned NumElem = VT.getVectorNumElements();
6431     int Size = VT.getSizeInBits();
6432
6433     // Use vbroadcast whenever the splat comes from a foldable load
6434     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6435     if (Broadcast.getNode())
6436       return Broadcast;
6437
6438     // Handle splats by matching through known shuffle masks
6439     if ((Size == 128 && NumElem <= 4) ||
6440         (Size == 256 && NumElem < 8))
6441       return SDValue();
6442
6443     // All remaning splats are promoted to target supported vector shuffles.
6444     return PromoteSplat(SVOp, DAG);
6445   }
6446
6447   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6448   // do it!
6449   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6450       VT == MVT::v16i16 || VT == MVT::v32i8) {
6451     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6452     if (NewOp.getNode())
6453       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6454   } else if ((VT == MVT::v4i32 ||
6455              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6456     // FIXME: Figure out a cleaner way to do this.
6457     // Try to make use of movq to zero out the top part.
6458     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6459       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6460       if (NewOp.getNode()) {
6461         EVT NewVT = NewOp.getValueType();
6462         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6463                                NewVT, true, false))
6464           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6465                               DAG, Subtarget, dl);
6466       }
6467     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6468       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6469       if (NewOp.getNode()) {
6470         EVT NewVT = NewOp.getValueType();
6471         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6472           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6473                               DAG, Subtarget, dl);
6474       }
6475     }
6476   }
6477   return SDValue();
6478 }
6479
6480 SDValue
6481 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6482   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6483   SDValue V1 = Op.getOperand(0);
6484   SDValue V2 = Op.getOperand(1);
6485   EVT VT = Op.getValueType();
6486   DebugLoc dl = Op.getDebugLoc();
6487   unsigned NumElems = VT.getVectorNumElements();
6488   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6489   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6490   bool V1IsSplat = false;
6491   bool V2IsSplat = false;
6492   bool HasSSE2 = Subtarget->hasSSE2();
6493   bool HasAVX    = Subtarget->hasAVX();
6494   bool HasAVX2   = Subtarget->hasAVX2();
6495   MachineFunction &MF = DAG.getMachineFunction();
6496   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6497
6498   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6499
6500   if (V1IsUndef && V2IsUndef)
6501     return DAG.getUNDEF(VT);
6502
6503   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6504
6505   // Vector shuffle lowering takes 3 steps:
6506   //
6507   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6508   //    narrowing and commutation of operands should be handled.
6509   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6510   //    shuffle nodes.
6511   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6512   //    so the shuffle can be broken into other shuffles and the legalizer can
6513   //    try the lowering again.
6514   //
6515   // The general idea is that no vector_shuffle operation should be left to
6516   // be matched during isel, all of them must be converted to a target specific
6517   // node here.
6518
6519   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6520   // narrowing and commutation of operands should be handled. The actual code
6521   // doesn't include all of those, work in progress...
6522   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6523   if (NewOp.getNode())
6524     return NewOp;
6525
6526   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6527
6528   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6529   // unpckh_undef). Only use pshufd if speed is more important than size.
6530   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6531     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6532   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6533     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6534
6535   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6536       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6537     return getMOVDDup(Op, dl, V1, DAG);
6538
6539   if (isMOVHLPS_v_undef_Mask(M, VT))
6540     return getMOVHighToLow(Op, dl, DAG);
6541
6542   // Use to match splats
6543   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6544       (VT == MVT::v2f64 || VT == MVT::v2i64))
6545     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6546
6547   if (isPSHUFDMask(M, VT)) {
6548     // The actual implementation will match the mask in the if above and then
6549     // during isel it can match several different instructions, not only pshufd
6550     // as its name says, sad but true, emulate the behavior for now...
6551     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6552       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6553
6554     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6555
6556     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6557       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6558
6559     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6560       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6561
6562     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6563                                 TargetMask, DAG);
6564   }
6565
6566   // Check if this can be converted into a logical shift.
6567   bool isLeft = false;
6568   unsigned ShAmt = 0;
6569   SDValue ShVal;
6570   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6571   if (isShift && ShVal.hasOneUse()) {
6572     // If the shifted value has multiple uses, it may be cheaper to use
6573     // v_set0 + movlhps or movhlps, etc.
6574     EVT EltVT = VT.getVectorElementType();
6575     ShAmt *= EltVT.getSizeInBits();
6576     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6577   }
6578
6579   if (isMOVLMask(M, VT)) {
6580     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6581       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6582     if (!isMOVLPMask(M, VT)) {
6583       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6584         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6585
6586       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6587         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6588     }
6589   }
6590
6591   // FIXME: fold these into legal mask.
6592   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6593     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6594
6595   if (isMOVHLPSMask(M, VT))
6596     return getMOVHighToLow(Op, dl, DAG);
6597
6598   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6599     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6600
6601   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6602     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6603
6604   if (isMOVLPMask(M, VT))
6605     return getMOVLP(Op, dl, DAG, HasSSE2);
6606
6607   if (ShouldXformToMOVHLPS(M, VT) ||
6608       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6609     return CommuteVectorShuffle(SVOp, DAG);
6610
6611   if (isShift) {
6612     // No better options. Use a vshldq / vsrldq.
6613     EVT EltVT = VT.getVectorElementType();
6614     ShAmt *= EltVT.getSizeInBits();
6615     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6616   }
6617
6618   bool Commuted = false;
6619   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6620   // 1,1,1,1 -> v8i16 though.
6621   V1IsSplat = isSplatVector(V1.getNode());
6622   V2IsSplat = isSplatVector(V2.getNode());
6623
6624   // Canonicalize the splat or undef, if present, to be on the RHS.
6625   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6626     CommuteVectorShuffleMask(M, NumElems);
6627     std::swap(V1, V2);
6628     std::swap(V1IsSplat, V2IsSplat);
6629     Commuted = true;
6630   }
6631
6632   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6633     // Shuffling low element of v1 into undef, just return v1.
6634     if (V2IsUndef)
6635       return V1;
6636     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6637     // the instruction selector will not match, so get a canonical MOVL with
6638     // swapped operands to undo the commute.
6639     return getMOVL(DAG, dl, VT, V2, V1);
6640   }
6641
6642   if (isUNPCKLMask(M, VT, HasAVX2))
6643     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6644
6645   if (isUNPCKHMask(M, VT, HasAVX2))
6646     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6647
6648   if (V2IsSplat) {
6649     // Normalize mask so all entries that point to V2 points to its first
6650     // element then try to match unpck{h|l} again. If match, return a
6651     // new vector_shuffle with the corrected mask.p
6652     SmallVector<int, 8> NewMask(M.begin(), M.end());
6653     NormalizeMask(NewMask, NumElems);
6654     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6655       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6656     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6657       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6658   }
6659
6660   if (Commuted) {
6661     // Commute is back and try unpck* again.
6662     // FIXME: this seems wrong.
6663     CommuteVectorShuffleMask(M, NumElems);
6664     std::swap(V1, V2);
6665     std::swap(V1IsSplat, V2IsSplat);
6666     Commuted = false;
6667
6668     if (isUNPCKLMask(M, VT, HasAVX2))
6669       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6670
6671     if (isUNPCKHMask(M, VT, HasAVX2))
6672       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6673   }
6674
6675   // Normalize the node to match x86 shuffle ops if needed
6676   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6677     return CommuteVectorShuffle(SVOp, DAG);
6678
6679   // The checks below are all present in isShuffleMaskLegal, but they are
6680   // inlined here right now to enable us to directly emit target specific
6681   // nodes, and remove one by one until they don't return Op anymore.
6682
6683   if (isPALIGNRMask(M, VT, Subtarget))
6684     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6685                                 getShufflePALIGNRImmediate(SVOp),
6686                                 DAG);
6687
6688   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6689       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6690     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6691       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6692   }
6693
6694   if (isPSHUFHWMask(M, VT, HasAVX2))
6695     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6696                                 getShufflePSHUFHWImmediate(SVOp),
6697                                 DAG);
6698
6699   if (isPSHUFLWMask(M, VT, HasAVX2))
6700     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6701                                 getShufflePSHUFLWImmediate(SVOp),
6702                                 DAG);
6703
6704   if (isSHUFPMask(M, VT, HasAVX))
6705     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6706                                 getShuffleSHUFImmediate(SVOp), DAG);
6707
6708   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6709     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6710   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6711     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6712
6713   //===--------------------------------------------------------------------===//
6714   // Generate target specific nodes for 128 or 256-bit shuffles only
6715   // supported in the AVX instruction set.
6716   //
6717
6718   // Handle VMOVDDUPY permutations
6719   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6720     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6721
6722   // Handle VPERMILPS/D* permutations
6723   if (isVPERMILPMask(M, VT, HasAVX)) {
6724     if (HasAVX2 && VT == MVT::v8i32)
6725       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6726                                   getShuffleSHUFImmediate(SVOp), DAG);
6727     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6728                                 getShuffleSHUFImmediate(SVOp), DAG);
6729   }
6730
6731   // Handle VPERM2F128/VPERM2I128 permutations
6732   if (isVPERM2X128Mask(M, VT, HasAVX))
6733     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6734                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6735
6736   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6737   if (BlendOp.getNode())
6738     return BlendOp;
6739
6740   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6741     SmallVector<SDValue, 8> permclMask;
6742     for (unsigned i = 0; i != 8; ++i) {
6743       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6744     }
6745     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6746                                &permclMask[0], 8);
6747     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6748     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6749                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6750   }
6751
6752   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6753     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6754                                 getShuffleCLImmediate(SVOp), DAG);
6755
6756
6757   //===--------------------------------------------------------------------===//
6758   // Since no target specific shuffle was selected for this generic one,
6759   // lower it into other known shuffles. FIXME: this isn't true yet, but
6760   // this is the plan.
6761   //
6762
6763   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6764   if (VT == MVT::v8i16) {
6765     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6766     if (NewOp.getNode())
6767       return NewOp;
6768   }
6769
6770   if (VT == MVT::v16i8) {
6771     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6772     if (NewOp.getNode())
6773       return NewOp;
6774   }
6775
6776   // Handle all 128-bit wide vectors with 4 elements, and match them with
6777   // several different shuffle types.
6778   if (NumElems == 4 && VT.getSizeInBits() == 128)
6779     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6780
6781   // Handle general 256-bit shuffles
6782   if (VT.is256BitVector())
6783     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6784
6785   return SDValue();
6786 }
6787
6788 SDValue
6789 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6790                                                 SelectionDAG &DAG) const {
6791   EVT VT = Op.getValueType();
6792   DebugLoc dl = Op.getDebugLoc();
6793
6794   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6795     return SDValue();
6796
6797   if (VT.getSizeInBits() == 8) {
6798     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6799                                     Op.getOperand(0), Op.getOperand(1));
6800     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6801                                     DAG.getValueType(VT));
6802     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6803   }
6804
6805   if (VT.getSizeInBits() == 16) {
6806     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6807     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6808     if (Idx == 0)
6809       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6810                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6811                                      DAG.getNode(ISD::BITCAST, dl,
6812                                                  MVT::v4i32,
6813                                                  Op.getOperand(0)),
6814                                      Op.getOperand(1)));
6815     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6816                                     Op.getOperand(0), Op.getOperand(1));
6817     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6818                                     DAG.getValueType(VT));
6819     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6820   }
6821
6822   if (VT == MVT::f32) {
6823     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6824     // the result back to FR32 register. It's only worth matching if the
6825     // result has a single use which is a store or a bitcast to i32.  And in
6826     // the case of a store, it's not worth it if the index is a constant 0,
6827     // because a MOVSSmr can be used instead, which is smaller and faster.
6828     if (!Op.hasOneUse())
6829       return SDValue();
6830     SDNode *User = *Op.getNode()->use_begin();
6831     if ((User->getOpcode() != ISD::STORE ||
6832          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6833           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6834         (User->getOpcode() != ISD::BITCAST ||
6835          User->getValueType(0) != MVT::i32))
6836       return SDValue();
6837     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6838                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6839                                               Op.getOperand(0)),
6840                                               Op.getOperand(1));
6841     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6842   }
6843
6844   if (VT == MVT::i32 || VT == MVT::i64) {
6845     // ExtractPS/pextrq works with constant index.
6846     if (isa<ConstantSDNode>(Op.getOperand(1)))
6847       return Op;
6848   }
6849   return SDValue();
6850 }
6851
6852
6853 SDValue
6854 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6855                                            SelectionDAG &DAG) const {
6856   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6857     return SDValue();
6858
6859   SDValue Vec = Op.getOperand(0);
6860   EVT VecVT = Vec.getValueType();
6861
6862   // If this is a 256-bit vector result, first extract the 128-bit vector and
6863   // then extract the element from the 128-bit vector.
6864   if (VecVT.getSizeInBits() == 256) {
6865     DebugLoc dl = Op.getNode()->getDebugLoc();
6866     unsigned NumElems = VecVT.getVectorNumElements();
6867     SDValue Idx = Op.getOperand(1);
6868     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6869
6870     // Get the 128-bit vector.
6871     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6872
6873     if (IdxVal >= NumElems/2)
6874       IdxVal -= NumElems/2;
6875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6876                        DAG.getConstant(IdxVal, MVT::i32));
6877   }
6878
6879   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6880
6881   if (Subtarget->hasSSE41()) {
6882     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6883     if (Res.getNode())
6884       return Res;
6885   }
6886
6887   EVT VT = Op.getValueType();
6888   DebugLoc dl = Op.getDebugLoc();
6889   // TODO: handle v16i8.
6890   if (VT.getSizeInBits() == 16) {
6891     SDValue Vec = Op.getOperand(0);
6892     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6893     if (Idx == 0)
6894       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6895                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6896                                      DAG.getNode(ISD::BITCAST, dl,
6897                                                  MVT::v4i32, Vec),
6898                                      Op.getOperand(1)));
6899     // Transform it so it match pextrw which produces a 32-bit result.
6900     EVT EltVT = MVT::i32;
6901     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6902                                     Op.getOperand(0), Op.getOperand(1));
6903     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6904                                     DAG.getValueType(VT));
6905     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6906   }
6907
6908   if (VT.getSizeInBits() == 32) {
6909     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6910     if (Idx == 0)
6911       return Op;
6912
6913     // SHUFPS the element to the lowest double word, then movss.
6914     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6915     EVT VVT = Op.getOperand(0).getValueType();
6916     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6917                                        DAG.getUNDEF(VVT), Mask);
6918     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6919                        DAG.getIntPtrConstant(0));
6920   }
6921
6922   if (VT.getSizeInBits() == 64) {
6923     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6924     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6925     //        to match extract_elt for f64.
6926     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6927     if (Idx == 0)
6928       return Op;
6929
6930     // UNPCKHPD the element to the lowest double word, then movsd.
6931     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6932     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6933     int Mask[2] = { 1, -1 };
6934     EVT VVT = Op.getOperand(0).getValueType();
6935     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6936                                        DAG.getUNDEF(VVT), Mask);
6937     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6938                        DAG.getIntPtrConstant(0));
6939   }
6940
6941   return SDValue();
6942 }
6943
6944 SDValue
6945 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6946                                                SelectionDAG &DAG) const {
6947   EVT VT = Op.getValueType();
6948   EVT EltVT = VT.getVectorElementType();
6949   DebugLoc dl = Op.getDebugLoc();
6950
6951   SDValue N0 = Op.getOperand(0);
6952   SDValue N1 = Op.getOperand(1);
6953   SDValue N2 = Op.getOperand(2);
6954
6955   if (VT.getSizeInBits() == 256)
6956     return SDValue();
6957
6958   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6959       isa<ConstantSDNode>(N2)) {
6960     unsigned Opc;
6961     if (VT == MVT::v8i16)
6962       Opc = X86ISD::PINSRW;
6963     else if (VT == MVT::v16i8)
6964       Opc = X86ISD::PINSRB;
6965     else
6966       Opc = X86ISD::PINSRB;
6967
6968     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6969     // argument.
6970     if (N1.getValueType() != MVT::i32)
6971       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6972     if (N2.getValueType() != MVT::i32)
6973       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6974     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6975   }
6976
6977   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6978     // Bits [7:6] of the constant are the source select.  This will always be
6979     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6980     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6981     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6982     // Bits [5:4] of the constant are the destination select.  This is the
6983     //  value of the incoming immediate.
6984     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6985     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6986     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6987     // Create this as a scalar to vector..
6988     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6989     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6990   }
6991
6992   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6993     // PINSR* works with constant index.
6994     return Op;
6995   }
6996   return SDValue();
6997 }
6998
6999 SDValue
7000 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7001   EVT VT = Op.getValueType();
7002   EVT EltVT = VT.getVectorElementType();
7003
7004   DebugLoc dl = Op.getDebugLoc();
7005   SDValue N0 = Op.getOperand(0);
7006   SDValue N1 = Op.getOperand(1);
7007   SDValue N2 = Op.getOperand(2);
7008
7009   // If this is a 256-bit vector result, first extract the 128-bit vector,
7010   // insert the element into the extracted half and then place it back.
7011   if (VT.getSizeInBits() == 256) {
7012     if (!isa<ConstantSDNode>(N2))
7013       return SDValue();
7014
7015     // Get the desired 128-bit vector half.
7016     unsigned NumElems = VT.getVectorNumElements();
7017     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7018     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7019
7020     // Insert the element into the desired half.
7021     bool Upper = IdxVal >= NumElems/2;
7022     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7023                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7024
7025     // Insert the changed part back to the 256-bit vector
7026     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7027   }
7028
7029   if (Subtarget->hasSSE41())
7030     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7031
7032   if (EltVT == MVT::i8)
7033     return SDValue();
7034
7035   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7036     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7037     // as its second argument.
7038     if (N1.getValueType() != MVT::i32)
7039       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7040     if (N2.getValueType() != MVT::i32)
7041       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7042     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7043   }
7044   return SDValue();
7045 }
7046
7047 SDValue
7048 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7049   LLVMContext *Context = DAG.getContext();
7050   DebugLoc dl = Op.getDebugLoc();
7051   EVT OpVT = Op.getValueType();
7052
7053   // If this is a 256-bit vector result, first insert into a 128-bit
7054   // vector and then insert into the 256-bit vector.
7055   if (OpVT.getSizeInBits() > 128) {
7056     // Insert into a 128-bit vector.
7057     EVT VT128 = EVT::getVectorVT(*Context,
7058                                  OpVT.getVectorElementType(),
7059                                  OpVT.getVectorNumElements() / 2);
7060
7061     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7062
7063     // Insert the 128-bit vector.
7064     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7065   }
7066
7067   if (OpVT == MVT::v1i64 &&
7068       Op.getOperand(0).getValueType() == MVT::i64)
7069     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7070
7071   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7072   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7073   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7074                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7075 }
7076
7077 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7078 // a simple subregister reference or explicit instructions to grab
7079 // upper bits of a vector.
7080 SDValue
7081 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7082   if (Subtarget->hasAVX()) {
7083     DebugLoc dl = Op.getNode()->getDebugLoc();
7084     SDValue Vec = Op.getNode()->getOperand(0);
7085     SDValue Idx = Op.getNode()->getOperand(1);
7086
7087     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7088         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7089         isa<ConstantSDNode>(Idx)) {
7090       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7091       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7092     }
7093   }
7094   return SDValue();
7095 }
7096
7097 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7098 // simple superregister reference or explicit instructions to insert
7099 // the upper bits of a vector.
7100 SDValue
7101 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7102   if (Subtarget->hasAVX()) {
7103     DebugLoc dl = Op.getNode()->getDebugLoc();
7104     SDValue Vec = Op.getNode()->getOperand(0);
7105     SDValue SubVec = Op.getNode()->getOperand(1);
7106     SDValue Idx = Op.getNode()->getOperand(2);
7107
7108     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7109         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7110         isa<ConstantSDNode>(Idx)) {
7111       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7112       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7113     }
7114   }
7115   return SDValue();
7116 }
7117
7118 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7119 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7120 // one of the above mentioned nodes. It has to be wrapped because otherwise
7121 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7122 // be used to form addressing mode. These wrapped nodes will be selected
7123 // into MOV32ri.
7124 SDValue
7125 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7126   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7127
7128   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7129   // global base reg.
7130   unsigned char OpFlag = 0;
7131   unsigned WrapperKind = X86ISD::Wrapper;
7132   CodeModel::Model M = getTargetMachine().getCodeModel();
7133
7134   if (Subtarget->isPICStyleRIPRel() &&
7135       (M == CodeModel::Small || M == CodeModel::Kernel))
7136     WrapperKind = X86ISD::WrapperRIP;
7137   else if (Subtarget->isPICStyleGOT())
7138     OpFlag = X86II::MO_GOTOFF;
7139   else if (Subtarget->isPICStyleStubPIC())
7140     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7141
7142   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7143                                              CP->getAlignment(),
7144                                              CP->getOffset(), OpFlag);
7145   DebugLoc DL = CP->getDebugLoc();
7146   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7147   // With PIC, the address is actually $g + Offset.
7148   if (OpFlag) {
7149     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7150                          DAG.getNode(X86ISD::GlobalBaseReg,
7151                                      DebugLoc(), getPointerTy()),
7152                          Result);
7153   }
7154
7155   return Result;
7156 }
7157
7158 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7159   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7160
7161   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7162   // global base reg.
7163   unsigned char OpFlag = 0;
7164   unsigned WrapperKind = X86ISD::Wrapper;
7165   CodeModel::Model M = getTargetMachine().getCodeModel();
7166
7167   if (Subtarget->isPICStyleRIPRel() &&
7168       (M == CodeModel::Small || M == CodeModel::Kernel))
7169     WrapperKind = X86ISD::WrapperRIP;
7170   else if (Subtarget->isPICStyleGOT())
7171     OpFlag = X86II::MO_GOTOFF;
7172   else if (Subtarget->isPICStyleStubPIC())
7173     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7174
7175   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7176                                           OpFlag);
7177   DebugLoc DL = JT->getDebugLoc();
7178   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7179
7180   // With PIC, the address is actually $g + Offset.
7181   if (OpFlag)
7182     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7183                          DAG.getNode(X86ISD::GlobalBaseReg,
7184                                      DebugLoc(), getPointerTy()),
7185                          Result);
7186
7187   return Result;
7188 }
7189
7190 SDValue
7191 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7192   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7193
7194   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7195   // global base reg.
7196   unsigned char OpFlag = 0;
7197   unsigned WrapperKind = X86ISD::Wrapper;
7198   CodeModel::Model M = getTargetMachine().getCodeModel();
7199
7200   if (Subtarget->isPICStyleRIPRel() &&
7201       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7202     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7203       OpFlag = X86II::MO_GOTPCREL;
7204     WrapperKind = X86ISD::WrapperRIP;
7205   } else if (Subtarget->isPICStyleGOT()) {
7206     OpFlag = X86II::MO_GOT;
7207   } else if (Subtarget->isPICStyleStubPIC()) {
7208     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7209   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7210     OpFlag = X86II::MO_DARWIN_NONLAZY;
7211   }
7212
7213   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7214
7215   DebugLoc DL = Op.getDebugLoc();
7216   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7217
7218
7219   // With PIC, the address is actually $g + Offset.
7220   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7221       !Subtarget->is64Bit()) {
7222     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7223                          DAG.getNode(X86ISD::GlobalBaseReg,
7224                                      DebugLoc(), getPointerTy()),
7225                          Result);
7226   }
7227
7228   // For symbols that require a load from a stub to get the address, emit the
7229   // load.
7230   if (isGlobalStubReference(OpFlag))
7231     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7232                          MachinePointerInfo::getGOT(), false, false, false, 0);
7233
7234   return Result;
7235 }
7236
7237 SDValue
7238 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7239   // Create the TargetBlockAddressAddress node.
7240   unsigned char OpFlags =
7241     Subtarget->ClassifyBlockAddressReference();
7242   CodeModel::Model M = getTargetMachine().getCodeModel();
7243   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7244   DebugLoc dl = Op.getDebugLoc();
7245   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7246                                        /*isTarget=*/true, OpFlags);
7247
7248   if (Subtarget->isPICStyleRIPRel() &&
7249       (M == CodeModel::Small || M == CodeModel::Kernel))
7250     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7251   else
7252     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7253
7254   // With PIC, the address is actually $g + Offset.
7255   if (isGlobalRelativeToPICBase(OpFlags)) {
7256     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7257                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7258                          Result);
7259   }
7260
7261   return Result;
7262 }
7263
7264 SDValue
7265 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7266                                       int64_t Offset,
7267                                       SelectionDAG &DAG) const {
7268   // Create the TargetGlobalAddress node, folding in the constant
7269   // offset if it is legal.
7270   unsigned char OpFlags =
7271     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7272   CodeModel::Model M = getTargetMachine().getCodeModel();
7273   SDValue Result;
7274   if (OpFlags == X86II::MO_NO_FLAG &&
7275       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7276     // A direct static reference to a global.
7277     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7278     Offset = 0;
7279   } else {
7280     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7281   }
7282
7283   if (Subtarget->isPICStyleRIPRel() &&
7284       (M == CodeModel::Small || M == CodeModel::Kernel))
7285     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7286   else
7287     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7288
7289   // With PIC, the address is actually $g + Offset.
7290   if (isGlobalRelativeToPICBase(OpFlags)) {
7291     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7292                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7293                          Result);
7294   }
7295
7296   // For globals that require a load from a stub to get the address, emit the
7297   // load.
7298   if (isGlobalStubReference(OpFlags))
7299     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7300                          MachinePointerInfo::getGOT(), false, false, false, 0);
7301
7302   // If there was a non-zero offset that we didn't fold, create an explicit
7303   // addition for it.
7304   if (Offset != 0)
7305     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7306                          DAG.getConstant(Offset, getPointerTy()));
7307
7308   return Result;
7309 }
7310
7311 SDValue
7312 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7313   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7314   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7315   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7316 }
7317
7318 static SDValue
7319 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7320            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7321            unsigned char OperandFlags, bool LocalDynamic = false) {
7322   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7323   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7324   DebugLoc dl = GA->getDebugLoc();
7325   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7326                                            GA->getValueType(0),
7327                                            GA->getOffset(),
7328                                            OperandFlags);
7329
7330   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7331                                            : X86ISD::TLSADDR;
7332
7333   if (InFlag) {
7334     SDValue Ops[] = { Chain,  TGA, *InFlag };
7335     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7336   } else {
7337     SDValue Ops[]  = { Chain, TGA };
7338     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7339   }
7340
7341   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7342   MFI->setAdjustsStack(true);
7343
7344   SDValue Flag = Chain.getValue(1);
7345   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7346 }
7347
7348 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7349 static SDValue
7350 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7351                                 const EVT PtrVT) {
7352   SDValue InFlag;
7353   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7354   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7355                                      DAG.getNode(X86ISD::GlobalBaseReg,
7356                                                  DebugLoc(), PtrVT), InFlag);
7357   InFlag = Chain.getValue(1);
7358
7359   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7360 }
7361
7362 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7363 static SDValue
7364 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7365                                 const EVT PtrVT) {
7366   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7367                     X86::RAX, X86II::MO_TLSGD);
7368 }
7369
7370 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7371                                            SelectionDAG &DAG,
7372                                            const EVT PtrVT,
7373                                            bool is64Bit) {
7374   DebugLoc dl = GA->getDebugLoc();
7375
7376   // Get the start address of the TLS block for this module.
7377   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7378       .getInfo<X86MachineFunctionInfo>();
7379   MFI->incNumLocalDynamicTLSAccesses();
7380
7381   SDValue Base;
7382   if (is64Bit) {
7383     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7384                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7385   } else {
7386     SDValue InFlag;
7387     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7388         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7389     InFlag = Chain.getValue(1);
7390     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7391                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7392   }
7393
7394   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7395   // of Base.
7396
7397   // Build x@dtpoff.
7398   unsigned char OperandFlags = X86II::MO_DTPOFF;
7399   unsigned WrapperKind = X86ISD::Wrapper;
7400   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7401                                            GA->getValueType(0),
7402                                            GA->getOffset(), OperandFlags);
7403   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7404
7405   // Add x@dtpoff with the base.
7406   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7407 }
7408
7409 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7410 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7411                                    const EVT PtrVT, TLSModel::Model model,
7412                                    bool is64Bit, bool isPIC) {
7413   DebugLoc dl = GA->getDebugLoc();
7414
7415   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7416   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7417                                                          is64Bit ? 257 : 256));
7418
7419   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7420                                       DAG.getIntPtrConstant(0),
7421                                       MachinePointerInfo(Ptr),
7422                                       false, false, false, 0);
7423
7424   unsigned char OperandFlags = 0;
7425   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7426   // initialexec.
7427   unsigned WrapperKind = X86ISD::Wrapper;
7428   if (model == TLSModel::LocalExec) {
7429     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7430   } else if (model == TLSModel::InitialExec) {
7431     if (is64Bit) {
7432       OperandFlags = X86II::MO_GOTTPOFF;
7433       WrapperKind = X86ISD::WrapperRIP;
7434     } else {
7435       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7436     }
7437   } else {
7438     llvm_unreachable("Unexpected model");
7439   }
7440
7441   // emit "addl x@ntpoff,%eax" (local exec)
7442   // or "addl x@indntpoff,%eax" (initial exec)
7443   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7444   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7445                                            GA->getValueType(0),
7446                                            GA->getOffset(), OperandFlags);
7447   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7448
7449   if (model == TLSModel::InitialExec) {
7450     if (isPIC && !is64Bit) {
7451       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7452                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7453                            Offset);
7454     }
7455
7456     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7457                          MachinePointerInfo::getGOT(), false, false, false,
7458                          0);
7459   }
7460
7461   // The address of the thread local variable is the add of the thread
7462   // pointer with the offset of the variable.
7463   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7464 }
7465
7466 SDValue
7467 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7468
7469   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7470   const GlobalValue *GV = GA->getGlobal();
7471
7472   if (Subtarget->isTargetELF()) {
7473     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7474
7475     switch (model) {
7476       case TLSModel::GeneralDynamic:
7477         if (Subtarget->is64Bit())
7478           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7479         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7480       case TLSModel::LocalDynamic:
7481         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7482                                            Subtarget->is64Bit());
7483       case TLSModel::InitialExec:
7484       case TLSModel::LocalExec:
7485         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7486                                    Subtarget->is64Bit(),
7487                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7488     }
7489     llvm_unreachable("Unknown TLS model.");
7490   }
7491
7492   if (Subtarget->isTargetDarwin()) {
7493     // Darwin only has one model of TLS.  Lower to that.
7494     unsigned char OpFlag = 0;
7495     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7496                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7497
7498     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7499     // global base reg.
7500     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7501                   !Subtarget->is64Bit();
7502     if (PIC32)
7503       OpFlag = X86II::MO_TLVP_PIC_BASE;
7504     else
7505       OpFlag = X86II::MO_TLVP;
7506     DebugLoc DL = Op.getDebugLoc();
7507     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7508                                                 GA->getValueType(0),
7509                                                 GA->getOffset(), OpFlag);
7510     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7511
7512     // With PIC32, the address is actually $g + Offset.
7513     if (PIC32)
7514       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7515                            DAG.getNode(X86ISD::GlobalBaseReg,
7516                                        DebugLoc(), getPointerTy()),
7517                            Offset);
7518
7519     // Lowering the machine isd will make sure everything is in the right
7520     // location.
7521     SDValue Chain = DAG.getEntryNode();
7522     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7523     SDValue Args[] = { Chain, Offset };
7524     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7525
7526     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7527     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7528     MFI->setAdjustsStack(true);
7529
7530     // And our return value (tls address) is in the standard call return value
7531     // location.
7532     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7533     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7534                               Chain.getValue(1));
7535   }
7536
7537   if (Subtarget->isTargetWindows()) {
7538     // Just use the implicit TLS architecture
7539     // Need to generate someting similar to:
7540     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7541     //                                  ; from TEB
7542     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7543     //   mov     rcx, qword [rdx+rcx*8]
7544     //   mov     eax, .tls$:tlsvar
7545     //   [rax+rcx] contains the address
7546     // Windows 64bit: gs:0x58
7547     // Windows 32bit: fs:__tls_array
7548
7549     // If GV is an alias then use the aliasee for determining
7550     // thread-localness.
7551     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7552       GV = GA->resolveAliasedGlobal(false);
7553     DebugLoc dl = GA->getDebugLoc();
7554     SDValue Chain = DAG.getEntryNode();
7555
7556     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7557     // %gs:0x58 (64-bit).
7558     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7559                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7560                                                              256)
7561                                         : Type::getInt32PtrTy(*DAG.getContext(),
7562                                                               257));
7563
7564     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7565                                         Subtarget->is64Bit()
7566                                         ? DAG.getIntPtrConstant(0x58)
7567                                         : DAG.getExternalSymbol("_tls_array",
7568                                                                 getPointerTy()),
7569                                         MachinePointerInfo(Ptr),
7570                                         false, false, false, 0);
7571
7572     // Load the _tls_index variable
7573     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7574     if (Subtarget->is64Bit())
7575       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7576                            IDX, MachinePointerInfo(), MVT::i32,
7577                            false, false, 0);
7578     else
7579       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7580                         false, false, false, 0);
7581
7582     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7583                                     getPointerTy());
7584     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7585
7586     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7587     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7588                       false, false, false, 0);
7589
7590     // Get the offset of start of .tls section
7591     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7592                                              GA->getValueType(0),
7593                                              GA->getOffset(), X86II::MO_SECREL);
7594     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7595
7596     // The address of the thread local variable is the add of the thread
7597     // pointer with the offset of the variable.
7598     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7599   }
7600
7601   llvm_unreachable("TLS not implemented for this target.");
7602 }
7603
7604
7605 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7606 /// and take a 2 x i32 value to shift plus a shift amount.
7607 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7608   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7609   EVT VT = Op.getValueType();
7610   unsigned VTBits = VT.getSizeInBits();
7611   DebugLoc dl = Op.getDebugLoc();
7612   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7613   SDValue ShOpLo = Op.getOperand(0);
7614   SDValue ShOpHi = Op.getOperand(1);
7615   SDValue ShAmt  = Op.getOperand(2);
7616   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7617                                      DAG.getConstant(VTBits - 1, MVT::i8))
7618                        : DAG.getConstant(0, VT);
7619
7620   SDValue Tmp2, Tmp3;
7621   if (Op.getOpcode() == ISD::SHL_PARTS) {
7622     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7623     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7624   } else {
7625     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7626     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7627   }
7628
7629   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7630                                 DAG.getConstant(VTBits, MVT::i8));
7631   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7632                              AndNode, DAG.getConstant(0, MVT::i8));
7633
7634   SDValue Hi, Lo;
7635   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7636   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7637   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7638
7639   if (Op.getOpcode() == ISD::SHL_PARTS) {
7640     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7641     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7642   } else {
7643     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7644     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7645   }
7646
7647   SDValue Ops[2] = { Lo, Hi };
7648   return DAG.getMergeValues(Ops, 2, dl);
7649 }
7650
7651 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7652                                            SelectionDAG &DAG) const {
7653   EVT SrcVT = Op.getOperand(0).getValueType();
7654
7655   if (SrcVT.isVector())
7656     return SDValue();
7657
7658   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7659          "Unknown SINT_TO_FP to lower!");
7660
7661   // These are really Legal; return the operand so the caller accepts it as
7662   // Legal.
7663   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7664     return Op;
7665   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7666       Subtarget->is64Bit()) {
7667     return Op;
7668   }
7669
7670   DebugLoc dl = Op.getDebugLoc();
7671   unsigned Size = SrcVT.getSizeInBits()/8;
7672   MachineFunction &MF = DAG.getMachineFunction();
7673   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7674   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7675   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7676                                StackSlot,
7677                                MachinePointerInfo::getFixedStack(SSFI),
7678                                false, false, 0);
7679   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7680 }
7681
7682 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7683                                      SDValue StackSlot,
7684                                      SelectionDAG &DAG) const {
7685   // Build the FILD
7686   DebugLoc DL = Op.getDebugLoc();
7687   SDVTList Tys;
7688   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7689   if (useSSE)
7690     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7691   else
7692     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7693
7694   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7695
7696   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7697   MachineMemOperand *MMO;
7698   if (FI) {
7699     int SSFI = FI->getIndex();
7700     MMO =
7701       DAG.getMachineFunction()
7702       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7703                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7704   } else {
7705     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7706     StackSlot = StackSlot.getOperand(1);
7707   }
7708   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7709   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7710                                            X86ISD::FILD, DL,
7711                                            Tys, Ops, array_lengthof(Ops),
7712                                            SrcVT, MMO);
7713
7714   if (useSSE) {
7715     Chain = Result.getValue(1);
7716     SDValue InFlag = Result.getValue(2);
7717
7718     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7719     // shouldn't be necessary except that RFP cannot be live across
7720     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7721     MachineFunction &MF = DAG.getMachineFunction();
7722     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7723     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7724     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7725     Tys = DAG.getVTList(MVT::Other);
7726     SDValue Ops[] = {
7727       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7728     };
7729     MachineMemOperand *MMO =
7730       DAG.getMachineFunction()
7731       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7732                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7733
7734     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7735                                     Ops, array_lengthof(Ops),
7736                                     Op.getValueType(), MMO);
7737     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7738                          MachinePointerInfo::getFixedStack(SSFI),
7739                          false, false, false, 0);
7740   }
7741
7742   return Result;
7743 }
7744
7745 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7746 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7747                                                SelectionDAG &DAG) const {
7748   // This algorithm is not obvious. Here it is what we're trying to output:
7749   /*
7750      movq       %rax,  %xmm0
7751      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7752      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7753      #ifdef __SSE3__
7754        haddpd   %xmm0, %xmm0          
7755      #else
7756        pshufd   $0x4e, %xmm0, %xmm1 
7757        addpd    %xmm1, %xmm0
7758      #endif
7759   */
7760
7761   DebugLoc dl = Op.getDebugLoc();
7762   LLVMContext *Context = DAG.getContext();
7763
7764   // Build some magic constants.
7765   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7766   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7767   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7768
7769   SmallVector<Constant*,2> CV1;
7770   CV1.push_back(
7771         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7772   CV1.push_back(
7773         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7774   Constant *C1 = ConstantVector::get(CV1);
7775   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7776
7777   // Load the 64-bit value into an XMM register.
7778   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7779                             Op.getOperand(0));
7780   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7781                               MachinePointerInfo::getConstantPool(),
7782                               false, false, false, 16);
7783   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7784                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7785                               CLod0);
7786
7787   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7788                               MachinePointerInfo::getConstantPool(),
7789                               false, false, false, 16);
7790   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7791   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7792   SDValue Result;
7793
7794   if (Subtarget->hasSSE3()) {
7795     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7796     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7797   } else {
7798     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7799     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7800                                            S2F, 0x4E, DAG);
7801     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7802                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7803                          Sub);
7804   }
7805
7806   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7807                      DAG.getIntPtrConstant(0));
7808 }
7809
7810 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7811 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7812                                                SelectionDAG &DAG) const {
7813   DebugLoc dl = Op.getDebugLoc();
7814   // FP constant to bias correct the final result.
7815   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7816                                    MVT::f64);
7817
7818   // Load the 32-bit value into an XMM register.
7819   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7820                              Op.getOperand(0));
7821
7822   // Zero out the upper parts of the register.
7823   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7824
7825   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7826                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7827                      DAG.getIntPtrConstant(0));
7828
7829   // Or the load with the bias.
7830   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7831                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7832                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7833                                                    MVT::v2f64, Load)),
7834                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7835                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7836                                                    MVT::v2f64, Bias)));
7837   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7838                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7839                    DAG.getIntPtrConstant(0));
7840
7841   // Subtract the bias.
7842   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7843
7844   // Handle final rounding.
7845   EVT DestVT = Op.getValueType();
7846
7847   if (DestVT.bitsLT(MVT::f64))
7848     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7849                        DAG.getIntPtrConstant(0));
7850   if (DestVT.bitsGT(MVT::f64))
7851     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7852
7853   // Handle final rounding.
7854   return Sub;
7855 }
7856
7857 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7858                                            SelectionDAG &DAG) const {
7859   SDValue N0 = Op.getOperand(0);
7860   DebugLoc dl = Op.getDebugLoc();
7861
7862   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7863   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7864   // the optimization here.
7865   if (DAG.SignBitIsZero(N0))
7866     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7867
7868   EVT SrcVT = N0.getValueType();
7869   EVT DstVT = Op.getValueType();
7870   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7871     return LowerUINT_TO_FP_i64(Op, DAG);
7872   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7873     return LowerUINT_TO_FP_i32(Op, DAG);
7874   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7875     return SDValue();
7876
7877   // Make a 64-bit buffer, and use it to build an FILD.
7878   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7879   if (SrcVT == MVT::i32) {
7880     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7881     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7882                                      getPointerTy(), StackSlot, WordOff);
7883     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7884                                   StackSlot, MachinePointerInfo(),
7885                                   false, false, 0);
7886     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7887                                   OffsetSlot, MachinePointerInfo(),
7888                                   false, false, 0);
7889     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7890     return Fild;
7891   }
7892
7893   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7894   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7895                                StackSlot, MachinePointerInfo(),
7896                                false, false, 0);
7897   // For i64 source, we need to add the appropriate power of 2 if the input
7898   // was negative.  This is the same as the optimization in
7899   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7900   // we must be careful to do the computation in x87 extended precision, not
7901   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7902   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7903   MachineMemOperand *MMO =
7904     DAG.getMachineFunction()
7905     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7906                           MachineMemOperand::MOLoad, 8, 8);
7907
7908   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7909   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7910   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7911                                          MVT::i64, MMO);
7912
7913   APInt FF(32, 0x5F800000ULL);
7914
7915   // Check whether the sign bit is set.
7916   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7917                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7918                                  ISD::SETLT);
7919
7920   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7921   SDValue FudgePtr = DAG.getConstantPool(
7922                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7923                                          getPointerTy());
7924
7925   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7926   SDValue Zero = DAG.getIntPtrConstant(0);
7927   SDValue Four = DAG.getIntPtrConstant(4);
7928   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7929                                Zero, Four);
7930   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7931
7932   // Load the value out, extending it from f32 to f80.
7933   // FIXME: Avoid the extend by constructing the right constant pool?
7934   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7935                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7936                                  MVT::f32, false, false, 4);
7937   // Extend everything to 80 bits to force it to be done on x87.
7938   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7939   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7940 }
7941
7942 std::pair<SDValue,SDValue> X86TargetLowering::
7943 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7944   DebugLoc DL = Op.getDebugLoc();
7945
7946   EVT DstTy = Op.getValueType();
7947
7948   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7949     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7950     DstTy = MVT::i64;
7951   }
7952
7953   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7954          DstTy.getSimpleVT() >= MVT::i16 &&
7955          "Unknown FP_TO_INT to lower!");
7956
7957   // These are really Legal.
7958   if (DstTy == MVT::i32 &&
7959       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7960     return std::make_pair(SDValue(), SDValue());
7961   if (Subtarget->is64Bit() &&
7962       DstTy == MVT::i64 &&
7963       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7964     return std::make_pair(SDValue(), SDValue());
7965
7966   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7967   // stack slot, or into the FTOL runtime function.
7968   MachineFunction &MF = DAG.getMachineFunction();
7969   unsigned MemSize = DstTy.getSizeInBits()/8;
7970   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7971   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7972
7973   unsigned Opc;
7974   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7975     Opc = X86ISD::WIN_FTOL;
7976   else
7977     switch (DstTy.getSimpleVT().SimpleTy) {
7978     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7979     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7980     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7981     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7982     }
7983
7984   SDValue Chain = DAG.getEntryNode();
7985   SDValue Value = Op.getOperand(0);
7986   EVT TheVT = Op.getOperand(0).getValueType();
7987   // FIXME This causes a redundant load/store if the SSE-class value is already
7988   // in memory, such as if it is on the callstack.
7989   if (isScalarFPTypeInSSEReg(TheVT)) {
7990     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7991     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7992                          MachinePointerInfo::getFixedStack(SSFI),
7993                          false, false, 0);
7994     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7995     SDValue Ops[] = {
7996       Chain, StackSlot, DAG.getValueType(TheVT)
7997     };
7998
7999     MachineMemOperand *MMO =
8000       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8001                               MachineMemOperand::MOLoad, MemSize, MemSize);
8002     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8003                                     DstTy, MMO);
8004     Chain = Value.getValue(1);
8005     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8006     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8007   }
8008
8009   MachineMemOperand *MMO =
8010     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8011                             MachineMemOperand::MOStore, MemSize, MemSize);
8012
8013   if (Opc != X86ISD::WIN_FTOL) {
8014     // Build the FP_TO_INT*_IN_MEM
8015     SDValue Ops[] = { Chain, Value, StackSlot };
8016     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8017                                            Ops, 3, DstTy, MMO);
8018     return std::make_pair(FIST, StackSlot);
8019   } else {
8020     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8021       DAG.getVTList(MVT::Other, MVT::Glue),
8022       Chain, Value);
8023     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8024       MVT::i32, ftol.getValue(1));
8025     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8026       MVT::i32, eax.getValue(2));
8027     SDValue Ops[] = { eax, edx };
8028     SDValue pair = IsReplace
8029       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8030       : DAG.getMergeValues(Ops, 2, DL);
8031     return std::make_pair(pair, SDValue());
8032   }
8033 }
8034
8035 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8036                                            SelectionDAG &DAG) const {
8037   if (Op.getValueType().isVector())
8038     return SDValue();
8039
8040   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8041     /*IsSigned=*/ true, /*IsReplace=*/ false);
8042   SDValue FIST = Vals.first, StackSlot = Vals.second;
8043   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8044   if (FIST.getNode() == 0) return Op;
8045
8046   if (StackSlot.getNode())
8047     // Load the result.
8048     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8049                        FIST, StackSlot, MachinePointerInfo(),
8050                        false, false, false, 0);
8051
8052   // The node is the result.
8053   return FIST;
8054 }
8055
8056 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8057                                            SelectionDAG &DAG) const {
8058   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8059     /*IsSigned=*/ false, /*IsReplace=*/ false);
8060   SDValue FIST = Vals.first, StackSlot = Vals.second;
8061   assert(FIST.getNode() && "Unexpected failure");
8062
8063   if (StackSlot.getNode())
8064     // Load the result.
8065     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8066                        FIST, StackSlot, MachinePointerInfo(),
8067                        false, false, false, 0);
8068
8069   // The node is the result.
8070   return FIST;
8071 }
8072
8073 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8074                                      SelectionDAG &DAG) const {
8075   LLVMContext *Context = DAG.getContext();
8076   DebugLoc dl = Op.getDebugLoc();
8077   EVT VT = Op.getValueType();
8078   EVT EltVT = VT;
8079   if (VT.isVector())
8080     EltVT = VT.getVectorElementType();
8081   Constant *C;
8082   if (EltVT == MVT::f64) {
8083     C = ConstantVector::getSplat(2, 
8084                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8085   } else {
8086     C = ConstantVector::getSplat(4,
8087                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8088   }
8089   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8090   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8091                              MachinePointerInfo::getConstantPool(),
8092                              false, false, false, 16);
8093   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8094 }
8095
8096 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8097   LLVMContext *Context = DAG.getContext();
8098   DebugLoc dl = Op.getDebugLoc();
8099   EVT VT = Op.getValueType();
8100   EVT EltVT = VT;
8101   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8102   if (VT.isVector()) {
8103     EltVT = VT.getVectorElementType();
8104     NumElts = VT.getVectorNumElements();
8105   }
8106   Constant *C;
8107   if (EltVT == MVT::f64)
8108     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8109   else
8110     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8111   C = ConstantVector::getSplat(NumElts, C);
8112   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8113   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8114                              MachinePointerInfo::getConstantPool(),
8115                              false, false, false, 16);
8116   if (VT.isVector()) {
8117     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8118     return DAG.getNode(ISD::BITCAST, dl, VT,
8119                        DAG.getNode(ISD::XOR, dl, XORVT,
8120                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8121                                                Op.getOperand(0)),
8122                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8123   }
8124
8125   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8126 }
8127
8128 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8129   LLVMContext *Context = DAG.getContext();
8130   SDValue Op0 = Op.getOperand(0);
8131   SDValue Op1 = Op.getOperand(1);
8132   DebugLoc dl = Op.getDebugLoc();
8133   EVT VT = Op.getValueType();
8134   EVT SrcVT = Op1.getValueType();
8135
8136   // If second operand is smaller, extend it first.
8137   if (SrcVT.bitsLT(VT)) {
8138     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8139     SrcVT = VT;
8140   }
8141   // And if it is bigger, shrink it first.
8142   if (SrcVT.bitsGT(VT)) {
8143     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8144     SrcVT = VT;
8145   }
8146
8147   // At this point the operands and the result should have the same
8148   // type, and that won't be f80 since that is not custom lowered.
8149
8150   // First get the sign bit of second operand.
8151   SmallVector<Constant*,4> CV;
8152   if (SrcVT == MVT::f64) {
8153     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8154     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8155   } else {
8156     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8157     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8158     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8159     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8160   }
8161   Constant *C = ConstantVector::get(CV);
8162   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8163   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8164                               MachinePointerInfo::getConstantPool(),
8165                               false, false, false, 16);
8166   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8167
8168   // Shift sign bit right or left if the two operands have different types.
8169   if (SrcVT.bitsGT(VT)) {
8170     // Op0 is MVT::f32, Op1 is MVT::f64.
8171     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8172     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8173                           DAG.getConstant(32, MVT::i32));
8174     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8175     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8176                           DAG.getIntPtrConstant(0));
8177   }
8178
8179   // Clear first operand sign bit.
8180   CV.clear();
8181   if (VT == MVT::f64) {
8182     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8183     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8184   } else {
8185     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8186     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8187     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8188     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8189   }
8190   C = ConstantVector::get(CV);
8191   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8192   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8193                               MachinePointerInfo::getConstantPool(),
8194                               false, false, false, 16);
8195   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8196
8197   // Or the value with the sign bit.
8198   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8199 }
8200
8201 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8202   SDValue N0 = Op.getOperand(0);
8203   DebugLoc dl = Op.getDebugLoc();
8204   EVT VT = Op.getValueType();
8205
8206   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8207   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8208                                   DAG.getConstant(1, VT));
8209   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8210 }
8211
8212 /// Emit nodes that will be selected as "test Op0,Op0", or something
8213 /// equivalent.
8214 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8215                                     SelectionDAG &DAG) const {
8216   DebugLoc dl = Op.getDebugLoc();
8217
8218   // CF and OF aren't always set the way we want. Determine which
8219   // of these we need.
8220   bool NeedCF = false;
8221   bool NeedOF = false;
8222   switch (X86CC) {
8223   default: break;
8224   case X86::COND_A: case X86::COND_AE:
8225   case X86::COND_B: case X86::COND_BE:
8226     NeedCF = true;
8227     break;
8228   case X86::COND_G: case X86::COND_GE:
8229   case X86::COND_L: case X86::COND_LE:
8230   case X86::COND_O: case X86::COND_NO:
8231     NeedOF = true;
8232     break;
8233   }
8234
8235   // See if we can use the EFLAGS value from the operand instead of
8236   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8237   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8238   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8239     // Emit a CMP with 0, which is the TEST pattern.
8240     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8241                        DAG.getConstant(0, Op.getValueType()));
8242
8243   unsigned Opcode = 0;
8244   unsigned NumOperands = 0;
8245   switch (Op.getNode()->getOpcode()) {
8246   case ISD::ADD:
8247     // Due to an isel shortcoming, be conservative if this add is likely to be
8248     // selected as part of a load-modify-store instruction. When the root node
8249     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8250     // uses of other nodes in the match, such as the ADD in this case. This
8251     // leads to the ADD being left around and reselected, with the result being
8252     // two adds in the output.  Alas, even if none our users are stores, that
8253     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8254     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8255     // climbing the DAG back to the root, and it doesn't seem to be worth the
8256     // effort.
8257     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8258          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8259       if (UI->getOpcode() != ISD::CopyToReg &&
8260           UI->getOpcode() != ISD::SETCC &&
8261           UI->getOpcode() != ISD::STORE)
8262         goto default_case;
8263
8264     if (ConstantSDNode *C =
8265         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8266       // An add of one will be selected as an INC.
8267       if (C->getAPIntValue() == 1) {
8268         Opcode = X86ISD::INC;
8269         NumOperands = 1;
8270         break;
8271       }
8272
8273       // An add of negative one (subtract of one) will be selected as a DEC.
8274       if (C->getAPIntValue().isAllOnesValue()) {
8275         Opcode = X86ISD::DEC;
8276         NumOperands = 1;
8277         break;
8278       }
8279     }
8280
8281     // Otherwise use a regular EFLAGS-setting add.
8282     Opcode = X86ISD::ADD;
8283     NumOperands = 2;
8284     break;
8285   case ISD::AND: {
8286     // If the primary and result isn't used, don't bother using X86ISD::AND,
8287     // because a TEST instruction will be better.
8288     bool NonFlagUse = false;
8289     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8290            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8291       SDNode *User = *UI;
8292       unsigned UOpNo = UI.getOperandNo();
8293       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8294         // Look pass truncate.
8295         UOpNo = User->use_begin().getOperandNo();
8296         User = *User->use_begin();
8297       }
8298
8299       if (User->getOpcode() != ISD::BRCOND &&
8300           User->getOpcode() != ISD::SETCC &&
8301           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8302         NonFlagUse = true;
8303         break;
8304       }
8305     }
8306
8307     if (!NonFlagUse)
8308       break;
8309   }
8310     // FALL THROUGH
8311   case ISD::SUB:
8312   case ISD::OR:
8313   case ISD::XOR:
8314     // Due to the ISEL shortcoming noted above, be conservative if this op is
8315     // likely to be selected as part of a load-modify-store instruction.
8316     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8317            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8318       if (UI->getOpcode() == ISD::STORE)
8319         goto default_case;
8320
8321     // Otherwise use a regular EFLAGS-setting instruction.
8322     switch (Op.getNode()->getOpcode()) {
8323     default: llvm_unreachable("unexpected operator!");
8324     case ISD::SUB:
8325       // If the only use of SUB is EFLAGS, use CMP instead.
8326       if (Op.hasOneUse())
8327         Opcode = X86ISD::CMP;
8328       else
8329         Opcode = X86ISD::SUB;
8330       break;
8331     case ISD::OR:  Opcode = X86ISD::OR;  break;
8332     case ISD::XOR: Opcode = X86ISD::XOR; break;
8333     case ISD::AND: Opcode = X86ISD::AND; break;
8334     }
8335
8336     NumOperands = 2;
8337     break;
8338   case X86ISD::ADD:
8339   case X86ISD::SUB:
8340   case X86ISD::INC:
8341   case X86ISD::DEC:
8342   case X86ISD::OR:
8343   case X86ISD::XOR:
8344   case X86ISD::AND:
8345     return SDValue(Op.getNode(), 1);
8346   default:
8347   default_case:
8348     break;
8349   }
8350
8351   if (Opcode == 0)
8352     // Emit a CMP with 0, which is the TEST pattern.
8353     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8354                        DAG.getConstant(0, Op.getValueType()));
8355
8356   if (Opcode == X86ISD::CMP) {
8357     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8358                               Op.getOperand(1));
8359     // We can't replace usage of SUB with CMP.
8360     // The SUB node will be removed later because there is no use of it.
8361     return SDValue(New.getNode(), 0);
8362   }
8363
8364   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8365   SmallVector<SDValue, 4> Ops;
8366   for (unsigned i = 0; i != NumOperands; ++i)
8367     Ops.push_back(Op.getOperand(i));
8368
8369   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8370   DAG.ReplaceAllUsesWith(Op, New);
8371   return SDValue(New.getNode(), 1);
8372 }
8373
8374 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8375 /// equivalent.
8376 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8377                                    SelectionDAG &DAG) const {
8378   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8379     if (C->getAPIntValue() == 0)
8380       return EmitTest(Op0, X86CC, DAG);
8381
8382   DebugLoc dl = Op0.getDebugLoc();
8383   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8384 }
8385
8386 /// Convert a comparison if required by the subtarget.
8387 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8388                                                  SelectionDAG &DAG) const {
8389   // If the subtarget does not support the FUCOMI instruction, floating-point
8390   // comparisons have to be converted.
8391   if (Subtarget->hasCMov() ||
8392       Cmp.getOpcode() != X86ISD::CMP ||
8393       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8394       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8395     return Cmp;
8396
8397   // The instruction selector will select an FUCOM instruction instead of
8398   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8399   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8400   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8401   DebugLoc dl = Cmp.getDebugLoc();
8402   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8403   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8404   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8405                             DAG.getConstant(8, MVT::i8));
8406   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8407   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8408 }
8409
8410 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8411 /// if it's possible.
8412 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8413                                      DebugLoc dl, SelectionDAG &DAG) const {
8414   SDValue Op0 = And.getOperand(0);
8415   SDValue Op1 = And.getOperand(1);
8416   if (Op0.getOpcode() == ISD::TRUNCATE)
8417     Op0 = Op0.getOperand(0);
8418   if (Op1.getOpcode() == ISD::TRUNCATE)
8419     Op1 = Op1.getOperand(0);
8420
8421   SDValue LHS, RHS;
8422   if (Op1.getOpcode() == ISD::SHL)
8423     std::swap(Op0, Op1);
8424   if (Op0.getOpcode() == ISD::SHL) {
8425     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8426       if (And00C->getZExtValue() == 1) {
8427         // If we looked past a truncate, check that it's only truncating away
8428         // known zeros.
8429         unsigned BitWidth = Op0.getValueSizeInBits();
8430         unsigned AndBitWidth = And.getValueSizeInBits();
8431         if (BitWidth > AndBitWidth) {
8432           APInt Zeros, Ones;
8433           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8434           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8435             return SDValue();
8436         }
8437         LHS = Op1;
8438         RHS = Op0.getOperand(1);
8439       }
8440   } else if (Op1.getOpcode() == ISD::Constant) {
8441     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8442     uint64_t AndRHSVal = AndRHS->getZExtValue();
8443     SDValue AndLHS = Op0;
8444
8445     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8446       LHS = AndLHS.getOperand(0);
8447       RHS = AndLHS.getOperand(1);
8448     }
8449
8450     // Use BT if the immediate can't be encoded in a TEST instruction.
8451     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8452       LHS = AndLHS;
8453       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8454     }
8455   }
8456
8457   if (LHS.getNode()) {
8458     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8459     // instruction.  Since the shift amount is in-range-or-undefined, we know
8460     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8461     // the encoding for the i16 version is larger than the i32 version.
8462     // Also promote i16 to i32 for performance / code size reason.
8463     if (LHS.getValueType() == MVT::i8 ||
8464         LHS.getValueType() == MVT::i16)
8465       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8466
8467     // If the operand types disagree, extend the shift amount to match.  Since
8468     // BT ignores high bits (like shifts) we can use anyextend.
8469     if (LHS.getValueType() != RHS.getValueType())
8470       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8471
8472     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8473     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8474     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8475                        DAG.getConstant(Cond, MVT::i8), BT);
8476   }
8477
8478   return SDValue();
8479 }
8480
8481 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8482
8483   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8484
8485   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8486   SDValue Op0 = Op.getOperand(0);
8487   SDValue Op1 = Op.getOperand(1);
8488   DebugLoc dl = Op.getDebugLoc();
8489   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8490
8491   // Optimize to BT if possible.
8492   // Lower (X & (1 << N)) == 0 to BT(X, N).
8493   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8494   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8495   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8496       Op1.getOpcode() == ISD::Constant &&
8497       cast<ConstantSDNode>(Op1)->isNullValue() &&
8498       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8499     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8500     if (NewSetCC.getNode())
8501       return NewSetCC;
8502   }
8503
8504   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8505   // these.
8506   if (Op1.getOpcode() == ISD::Constant &&
8507       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8508        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8509       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8510
8511     // If the input is a setcc, then reuse the input setcc or use a new one with
8512     // the inverted condition.
8513     if (Op0.getOpcode() == X86ISD::SETCC) {
8514       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8515       bool Invert = (CC == ISD::SETNE) ^
8516         cast<ConstantSDNode>(Op1)->isNullValue();
8517       if (!Invert) return Op0;
8518
8519       CCode = X86::GetOppositeBranchCondition(CCode);
8520       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8521                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8522     }
8523   }
8524
8525   bool isFP = Op1.getValueType().isFloatingPoint();
8526   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8527   if (X86CC == X86::COND_INVALID)
8528     return SDValue();
8529
8530   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8531   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8532   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8533                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8534 }
8535
8536 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8537 // ones, and then concatenate the result back.
8538 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8539   EVT VT = Op.getValueType();
8540
8541   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8542          "Unsupported value type for operation");
8543
8544   unsigned NumElems = VT.getVectorNumElements();
8545   DebugLoc dl = Op.getDebugLoc();
8546   SDValue CC = Op.getOperand(2);
8547
8548   // Extract the LHS vectors
8549   SDValue LHS = Op.getOperand(0);
8550   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8551   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8552
8553   // Extract the RHS vectors
8554   SDValue RHS = Op.getOperand(1);
8555   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8556   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8557
8558   // Issue the operation on the smaller types and concatenate the result back
8559   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8560   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8561   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8562                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8563                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8564 }
8565
8566
8567 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8568   SDValue Cond;
8569   SDValue Op0 = Op.getOperand(0);
8570   SDValue Op1 = Op.getOperand(1);
8571   SDValue CC = Op.getOperand(2);
8572   EVT VT = Op.getValueType();
8573   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8574   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8575   DebugLoc dl = Op.getDebugLoc();
8576
8577   if (isFP) {
8578     unsigned SSECC = 8;
8579     EVT EltVT = Op0.getValueType().getVectorElementType();
8580     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8581
8582     bool Swap = false;
8583
8584     // SSE Condition code mapping:
8585     //  0 - EQ
8586     //  1 - LT
8587     //  2 - LE
8588     //  3 - UNORD
8589     //  4 - NEQ
8590     //  5 - NLT
8591     //  6 - NLE
8592     //  7 - ORD
8593     switch (SetCCOpcode) {
8594     default: break;
8595     case ISD::SETOEQ:
8596     case ISD::SETEQ:  SSECC = 0; break;
8597     case ISD::SETOGT:
8598     case ISD::SETGT: Swap = true; // Fallthrough
8599     case ISD::SETLT:
8600     case ISD::SETOLT: SSECC = 1; break;
8601     case ISD::SETOGE:
8602     case ISD::SETGE: Swap = true; // Fallthrough
8603     case ISD::SETLE:
8604     case ISD::SETOLE: SSECC = 2; break;
8605     case ISD::SETUO:  SSECC = 3; break;
8606     case ISD::SETUNE:
8607     case ISD::SETNE:  SSECC = 4; break;
8608     case ISD::SETULE: Swap = true;
8609     case ISD::SETUGE: SSECC = 5; break;
8610     case ISD::SETULT: Swap = true;
8611     case ISD::SETUGT: SSECC = 6; break;
8612     case ISD::SETO:   SSECC = 7; break;
8613     }
8614     if (Swap)
8615       std::swap(Op0, Op1);
8616
8617     // In the two special cases we can't handle, emit two comparisons.
8618     if (SSECC == 8) {
8619       if (SetCCOpcode == ISD::SETUEQ) {
8620         SDValue UNORD, EQ;
8621         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8622                             DAG.getConstant(3, MVT::i8));
8623         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8624                          DAG.getConstant(0, MVT::i8));
8625         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8626       }
8627       if (SetCCOpcode == ISD::SETONE) {
8628         SDValue ORD, NEQ;
8629         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8630                           DAG.getConstant(7, MVT::i8));
8631         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8632                           DAG.getConstant(4, MVT::i8));
8633         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8634       }
8635       llvm_unreachable("Illegal FP comparison");
8636     }
8637     // Handle all other FP comparisons here.
8638     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8639                        DAG.getConstant(SSECC, MVT::i8));
8640   }
8641
8642   // Break 256-bit integer vector compare into smaller ones.
8643   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8644     return Lower256IntVSETCC(Op, DAG);
8645
8646   // We are handling one of the integer comparisons here.  Since SSE only has
8647   // GT and EQ comparisons for integer, swapping operands and multiple
8648   // operations may be required for some comparisons.
8649   unsigned Opc = 0;
8650   bool Swap = false, Invert = false, FlipSigns = false;
8651
8652   switch (SetCCOpcode) {
8653   default: break;
8654   case ISD::SETNE:  Invert = true;
8655   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8656   case ISD::SETLT:  Swap = true;
8657   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8658   case ISD::SETGE:  Swap = true;
8659   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8660   case ISD::SETULT: Swap = true;
8661   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8662   case ISD::SETUGE: Swap = true;
8663   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8664   }
8665   if (Swap)
8666     std::swap(Op0, Op1);
8667
8668   // Check that the operation in question is available (most are plain SSE2,
8669   // but PCMPGTQ and PCMPEQQ have different requirements).
8670   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8671     return SDValue();
8672   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8673     return SDValue();
8674
8675   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8676   // bits of the inputs before performing those operations.
8677   if (FlipSigns) {
8678     EVT EltVT = VT.getVectorElementType();
8679     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8680                                       EltVT);
8681     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8682     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8683                                     SignBits.size());
8684     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8685     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8686   }
8687
8688   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8689
8690   // If the logical-not of the result is required, perform that now.
8691   if (Invert)
8692     Result = DAG.getNOT(dl, Result, VT);
8693
8694   return Result;
8695 }
8696
8697 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8698 static bool isX86LogicalCmp(SDValue Op) {
8699   unsigned Opc = Op.getNode()->getOpcode();
8700   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8701       Opc == X86ISD::SAHF)
8702     return true;
8703   if (Op.getResNo() == 1 &&
8704       (Opc == X86ISD::ADD ||
8705        Opc == X86ISD::SUB ||
8706        Opc == X86ISD::ADC ||
8707        Opc == X86ISD::SBB ||
8708        Opc == X86ISD::SMUL ||
8709        Opc == X86ISD::UMUL ||
8710        Opc == X86ISD::INC ||
8711        Opc == X86ISD::DEC ||
8712        Opc == X86ISD::OR ||
8713        Opc == X86ISD::XOR ||
8714        Opc == X86ISD::AND))
8715     return true;
8716
8717   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8718     return true;
8719
8720   return false;
8721 }
8722
8723 static bool isZero(SDValue V) {
8724   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8725   return C && C->isNullValue();
8726 }
8727
8728 static bool isAllOnes(SDValue V) {
8729   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8730   return C && C->isAllOnesValue();
8731 }
8732
8733 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8734   bool addTest = true;
8735   SDValue Cond  = Op.getOperand(0);
8736   SDValue Op1 = Op.getOperand(1);
8737   SDValue Op2 = Op.getOperand(2);
8738   DebugLoc DL = Op.getDebugLoc();
8739   SDValue CC;
8740
8741   if (Cond.getOpcode() == ISD::SETCC) {
8742     SDValue NewCond = LowerSETCC(Cond, DAG);
8743     if (NewCond.getNode())
8744       Cond = NewCond;
8745   }
8746
8747   // Handle the following cases related to max and min:
8748   // (a > b) ? (a-b) : 0
8749   // (a >= b) ? (a-b) : 0
8750   // (b < a) ? (a-b) : 0
8751   // (b <= a) ? (a-b) : 0
8752   // Comparison is removed to use EFLAGS from SUB.
8753   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8754     if (Cond.getOpcode() == X86ISD::SETCC &&
8755         Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8756         (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8757         C->getAPIntValue() == 0) {
8758       SDValue Cmp = Cond.getOperand(1);
8759       unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8760       if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8761            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8762            (CC == X86::COND_G || CC == X86::COND_GE ||
8763             CC == X86::COND_A || CC == X86::COND_AE)) ||
8764           (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8765            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8766            (CC == X86::COND_L || CC == X86::COND_LE ||
8767             CC == X86::COND_B || CC == X86::COND_BE))) {
8768
8769         if (Op1.getOpcode() == ISD::SUB) {
8770           SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8771           SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8772                                     Op1.getOperand(0), Op1.getOperand(1));
8773           DAG.ReplaceAllUsesWith(Op1, New);
8774           Op1 = New;
8775         }
8776
8777         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8778         unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8779                           CC == X86::COND_L ||
8780                           CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8781         SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8782                           SDValue(Op1.getNode(), 1) };
8783         return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8784       }
8785     }
8786
8787   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8788   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8789   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8790   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8791   if (Cond.getOpcode() == X86ISD::SETCC &&
8792       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8793       isZero(Cond.getOperand(1).getOperand(1))) {
8794     SDValue Cmp = Cond.getOperand(1);
8795
8796     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8797
8798     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8799         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8800       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8801
8802       SDValue CmpOp0 = Cmp.getOperand(0);
8803       // Apply further optimizations for special cases
8804       // (select (x != 0), -1, 0) -> neg & sbb
8805       // (select (x == 0), 0, -1) -> neg & sbb
8806       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8807         if (YC->isNullValue() && 
8808             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8809           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8810           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 
8811                                     DAG.getConstant(0, CmpOp0.getValueType()), 
8812                                     CmpOp0);
8813           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8814                                     DAG.getConstant(X86::COND_B, MVT::i8),
8815                                     SDValue(Neg.getNode(), 1));
8816           return Res;
8817         }
8818
8819       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8820                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8821       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8822
8823       SDValue Res =   // Res = 0 or -1.
8824         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8825                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8826
8827       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8828         Res = DAG.getNOT(DL, Res, Res.getValueType());
8829
8830       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8831       if (N2C == 0 || !N2C->isNullValue())
8832         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8833       return Res;
8834     }
8835   }
8836
8837   // Look past (and (setcc_carry (cmp ...)), 1).
8838   if (Cond.getOpcode() == ISD::AND &&
8839       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8840     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8841     if (C && C->getAPIntValue() == 1)
8842       Cond = Cond.getOperand(0);
8843   }
8844
8845   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8846   // setting operand in place of the X86ISD::SETCC.
8847   unsigned CondOpcode = Cond.getOpcode();
8848   if (CondOpcode == X86ISD::SETCC ||
8849       CondOpcode == X86ISD::SETCC_CARRY) {
8850     CC = Cond.getOperand(0);
8851
8852     SDValue Cmp = Cond.getOperand(1);
8853     unsigned Opc = Cmp.getOpcode();
8854     EVT VT = Op.getValueType();
8855
8856     bool IllegalFPCMov = false;
8857     if (VT.isFloatingPoint() && !VT.isVector() &&
8858         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8859       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8860
8861     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8862         Opc == X86ISD::BT) { // FIXME
8863       Cond = Cmp;
8864       addTest = false;
8865     }
8866   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8867              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8868              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8869               Cond.getOperand(0).getValueType() != MVT::i8)) {
8870     SDValue LHS = Cond.getOperand(0);
8871     SDValue RHS = Cond.getOperand(1);
8872     unsigned X86Opcode;
8873     unsigned X86Cond;
8874     SDVTList VTs;
8875     switch (CondOpcode) {
8876     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8877     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8878     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8879     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8880     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8881     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8882     default: llvm_unreachable("unexpected overflowing operator");
8883     }
8884     if (CondOpcode == ISD::UMULO)
8885       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8886                           MVT::i32);
8887     else
8888       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8889
8890     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8891
8892     if (CondOpcode == ISD::UMULO)
8893       Cond = X86Op.getValue(2);
8894     else
8895       Cond = X86Op.getValue(1);
8896
8897     CC = DAG.getConstant(X86Cond, MVT::i8);
8898     addTest = false;
8899   }
8900
8901   if (addTest) {
8902     // Look pass the truncate.
8903     if (Cond.getOpcode() == ISD::TRUNCATE)
8904       Cond = Cond.getOperand(0);
8905
8906     // We know the result of AND is compared against zero. Try to match
8907     // it to BT.
8908     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8909       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8910       if (NewSetCC.getNode()) {
8911         CC = NewSetCC.getOperand(0);
8912         Cond = NewSetCC.getOperand(1);
8913         addTest = false;
8914       }
8915     }
8916   }
8917
8918   if (addTest) {
8919     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8920     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8921   }
8922
8923   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8924   // a <  b ?  0 : -1 -> RES = setcc_carry
8925   // a >= b ? -1 :  0 -> RES = setcc_carry
8926   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8927   if (Cond.getOpcode() == X86ISD::CMP) {
8928     Cond = ConvertCmpIfNecessary(Cond, DAG);
8929     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8930
8931     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8932         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8933       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8934                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8935       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8936         return DAG.getNOT(DL, Res, Res.getValueType());
8937       return Res;
8938     }
8939   }
8940
8941   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8942   // condition is true.
8943   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8944   SDValue Ops[] = { Op2, Op1, CC, Cond };
8945   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8946 }
8947
8948 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8949 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8950 // from the AND / OR.
8951 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8952   Opc = Op.getOpcode();
8953   if (Opc != ISD::OR && Opc != ISD::AND)
8954     return false;
8955   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8956           Op.getOperand(0).hasOneUse() &&
8957           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8958           Op.getOperand(1).hasOneUse());
8959 }
8960
8961 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8962 // 1 and that the SETCC node has a single use.
8963 static bool isXor1OfSetCC(SDValue Op) {
8964   if (Op.getOpcode() != ISD::XOR)
8965     return false;
8966   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8967   if (N1C && N1C->getAPIntValue() == 1) {
8968     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8969       Op.getOperand(0).hasOneUse();
8970   }
8971   return false;
8972 }
8973
8974 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8975   bool addTest = true;
8976   SDValue Chain = Op.getOperand(0);
8977   SDValue Cond  = Op.getOperand(1);
8978   SDValue Dest  = Op.getOperand(2);
8979   DebugLoc dl = Op.getDebugLoc();
8980   SDValue CC;
8981   bool Inverted = false;
8982
8983   if (Cond.getOpcode() == ISD::SETCC) {
8984     // Check for setcc([su]{add,sub,mul}o == 0).
8985     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8986         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8987         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8988         Cond.getOperand(0).getResNo() == 1 &&
8989         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8990          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8991          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8992          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8993          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8994          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8995       Inverted = true;
8996       Cond = Cond.getOperand(0);
8997     } else {
8998       SDValue NewCond = LowerSETCC(Cond, DAG);
8999       if (NewCond.getNode())
9000         Cond = NewCond;
9001     }
9002   }
9003 #if 0
9004   // FIXME: LowerXALUO doesn't handle these!!
9005   else if (Cond.getOpcode() == X86ISD::ADD  ||
9006            Cond.getOpcode() == X86ISD::SUB  ||
9007            Cond.getOpcode() == X86ISD::SMUL ||
9008            Cond.getOpcode() == X86ISD::UMUL)
9009     Cond = LowerXALUO(Cond, DAG);
9010 #endif
9011
9012   // Look pass (and (setcc_carry (cmp ...)), 1).
9013   if (Cond.getOpcode() == ISD::AND &&
9014       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9015     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9016     if (C && C->getAPIntValue() == 1)
9017       Cond = Cond.getOperand(0);
9018   }
9019
9020   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9021   // setting operand in place of the X86ISD::SETCC.
9022   unsigned CondOpcode = Cond.getOpcode();
9023   if (CondOpcode == X86ISD::SETCC ||
9024       CondOpcode == X86ISD::SETCC_CARRY) {
9025     CC = Cond.getOperand(0);
9026
9027     SDValue Cmp = Cond.getOperand(1);
9028     unsigned Opc = Cmp.getOpcode();
9029     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9030     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9031       Cond = Cmp;
9032       addTest = false;
9033     } else {
9034       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9035       default: break;
9036       case X86::COND_O:
9037       case X86::COND_B:
9038         // These can only come from an arithmetic instruction with overflow,
9039         // e.g. SADDO, UADDO.
9040         Cond = Cond.getNode()->getOperand(1);
9041         addTest = false;
9042         break;
9043       }
9044     }
9045   }
9046   CondOpcode = Cond.getOpcode();
9047   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9048       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9049       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9050        Cond.getOperand(0).getValueType() != MVT::i8)) {
9051     SDValue LHS = Cond.getOperand(0);
9052     SDValue RHS = Cond.getOperand(1);
9053     unsigned X86Opcode;
9054     unsigned X86Cond;
9055     SDVTList VTs;
9056     switch (CondOpcode) {
9057     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9058     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9059     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9060     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9061     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9062     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9063     default: llvm_unreachable("unexpected overflowing operator");
9064     }
9065     if (Inverted)
9066       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9067     if (CondOpcode == ISD::UMULO)
9068       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9069                           MVT::i32);
9070     else
9071       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9072
9073     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9074
9075     if (CondOpcode == ISD::UMULO)
9076       Cond = X86Op.getValue(2);
9077     else
9078       Cond = X86Op.getValue(1);
9079
9080     CC = DAG.getConstant(X86Cond, MVT::i8);
9081     addTest = false;
9082   } else {
9083     unsigned CondOpc;
9084     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9085       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9086       if (CondOpc == ISD::OR) {
9087         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9088         // two branches instead of an explicit OR instruction with a
9089         // separate test.
9090         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9091             isX86LogicalCmp(Cmp)) {
9092           CC = Cond.getOperand(0).getOperand(0);
9093           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9094                               Chain, Dest, CC, Cmp);
9095           CC = Cond.getOperand(1).getOperand(0);
9096           Cond = Cmp;
9097           addTest = false;
9098         }
9099       } else { // ISD::AND
9100         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9101         // two branches instead of an explicit AND instruction with a
9102         // separate test. However, we only do this if this block doesn't
9103         // have a fall-through edge, because this requires an explicit
9104         // jmp when the condition is false.
9105         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9106             isX86LogicalCmp(Cmp) &&
9107             Op.getNode()->hasOneUse()) {
9108           X86::CondCode CCode =
9109             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9110           CCode = X86::GetOppositeBranchCondition(CCode);
9111           CC = DAG.getConstant(CCode, MVT::i8);
9112           SDNode *User = *Op.getNode()->use_begin();
9113           // Look for an unconditional branch following this conditional branch.
9114           // We need this because we need to reverse the successors in order
9115           // to implement FCMP_OEQ.
9116           if (User->getOpcode() == ISD::BR) {
9117             SDValue FalseBB = User->getOperand(1);
9118             SDNode *NewBR =
9119               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9120             assert(NewBR == User);
9121             (void)NewBR;
9122             Dest = FalseBB;
9123
9124             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9125                                 Chain, Dest, CC, Cmp);
9126             X86::CondCode CCode =
9127               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9128             CCode = X86::GetOppositeBranchCondition(CCode);
9129             CC = DAG.getConstant(CCode, MVT::i8);
9130             Cond = Cmp;
9131             addTest = false;
9132           }
9133         }
9134       }
9135     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9136       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9137       // It should be transformed during dag combiner except when the condition
9138       // is set by a arithmetics with overflow node.
9139       X86::CondCode CCode =
9140         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9141       CCode = X86::GetOppositeBranchCondition(CCode);
9142       CC = DAG.getConstant(CCode, MVT::i8);
9143       Cond = Cond.getOperand(0).getOperand(1);
9144       addTest = false;
9145     } else if (Cond.getOpcode() == ISD::SETCC &&
9146                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9147       // For FCMP_OEQ, we can emit
9148       // two branches instead of an explicit AND instruction with a
9149       // separate test. However, we only do this if this block doesn't
9150       // have a fall-through edge, because this requires an explicit
9151       // jmp when the condition is false.
9152       if (Op.getNode()->hasOneUse()) {
9153         SDNode *User = *Op.getNode()->use_begin();
9154         // Look for an unconditional branch following this conditional branch.
9155         // We need this because we need to reverse the successors in order
9156         // to implement FCMP_OEQ.
9157         if (User->getOpcode() == ISD::BR) {
9158           SDValue FalseBB = User->getOperand(1);
9159           SDNode *NewBR =
9160             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9161           assert(NewBR == User);
9162           (void)NewBR;
9163           Dest = FalseBB;
9164
9165           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9166                                     Cond.getOperand(0), Cond.getOperand(1));
9167           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9168           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9169           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9170                               Chain, Dest, CC, Cmp);
9171           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9172           Cond = Cmp;
9173           addTest = false;
9174         }
9175       }
9176     } else if (Cond.getOpcode() == ISD::SETCC &&
9177                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9178       // For FCMP_UNE, we can emit
9179       // two branches instead of an explicit AND instruction with a
9180       // separate test. However, we only do this if this block doesn't
9181       // have a fall-through edge, because this requires an explicit
9182       // jmp when the condition is false.
9183       if (Op.getNode()->hasOneUse()) {
9184         SDNode *User = *Op.getNode()->use_begin();
9185         // Look for an unconditional branch following this conditional branch.
9186         // We need this because we need to reverse the successors in order
9187         // to implement FCMP_UNE.
9188         if (User->getOpcode() == ISD::BR) {
9189           SDValue FalseBB = User->getOperand(1);
9190           SDNode *NewBR =
9191             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9192           assert(NewBR == User);
9193           (void)NewBR;
9194
9195           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9196                                     Cond.getOperand(0), Cond.getOperand(1));
9197           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9198           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9199           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9200                               Chain, Dest, CC, Cmp);
9201           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9202           Cond = Cmp;
9203           addTest = false;
9204           Dest = FalseBB;
9205         }
9206       }
9207     }
9208   }
9209
9210   if (addTest) {
9211     // Look pass the truncate.
9212     if (Cond.getOpcode() == ISD::TRUNCATE)
9213       Cond = Cond.getOperand(0);
9214
9215     // We know the result of AND is compared against zero. Try to match
9216     // it to BT.
9217     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9218       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9219       if (NewSetCC.getNode()) {
9220         CC = NewSetCC.getOperand(0);
9221         Cond = NewSetCC.getOperand(1);
9222         addTest = false;
9223       }
9224     }
9225   }
9226
9227   if (addTest) {
9228     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9229     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9230   }
9231   Cond = ConvertCmpIfNecessary(Cond, DAG);
9232   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9233                      Chain, Dest, CC, Cond);
9234 }
9235
9236
9237 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9238 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9239 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9240 // that the guard pages used by the OS virtual memory manager are allocated in
9241 // correct sequence.
9242 SDValue
9243 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9244                                            SelectionDAG &DAG) const {
9245   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9246           getTargetMachine().Options.EnableSegmentedStacks) &&
9247          "This should be used only on Windows targets or when segmented stacks "
9248          "are being used");
9249   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9250   DebugLoc dl = Op.getDebugLoc();
9251
9252   // Get the inputs.
9253   SDValue Chain = Op.getOperand(0);
9254   SDValue Size  = Op.getOperand(1);
9255   // FIXME: Ensure alignment here
9256
9257   bool Is64Bit = Subtarget->is64Bit();
9258   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9259
9260   if (getTargetMachine().Options.EnableSegmentedStacks) {
9261     MachineFunction &MF = DAG.getMachineFunction();
9262     MachineRegisterInfo &MRI = MF.getRegInfo();
9263
9264     if (Is64Bit) {
9265       // The 64 bit implementation of segmented stacks needs to clobber both r10
9266       // r11. This makes it impossible to use it along with nested parameters.
9267       const Function *F = MF.getFunction();
9268
9269       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9270            I != E; ++I)
9271         if (I->hasNestAttr())
9272           report_fatal_error("Cannot use segmented stacks with functions that "
9273                              "have nested arguments.");
9274     }
9275
9276     const TargetRegisterClass *AddrRegClass =
9277       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9278     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9279     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9280     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9281                                 DAG.getRegister(Vreg, SPTy));
9282     SDValue Ops1[2] = { Value, Chain };
9283     return DAG.getMergeValues(Ops1, 2, dl);
9284   } else {
9285     SDValue Flag;
9286     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9287
9288     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9289     Flag = Chain.getValue(1);
9290     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9291
9292     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9293     Flag = Chain.getValue(1);
9294
9295     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9296
9297     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9298     return DAG.getMergeValues(Ops1, 2, dl);
9299   }
9300 }
9301
9302 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9303   MachineFunction &MF = DAG.getMachineFunction();
9304   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9305
9306   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9307   DebugLoc DL = Op.getDebugLoc();
9308
9309   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9310     // vastart just stores the address of the VarArgsFrameIndex slot into the
9311     // memory location argument.
9312     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9313                                    getPointerTy());
9314     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9315                         MachinePointerInfo(SV), false, false, 0);
9316   }
9317
9318   // __va_list_tag:
9319   //   gp_offset         (0 - 6 * 8)
9320   //   fp_offset         (48 - 48 + 8 * 16)
9321   //   overflow_arg_area (point to parameters coming in memory).
9322   //   reg_save_area
9323   SmallVector<SDValue, 8> MemOps;
9324   SDValue FIN = Op.getOperand(1);
9325   // Store gp_offset
9326   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9327                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9328                                                MVT::i32),
9329                                FIN, MachinePointerInfo(SV), false, false, 0);
9330   MemOps.push_back(Store);
9331
9332   // Store fp_offset
9333   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9334                     FIN, DAG.getIntPtrConstant(4));
9335   Store = DAG.getStore(Op.getOperand(0), DL,
9336                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9337                                        MVT::i32),
9338                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9339   MemOps.push_back(Store);
9340
9341   // Store ptr to overflow_arg_area
9342   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9343                     FIN, DAG.getIntPtrConstant(4));
9344   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9345                                     getPointerTy());
9346   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9347                        MachinePointerInfo(SV, 8),
9348                        false, false, 0);
9349   MemOps.push_back(Store);
9350
9351   // Store ptr to reg_save_area.
9352   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9353                     FIN, DAG.getIntPtrConstant(8));
9354   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9355                                     getPointerTy());
9356   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9357                        MachinePointerInfo(SV, 16), false, false, 0);
9358   MemOps.push_back(Store);
9359   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9360                      &MemOps[0], MemOps.size());
9361 }
9362
9363 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9364   assert(Subtarget->is64Bit() &&
9365          "LowerVAARG only handles 64-bit va_arg!");
9366   assert((Subtarget->isTargetLinux() ||
9367           Subtarget->isTargetDarwin()) &&
9368           "Unhandled target in LowerVAARG");
9369   assert(Op.getNode()->getNumOperands() == 4);
9370   SDValue Chain = Op.getOperand(0);
9371   SDValue SrcPtr = Op.getOperand(1);
9372   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9373   unsigned Align = Op.getConstantOperandVal(3);
9374   DebugLoc dl = Op.getDebugLoc();
9375
9376   EVT ArgVT = Op.getNode()->getValueType(0);
9377   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9378   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9379   uint8_t ArgMode;
9380
9381   // Decide which area this value should be read from.
9382   // TODO: Implement the AMD64 ABI in its entirety. This simple
9383   // selection mechanism works only for the basic types.
9384   if (ArgVT == MVT::f80) {
9385     llvm_unreachable("va_arg for f80 not yet implemented");
9386   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9387     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9388   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9389     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9390   } else {
9391     llvm_unreachable("Unhandled argument type in LowerVAARG");
9392   }
9393
9394   if (ArgMode == 2) {
9395     // Sanity Check: Make sure using fp_offset makes sense.
9396     assert(!getTargetMachine().Options.UseSoftFloat &&
9397            !(DAG.getMachineFunction()
9398                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9399            Subtarget->hasSSE1());
9400   }
9401
9402   // Insert VAARG_64 node into the DAG
9403   // VAARG_64 returns two values: Variable Argument Address, Chain
9404   SmallVector<SDValue, 11> InstOps;
9405   InstOps.push_back(Chain);
9406   InstOps.push_back(SrcPtr);
9407   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9408   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9409   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9410   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9411   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9412                                           VTs, &InstOps[0], InstOps.size(),
9413                                           MVT::i64,
9414                                           MachinePointerInfo(SV),
9415                                           /*Align=*/0,
9416                                           /*Volatile=*/false,
9417                                           /*ReadMem=*/true,
9418                                           /*WriteMem=*/true);
9419   Chain = VAARG.getValue(1);
9420
9421   // Load the next argument and return it
9422   return DAG.getLoad(ArgVT, dl,
9423                      Chain,
9424                      VAARG,
9425                      MachinePointerInfo(),
9426                      false, false, false, 0);
9427 }
9428
9429 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9430   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9431   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9432   SDValue Chain = Op.getOperand(0);
9433   SDValue DstPtr = Op.getOperand(1);
9434   SDValue SrcPtr = Op.getOperand(2);
9435   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9436   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9437   DebugLoc DL = Op.getDebugLoc();
9438
9439   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9440                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9441                        false,
9442                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9443 }
9444
9445 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9446 // may or may not be a constant. Takes immediate version of shift as input.
9447 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9448                                    SDValue SrcOp, SDValue ShAmt,
9449                                    SelectionDAG &DAG) {
9450   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9451
9452   if (isa<ConstantSDNode>(ShAmt)) {
9453     // Constant may be a TargetConstant. Use a regular constant.
9454     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9455     switch (Opc) {
9456       default: llvm_unreachable("Unknown target vector shift node");
9457       case X86ISD::VSHLI:
9458       case X86ISD::VSRLI:
9459       case X86ISD::VSRAI:
9460         return DAG.getNode(Opc, dl, VT, SrcOp,
9461                            DAG.getConstant(ShiftAmt, MVT::i32));
9462     }
9463   }
9464
9465   // Change opcode to non-immediate version
9466   switch (Opc) {
9467     default: llvm_unreachable("Unknown target vector shift node");
9468     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9469     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9470     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9471   }
9472
9473   // Need to build a vector containing shift amount
9474   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9475   SDValue ShOps[4];
9476   ShOps[0] = ShAmt;
9477   ShOps[1] = DAG.getConstant(0, MVT::i32);
9478   ShOps[2] = DAG.getUNDEF(MVT::i32);
9479   ShOps[3] = DAG.getUNDEF(MVT::i32);
9480   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9481
9482   // The return type has to be a 128-bit type with the same element
9483   // type as the input type.
9484   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9485   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9486
9487   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9488   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9489 }
9490
9491 SDValue
9492 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9493   DebugLoc dl = Op.getDebugLoc();
9494   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9495   switch (IntNo) {
9496   default: return SDValue();    // Don't custom lower most intrinsics.
9497   // Comparison intrinsics.
9498   case Intrinsic::x86_sse_comieq_ss:
9499   case Intrinsic::x86_sse_comilt_ss:
9500   case Intrinsic::x86_sse_comile_ss:
9501   case Intrinsic::x86_sse_comigt_ss:
9502   case Intrinsic::x86_sse_comige_ss:
9503   case Intrinsic::x86_sse_comineq_ss:
9504   case Intrinsic::x86_sse_ucomieq_ss:
9505   case Intrinsic::x86_sse_ucomilt_ss:
9506   case Intrinsic::x86_sse_ucomile_ss:
9507   case Intrinsic::x86_sse_ucomigt_ss:
9508   case Intrinsic::x86_sse_ucomige_ss:
9509   case Intrinsic::x86_sse_ucomineq_ss:
9510   case Intrinsic::x86_sse2_comieq_sd:
9511   case Intrinsic::x86_sse2_comilt_sd:
9512   case Intrinsic::x86_sse2_comile_sd:
9513   case Intrinsic::x86_sse2_comigt_sd:
9514   case Intrinsic::x86_sse2_comige_sd:
9515   case Intrinsic::x86_sse2_comineq_sd:
9516   case Intrinsic::x86_sse2_ucomieq_sd:
9517   case Intrinsic::x86_sse2_ucomilt_sd:
9518   case Intrinsic::x86_sse2_ucomile_sd:
9519   case Intrinsic::x86_sse2_ucomigt_sd:
9520   case Intrinsic::x86_sse2_ucomige_sd:
9521   case Intrinsic::x86_sse2_ucomineq_sd: {
9522     unsigned Opc = 0;
9523     ISD::CondCode CC = ISD::SETCC_INVALID;
9524     switch (IntNo) {
9525     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9526     case Intrinsic::x86_sse_comieq_ss:
9527     case Intrinsic::x86_sse2_comieq_sd:
9528       Opc = X86ISD::COMI;
9529       CC = ISD::SETEQ;
9530       break;
9531     case Intrinsic::x86_sse_comilt_ss:
9532     case Intrinsic::x86_sse2_comilt_sd:
9533       Opc = X86ISD::COMI;
9534       CC = ISD::SETLT;
9535       break;
9536     case Intrinsic::x86_sse_comile_ss:
9537     case Intrinsic::x86_sse2_comile_sd:
9538       Opc = X86ISD::COMI;
9539       CC = ISD::SETLE;
9540       break;
9541     case Intrinsic::x86_sse_comigt_ss:
9542     case Intrinsic::x86_sse2_comigt_sd:
9543       Opc = X86ISD::COMI;
9544       CC = ISD::SETGT;
9545       break;
9546     case Intrinsic::x86_sse_comige_ss:
9547     case Intrinsic::x86_sse2_comige_sd:
9548       Opc = X86ISD::COMI;
9549       CC = ISD::SETGE;
9550       break;
9551     case Intrinsic::x86_sse_comineq_ss:
9552     case Intrinsic::x86_sse2_comineq_sd:
9553       Opc = X86ISD::COMI;
9554       CC = ISD::SETNE;
9555       break;
9556     case Intrinsic::x86_sse_ucomieq_ss:
9557     case Intrinsic::x86_sse2_ucomieq_sd:
9558       Opc = X86ISD::UCOMI;
9559       CC = ISD::SETEQ;
9560       break;
9561     case Intrinsic::x86_sse_ucomilt_ss:
9562     case Intrinsic::x86_sse2_ucomilt_sd:
9563       Opc = X86ISD::UCOMI;
9564       CC = ISD::SETLT;
9565       break;
9566     case Intrinsic::x86_sse_ucomile_ss:
9567     case Intrinsic::x86_sse2_ucomile_sd:
9568       Opc = X86ISD::UCOMI;
9569       CC = ISD::SETLE;
9570       break;
9571     case Intrinsic::x86_sse_ucomigt_ss:
9572     case Intrinsic::x86_sse2_ucomigt_sd:
9573       Opc = X86ISD::UCOMI;
9574       CC = ISD::SETGT;
9575       break;
9576     case Intrinsic::x86_sse_ucomige_ss:
9577     case Intrinsic::x86_sse2_ucomige_sd:
9578       Opc = X86ISD::UCOMI;
9579       CC = ISD::SETGE;
9580       break;
9581     case Intrinsic::x86_sse_ucomineq_ss:
9582     case Intrinsic::x86_sse2_ucomineq_sd:
9583       Opc = X86ISD::UCOMI;
9584       CC = ISD::SETNE;
9585       break;
9586     }
9587
9588     SDValue LHS = Op.getOperand(1);
9589     SDValue RHS = Op.getOperand(2);
9590     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9591     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9592     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9593     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9594                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9595     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9596   }
9597   // Arithmetic intrinsics.
9598   case Intrinsic::x86_sse2_pmulu_dq:
9599   case Intrinsic::x86_avx2_pmulu_dq:
9600     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9601                        Op.getOperand(1), Op.getOperand(2));
9602   case Intrinsic::x86_sse3_hadd_ps:
9603   case Intrinsic::x86_sse3_hadd_pd:
9604   case Intrinsic::x86_avx_hadd_ps_256:
9605   case Intrinsic::x86_avx_hadd_pd_256:
9606     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9607                        Op.getOperand(1), Op.getOperand(2));
9608   case Intrinsic::x86_sse3_hsub_ps:
9609   case Intrinsic::x86_sse3_hsub_pd:
9610   case Intrinsic::x86_avx_hsub_ps_256:
9611   case Intrinsic::x86_avx_hsub_pd_256:
9612     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9613                        Op.getOperand(1), Op.getOperand(2));
9614   case Intrinsic::x86_ssse3_phadd_w_128:
9615   case Intrinsic::x86_ssse3_phadd_d_128:
9616   case Intrinsic::x86_avx2_phadd_w:
9617   case Intrinsic::x86_avx2_phadd_d:
9618     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9619                        Op.getOperand(1), Op.getOperand(2));
9620   case Intrinsic::x86_ssse3_phsub_w_128:
9621   case Intrinsic::x86_ssse3_phsub_d_128:
9622   case Intrinsic::x86_avx2_phsub_w:
9623   case Intrinsic::x86_avx2_phsub_d:
9624     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9625                        Op.getOperand(1), Op.getOperand(2));
9626   case Intrinsic::x86_avx2_psllv_d:
9627   case Intrinsic::x86_avx2_psllv_q:
9628   case Intrinsic::x86_avx2_psllv_d_256:
9629   case Intrinsic::x86_avx2_psllv_q_256:
9630     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9631                       Op.getOperand(1), Op.getOperand(2));
9632   case Intrinsic::x86_avx2_psrlv_d:
9633   case Intrinsic::x86_avx2_psrlv_q:
9634   case Intrinsic::x86_avx2_psrlv_d_256:
9635   case Intrinsic::x86_avx2_psrlv_q_256:
9636     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9637                       Op.getOperand(1), Op.getOperand(2));
9638   case Intrinsic::x86_avx2_psrav_d:
9639   case Intrinsic::x86_avx2_psrav_d_256:
9640     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9641                       Op.getOperand(1), Op.getOperand(2));
9642   case Intrinsic::x86_ssse3_pshuf_b_128:
9643   case Intrinsic::x86_avx2_pshuf_b:
9644     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9645                        Op.getOperand(1), Op.getOperand(2));
9646   case Intrinsic::x86_ssse3_psign_b_128:
9647   case Intrinsic::x86_ssse3_psign_w_128:
9648   case Intrinsic::x86_ssse3_psign_d_128:
9649   case Intrinsic::x86_avx2_psign_b:
9650   case Intrinsic::x86_avx2_psign_w:
9651   case Intrinsic::x86_avx2_psign_d:
9652     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9653                        Op.getOperand(1), Op.getOperand(2));
9654   case Intrinsic::x86_sse41_insertps:
9655     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9656                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9657   case Intrinsic::x86_avx_vperm2f128_ps_256:
9658   case Intrinsic::x86_avx_vperm2f128_pd_256:
9659   case Intrinsic::x86_avx_vperm2f128_si_256:
9660   case Intrinsic::x86_avx2_vperm2i128:
9661     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9662                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9663   case Intrinsic::x86_avx2_permd:
9664   case Intrinsic::x86_avx2_permps:
9665     // Operands intentionally swapped. Mask is last operand to intrinsic,
9666     // but second operand for node/intruction.
9667     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9668                        Op.getOperand(2), Op.getOperand(1));
9669
9670   // ptest and testp intrinsics. The intrinsic these come from are designed to
9671   // return an integer value, not just an instruction so lower it to the ptest
9672   // or testp pattern and a setcc for the result.
9673   case Intrinsic::x86_sse41_ptestz:
9674   case Intrinsic::x86_sse41_ptestc:
9675   case Intrinsic::x86_sse41_ptestnzc:
9676   case Intrinsic::x86_avx_ptestz_256:
9677   case Intrinsic::x86_avx_ptestc_256:
9678   case Intrinsic::x86_avx_ptestnzc_256:
9679   case Intrinsic::x86_avx_vtestz_ps:
9680   case Intrinsic::x86_avx_vtestc_ps:
9681   case Intrinsic::x86_avx_vtestnzc_ps:
9682   case Intrinsic::x86_avx_vtestz_pd:
9683   case Intrinsic::x86_avx_vtestc_pd:
9684   case Intrinsic::x86_avx_vtestnzc_pd:
9685   case Intrinsic::x86_avx_vtestz_ps_256:
9686   case Intrinsic::x86_avx_vtestc_ps_256:
9687   case Intrinsic::x86_avx_vtestnzc_ps_256:
9688   case Intrinsic::x86_avx_vtestz_pd_256:
9689   case Intrinsic::x86_avx_vtestc_pd_256:
9690   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9691     bool IsTestPacked = false;
9692     unsigned X86CC = 0;
9693     switch (IntNo) {
9694     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9695     case Intrinsic::x86_avx_vtestz_ps:
9696     case Intrinsic::x86_avx_vtestz_pd:
9697     case Intrinsic::x86_avx_vtestz_ps_256:
9698     case Intrinsic::x86_avx_vtestz_pd_256:
9699       IsTestPacked = true; // Fallthrough
9700     case Intrinsic::x86_sse41_ptestz:
9701     case Intrinsic::x86_avx_ptestz_256:
9702       // ZF = 1
9703       X86CC = X86::COND_E;
9704       break;
9705     case Intrinsic::x86_avx_vtestc_ps:
9706     case Intrinsic::x86_avx_vtestc_pd:
9707     case Intrinsic::x86_avx_vtestc_ps_256:
9708     case Intrinsic::x86_avx_vtestc_pd_256:
9709       IsTestPacked = true; // Fallthrough
9710     case Intrinsic::x86_sse41_ptestc:
9711     case Intrinsic::x86_avx_ptestc_256:
9712       // CF = 1
9713       X86CC = X86::COND_B;
9714       break;
9715     case Intrinsic::x86_avx_vtestnzc_ps:
9716     case Intrinsic::x86_avx_vtestnzc_pd:
9717     case Intrinsic::x86_avx_vtestnzc_ps_256:
9718     case Intrinsic::x86_avx_vtestnzc_pd_256:
9719       IsTestPacked = true; // Fallthrough
9720     case Intrinsic::x86_sse41_ptestnzc:
9721     case Intrinsic::x86_avx_ptestnzc_256:
9722       // ZF and CF = 0
9723       X86CC = X86::COND_A;
9724       break;
9725     }
9726
9727     SDValue LHS = Op.getOperand(1);
9728     SDValue RHS = Op.getOperand(2);
9729     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9730     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9731     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9732     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9733     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9734   }
9735
9736   // SSE/AVX shift intrinsics
9737   case Intrinsic::x86_sse2_psll_w:
9738   case Intrinsic::x86_sse2_psll_d:
9739   case Intrinsic::x86_sse2_psll_q:
9740   case Intrinsic::x86_avx2_psll_w:
9741   case Intrinsic::x86_avx2_psll_d:
9742   case Intrinsic::x86_avx2_psll_q:
9743     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9744                        Op.getOperand(1), Op.getOperand(2));
9745   case Intrinsic::x86_sse2_psrl_w:
9746   case Intrinsic::x86_sse2_psrl_d:
9747   case Intrinsic::x86_sse2_psrl_q:
9748   case Intrinsic::x86_avx2_psrl_w:
9749   case Intrinsic::x86_avx2_psrl_d:
9750   case Intrinsic::x86_avx2_psrl_q:
9751     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9752                        Op.getOperand(1), Op.getOperand(2));
9753   case Intrinsic::x86_sse2_psra_w:
9754   case Intrinsic::x86_sse2_psra_d:
9755   case Intrinsic::x86_avx2_psra_w:
9756   case Intrinsic::x86_avx2_psra_d:
9757     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9758                        Op.getOperand(1), Op.getOperand(2));
9759   case Intrinsic::x86_sse2_pslli_w:
9760   case Intrinsic::x86_sse2_pslli_d:
9761   case Intrinsic::x86_sse2_pslli_q:
9762   case Intrinsic::x86_avx2_pslli_w:
9763   case Intrinsic::x86_avx2_pslli_d:
9764   case Intrinsic::x86_avx2_pslli_q:
9765     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9766                                Op.getOperand(1), Op.getOperand(2), DAG);
9767   case Intrinsic::x86_sse2_psrli_w:
9768   case Intrinsic::x86_sse2_psrli_d:
9769   case Intrinsic::x86_sse2_psrli_q:
9770   case Intrinsic::x86_avx2_psrli_w:
9771   case Intrinsic::x86_avx2_psrli_d:
9772   case Intrinsic::x86_avx2_psrli_q:
9773     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9774                                Op.getOperand(1), Op.getOperand(2), DAG);
9775   case Intrinsic::x86_sse2_psrai_w:
9776   case Intrinsic::x86_sse2_psrai_d:
9777   case Intrinsic::x86_avx2_psrai_w:
9778   case Intrinsic::x86_avx2_psrai_d:
9779     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9780                                Op.getOperand(1), Op.getOperand(2), DAG);
9781   // Fix vector shift instructions where the last operand is a non-immediate
9782   // i32 value.
9783   case Intrinsic::x86_mmx_pslli_w:
9784   case Intrinsic::x86_mmx_pslli_d:
9785   case Intrinsic::x86_mmx_pslli_q:
9786   case Intrinsic::x86_mmx_psrli_w:
9787   case Intrinsic::x86_mmx_psrli_d:
9788   case Intrinsic::x86_mmx_psrli_q:
9789   case Intrinsic::x86_mmx_psrai_w:
9790   case Intrinsic::x86_mmx_psrai_d: {
9791     SDValue ShAmt = Op.getOperand(2);
9792     if (isa<ConstantSDNode>(ShAmt))
9793       return SDValue();
9794
9795     unsigned NewIntNo = 0;
9796     switch (IntNo) {
9797     case Intrinsic::x86_mmx_pslli_w:
9798       NewIntNo = Intrinsic::x86_mmx_psll_w;
9799       break;
9800     case Intrinsic::x86_mmx_pslli_d:
9801       NewIntNo = Intrinsic::x86_mmx_psll_d;
9802       break;
9803     case Intrinsic::x86_mmx_pslli_q:
9804       NewIntNo = Intrinsic::x86_mmx_psll_q;
9805       break;
9806     case Intrinsic::x86_mmx_psrli_w:
9807       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9808       break;
9809     case Intrinsic::x86_mmx_psrli_d:
9810       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9811       break;
9812     case Intrinsic::x86_mmx_psrli_q:
9813       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9814       break;
9815     case Intrinsic::x86_mmx_psrai_w:
9816       NewIntNo = Intrinsic::x86_mmx_psra_w;
9817       break;
9818     case Intrinsic::x86_mmx_psrai_d:
9819       NewIntNo = Intrinsic::x86_mmx_psra_d;
9820       break;
9821     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9822     }
9823
9824     // The vector shift intrinsics with scalars uses 32b shift amounts but
9825     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9826     // to be zero.
9827     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9828                          DAG.getConstant(0, MVT::i32));
9829 // FIXME this must be lowered to get rid of the invalid type.
9830
9831     EVT VT = Op.getValueType();
9832     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9833     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9834                        DAG.getConstant(NewIntNo, MVT::i32),
9835                        Op.getOperand(1), ShAmt);
9836   }
9837   }
9838 }
9839
9840 SDValue
9841 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9842   DebugLoc dl = Op.getDebugLoc();
9843   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9844   switch (IntNo) {
9845   default: return SDValue();    // Don't custom lower most intrinsics.
9846
9847   // RDRAND intrinsics.
9848   case Intrinsic::x86_rdrand_16:
9849   case Intrinsic::x86_rdrand_32:
9850   case Intrinsic::x86_rdrand_64: {
9851     // Emit the node with the right value type.
9852     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9853     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9854
9855     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9856     // return the value from Rand, which is always 0, casted to i32.
9857     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9858                       DAG.getConstant(1, Op->getValueType(1)),
9859                       DAG.getConstant(X86::COND_B, MVT::i32),
9860                       SDValue(Result.getNode(), 1) };
9861     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9862                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
9863                                   Ops, 4);
9864
9865     // Return { result, isValid, chain }.
9866     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9867                        SDValue(Result.getNode(), 2));
9868   }
9869   }
9870 }
9871
9872 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9873                                            SelectionDAG &DAG) const {
9874   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9875   MFI->setReturnAddressIsTaken(true);
9876
9877   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9878   DebugLoc dl = Op.getDebugLoc();
9879
9880   if (Depth > 0) {
9881     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9882     SDValue Offset =
9883       DAG.getConstant(TD->getPointerSize(),
9884                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9885     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9886                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9887                                    FrameAddr, Offset),
9888                        MachinePointerInfo(), false, false, false, 0);
9889   }
9890
9891   // Just load the return address.
9892   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9893   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9894                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9895 }
9896
9897 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9898   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9899   MFI->setFrameAddressIsTaken(true);
9900
9901   EVT VT = Op.getValueType();
9902   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9903   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9904   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9905   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9906   while (Depth--)
9907     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9908                             MachinePointerInfo(),
9909                             false, false, false, 0);
9910   return FrameAddr;
9911 }
9912
9913 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9914                                                      SelectionDAG &DAG) const {
9915   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9916 }
9917
9918 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9919   SDValue Chain     = Op.getOperand(0);
9920   SDValue Offset    = Op.getOperand(1);
9921   SDValue Handler   = Op.getOperand(2);
9922   DebugLoc dl       = Op.getDebugLoc();
9923
9924   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9925                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9926                                      getPointerTy());
9927   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9928
9929   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9930                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9931   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9932   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9933                        false, false, 0);
9934   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9935
9936   return DAG.getNode(X86ISD::EH_RETURN, dl,
9937                      MVT::Other,
9938                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9939 }
9940
9941 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9942                                                   SelectionDAG &DAG) const {
9943   return Op.getOperand(0);
9944 }
9945
9946 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9947                                                 SelectionDAG &DAG) const {
9948   SDValue Root = Op.getOperand(0);
9949   SDValue Trmp = Op.getOperand(1); // trampoline
9950   SDValue FPtr = Op.getOperand(2); // nested function
9951   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9952   DebugLoc dl  = Op.getDebugLoc();
9953
9954   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9955
9956   if (Subtarget->is64Bit()) {
9957     SDValue OutChains[6];
9958
9959     // Large code-model.
9960     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9961     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9962
9963     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9964     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9965
9966     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9967
9968     // Load the pointer to the nested function into R11.
9969     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9970     SDValue Addr = Trmp;
9971     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9972                                 Addr, MachinePointerInfo(TrmpAddr),
9973                                 false, false, 0);
9974
9975     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9976                        DAG.getConstant(2, MVT::i64));
9977     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9978                                 MachinePointerInfo(TrmpAddr, 2),
9979                                 false, false, 2);
9980
9981     // Load the 'nest' parameter value into R10.
9982     // R10 is specified in X86CallingConv.td
9983     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9984     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9985                        DAG.getConstant(10, MVT::i64));
9986     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9987                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9988                                 false, false, 0);
9989
9990     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9991                        DAG.getConstant(12, MVT::i64));
9992     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9993                                 MachinePointerInfo(TrmpAddr, 12),
9994                                 false, false, 2);
9995
9996     // Jump to the nested function.
9997     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9998     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9999                        DAG.getConstant(20, MVT::i64));
10000     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10001                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10002                                 false, false, 0);
10003
10004     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10005     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10006                        DAG.getConstant(22, MVT::i64));
10007     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10008                                 MachinePointerInfo(TrmpAddr, 22),
10009                                 false, false, 0);
10010
10011     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10012   } else {
10013     const Function *Func =
10014       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10015     CallingConv::ID CC = Func->getCallingConv();
10016     unsigned NestReg;
10017
10018     switch (CC) {
10019     default:
10020       llvm_unreachable("Unsupported calling convention");
10021     case CallingConv::C:
10022     case CallingConv::X86_StdCall: {
10023       // Pass 'nest' parameter in ECX.
10024       // Must be kept in sync with X86CallingConv.td
10025       NestReg = X86::ECX;
10026
10027       // Check that ECX wasn't needed by an 'inreg' parameter.
10028       FunctionType *FTy = Func->getFunctionType();
10029       const AttrListPtr &Attrs = Func->getAttributes();
10030
10031       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10032         unsigned InRegCount = 0;
10033         unsigned Idx = 1;
10034
10035         for (FunctionType::param_iterator I = FTy->param_begin(),
10036              E = FTy->param_end(); I != E; ++I, ++Idx)
10037           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10038             // FIXME: should only count parameters that are lowered to integers.
10039             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10040
10041         if (InRegCount > 2) {
10042           report_fatal_error("Nest register in use - reduce number of inreg"
10043                              " parameters!");
10044         }
10045       }
10046       break;
10047     }
10048     case CallingConv::X86_FastCall:
10049     case CallingConv::X86_ThisCall:
10050     case CallingConv::Fast:
10051       // Pass 'nest' parameter in EAX.
10052       // Must be kept in sync with X86CallingConv.td
10053       NestReg = X86::EAX;
10054       break;
10055     }
10056
10057     SDValue OutChains[4];
10058     SDValue Addr, Disp;
10059
10060     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10061                        DAG.getConstant(10, MVT::i32));
10062     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10063
10064     // This is storing the opcode for MOV32ri.
10065     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10066     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10067     OutChains[0] = DAG.getStore(Root, dl,
10068                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10069                                 Trmp, MachinePointerInfo(TrmpAddr),
10070                                 false, false, 0);
10071
10072     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10073                        DAG.getConstant(1, MVT::i32));
10074     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10075                                 MachinePointerInfo(TrmpAddr, 1),
10076                                 false, false, 1);
10077
10078     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10079     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10080                        DAG.getConstant(5, MVT::i32));
10081     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10082                                 MachinePointerInfo(TrmpAddr, 5),
10083                                 false, false, 1);
10084
10085     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10086                        DAG.getConstant(6, MVT::i32));
10087     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10088                                 MachinePointerInfo(TrmpAddr, 6),
10089                                 false, false, 1);
10090
10091     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10092   }
10093 }
10094
10095 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10096                                             SelectionDAG &DAG) const {
10097   /*
10098    The rounding mode is in bits 11:10 of FPSR, and has the following
10099    settings:
10100      00 Round to nearest
10101      01 Round to -inf
10102      10 Round to +inf
10103      11 Round to 0
10104
10105   FLT_ROUNDS, on the other hand, expects the following:
10106     -1 Undefined
10107      0 Round to 0
10108      1 Round to nearest
10109      2 Round to +inf
10110      3 Round to -inf
10111
10112   To perform the conversion, we do:
10113     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10114   */
10115
10116   MachineFunction &MF = DAG.getMachineFunction();
10117   const TargetMachine &TM = MF.getTarget();
10118   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10119   unsigned StackAlignment = TFI.getStackAlignment();
10120   EVT VT = Op.getValueType();
10121   DebugLoc DL = Op.getDebugLoc();
10122
10123   // Save FP Control Word to stack slot
10124   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10125   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10126
10127
10128   MachineMemOperand *MMO =
10129    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10130                            MachineMemOperand::MOStore, 2, 2);
10131
10132   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10133   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10134                                           DAG.getVTList(MVT::Other),
10135                                           Ops, 2, MVT::i16, MMO);
10136
10137   // Load FP Control Word from stack slot
10138   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10139                             MachinePointerInfo(), false, false, false, 0);
10140
10141   // Transform as necessary
10142   SDValue CWD1 =
10143     DAG.getNode(ISD::SRL, DL, MVT::i16,
10144                 DAG.getNode(ISD::AND, DL, MVT::i16,
10145                             CWD, DAG.getConstant(0x800, MVT::i16)),
10146                 DAG.getConstant(11, MVT::i8));
10147   SDValue CWD2 =
10148     DAG.getNode(ISD::SRL, DL, MVT::i16,
10149                 DAG.getNode(ISD::AND, DL, MVT::i16,
10150                             CWD, DAG.getConstant(0x400, MVT::i16)),
10151                 DAG.getConstant(9, MVT::i8));
10152
10153   SDValue RetVal =
10154     DAG.getNode(ISD::AND, DL, MVT::i16,
10155                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10156                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10157                             DAG.getConstant(1, MVT::i16)),
10158                 DAG.getConstant(3, MVT::i16));
10159
10160
10161   return DAG.getNode((VT.getSizeInBits() < 16 ?
10162                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10163 }
10164
10165 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10166   EVT VT = Op.getValueType();
10167   EVT OpVT = VT;
10168   unsigned NumBits = VT.getSizeInBits();
10169   DebugLoc dl = Op.getDebugLoc();
10170
10171   Op = Op.getOperand(0);
10172   if (VT == MVT::i8) {
10173     // Zero extend to i32 since there is not an i8 bsr.
10174     OpVT = MVT::i32;
10175     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10176   }
10177
10178   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10179   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10180   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10181
10182   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10183   SDValue Ops[] = {
10184     Op,
10185     DAG.getConstant(NumBits+NumBits-1, OpVT),
10186     DAG.getConstant(X86::COND_E, MVT::i8),
10187     Op.getValue(1)
10188   };
10189   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10190
10191   // Finally xor with NumBits-1.
10192   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10193
10194   if (VT == MVT::i8)
10195     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10196   return Op;
10197 }
10198
10199 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10200                                                 SelectionDAG &DAG) const {
10201   EVT VT = Op.getValueType();
10202   EVT OpVT = VT;
10203   unsigned NumBits = VT.getSizeInBits();
10204   DebugLoc dl = Op.getDebugLoc();
10205
10206   Op = Op.getOperand(0);
10207   if (VT == MVT::i8) {
10208     // Zero extend to i32 since there is not an i8 bsr.
10209     OpVT = MVT::i32;
10210     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10211   }
10212
10213   // Issue a bsr (scan bits in reverse).
10214   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10215   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10216
10217   // And xor with NumBits-1.
10218   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10219
10220   if (VT == MVT::i8)
10221     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10222   return Op;
10223 }
10224
10225 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10226   EVT VT = Op.getValueType();
10227   unsigned NumBits = VT.getSizeInBits();
10228   DebugLoc dl = Op.getDebugLoc();
10229   Op = Op.getOperand(0);
10230
10231   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10232   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10233   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10234
10235   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10236   SDValue Ops[] = {
10237     Op,
10238     DAG.getConstant(NumBits, VT),
10239     DAG.getConstant(X86::COND_E, MVT::i8),
10240     Op.getValue(1)
10241   };
10242   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10243 }
10244
10245 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10246 // ones, and then concatenate the result back.
10247 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10248   EVT VT = Op.getValueType();
10249
10250   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10251          "Unsupported value type for operation");
10252
10253   unsigned NumElems = VT.getVectorNumElements();
10254   DebugLoc dl = Op.getDebugLoc();
10255
10256   // Extract the LHS vectors
10257   SDValue LHS = Op.getOperand(0);
10258   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10259   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10260
10261   // Extract the RHS vectors
10262   SDValue RHS = Op.getOperand(1);
10263   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10264   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10265
10266   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10267   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10268
10269   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10270                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10271                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10272 }
10273
10274 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10275   assert(Op.getValueType().getSizeInBits() == 256 &&
10276          Op.getValueType().isInteger() &&
10277          "Only handle AVX 256-bit vector integer operation");
10278   return Lower256IntArith(Op, DAG);
10279 }
10280
10281 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10282   assert(Op.getValueType().getSizeInBits() == 256 &&
10283          Op.getValueType().isInteger() &&
10284          "Only handle AVX 256-bit vector integer operation");
10285   return Lower256IntArith(Op, DAG);
10286 }
10287
10288 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10289   EVT VT = Op.getValueType();
10290
10291   // Decompose 256-bit ops into smaller 128-bit ops.
10292   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10293     return Lower256IntArith(Op, DAG);
10294
10295   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10296          "Only know how to lower V2I64/V4I64 multiply");
10297
10298   DebugLoc dl = Op.getDebugLoc();
10299
10300   //  Ahi = psrlqi(a, 32);
10301   //  Bhi = psrlqi(b, 32);
10302   //
10303   //  AloBlo = pmuludq(a, b);
10304   //  AloBhi = pmuludq(a, Bhi);
10305   //  AhiBlo = pmuludq(Ahi, b);
10306
10307   //  AloBhi = psllqi(AloBhi, 32);
10308   //  AhiBlo = psllqi(AhiBlo, 32);
10309   //  return AloBlo + AloBhi + AhiBlo;
10310
10311   SDValue A = Op.getOperand(0);
10312   SDValue B = Op.getOperand(1);
10313
10314   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10315
10316   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10317   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10318
10319   // Bit cast to 32-bit vectors for MULUDQ
10320   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10321   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10322   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10323   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10324   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10325
10326   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10327   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10328   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10329
10330   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10331   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10332
10333   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10334   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10335 }
10336
10337 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10338
10339   EVT VT = Op.getValueType();
10340   DebugLoc dl = Op.getDebugLoc();
10341   SDValue R = Op.getOperand(0);
10342   SDValue Amt = Op.getOperand(1);
10343   LLVMContext *Context = DAG.getContext();
10344
10345   if (!Subtarget->hasSSE2())
10346     return SDValue();
10347
10348   // Optimize shl/srl/sra with constant shift amount.
10349   if (isSplatVector(Amt.getNode())) {
10350     SDValue SclrAmt = Amt->getOperand(0);
10351     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10352       uint64_t ShiftAmt = C->getZExtValue();
10353
10354       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10355           (Subtarget->hasAVX2() &&
10356            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10357         if (Op.getOpcode() == ISD::SHL)
10358           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10359                              DAG.getConstant(ShiftAmt, MVT::i32));
10360         if (Op.getOpcode() == ISD::SRL)
10361           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10362                              DAG.getConstant(ShiftAmt, MVT::i32));
10363         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10364           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10365                              DAG.getConstant(ShiftAmt, MVT::i32));
10366       }
10367
10368       if (VT == MVT::v16i8) {
10369         if (Op.getOpcode() == ISD::SHL) {
10370           // Make a large shift.
10371           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10372                                     DAG.getConstant(ShiftAmt, MVT::i32));
10373           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10374           // Zero out the rightmost bits.
10375           SmallVector<SDValue, 16> V(16,
10376                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10377                                                      MVT::i8));
10378           return DAG.getNode(ISD::AND, dl, VT, SHL,
10379                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10380         }
10381         if (Op.getOpcode() == ISD::SRL) {
10382           // Make a large shift.
10383           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10384                                     DAG.getConstant(ShiftAmt, MVT::i32));
10385           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10386           // Zero out the leftmost bits.
10387           SmallVector<SDValue, 16> V(16,
10388                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10389                                                      MVT::i8));
10390           return DAG.getNode(ISD::AND, dl, VT, SRL,
10391                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10392         }
10393         if (Op.getOpcode() == ISD::SRA) {
10394           if (ShiftAmt == 7) {
10395             // R s>> 7  ===  R s< 0
10396             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10397             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10398           }
10399
10400           // R s>> a === ((R u>> a) ^ m) - m
10401           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10402           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10403                                                          MVT::i8));
10404           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10405           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10406           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10407           return Res;
10408         }
10409         llvm_unreachable("Unknown shift opcode.");
10410       }
10411
10412       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10413         if (Op.getOpcode() == ISD::SHL) {
10414           // Make a large shift.
10415           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10416                                     DAG.getConstant(ShiftAmt, MVT::i32));
10417           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10418           // Zero out the rightmost bits.
10419           SmallVector<SDValue, 32> V(32,
10420                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10421                                                      MVT::i8));
10422           return DAG.getNode(ISD::AND, dl, VT, SHL,
10423                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10424         }
10425         if (Op.getOpcode() == ISD::SRL) {
10426           // Make a large shift.
10427           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10428                                     DAG.getConstant(ShiftAmt, MVT::i32));
10429           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10430           // Zero out the leftmost bits.
10431           SmallVector<SDValue, 32> V(32,
10432                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10433                                                      MVT::i8));
10434           return DAG.getNode(ISD::AND, dl, VT, SRL,
10435                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10436         }
10437         if (Op.getOpcode() == ISD::SRA) {
10438           if (ShiftAmt == 7) {
10439             // R s>> 7  ===  R s< 0
10440             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10441             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10442           }
10443
10444           // R s>> a === ((R u>> a) ^ m) - m
10445           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10446           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10447                                                          MVT::i8));
10448           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10449           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10450           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10451           return Res;
10452         }
10453         llvm_unreachable("Unknown shift opcode.");
10454       }
10455     }
10456   }
10457
10458   // Lower SHL with variable shift amount.
10459   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10460     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10461                      DAG.getConstant(23, MVT::i32));
10462
10463     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10464     Constant *C = ConstantDataVector::get(*Context, CV);
10465     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10466     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10467                                  MachinePointerInfo::getConstantPool(),
10468                                  false, false, false, 16);
10469
10470     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10471     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10472     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10473     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10474   }
10475   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10476     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10477
10478     // a = a << 5;
10479     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10480                      DAG.getConstant(5, MVT::i32));
10481     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10482
10483     // Turn 'a' into a mask suitable for VSELECT
10484     SDValue VSelM = DAG.getConstant(0x80, VT);
10485     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10486     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10487
10488     SDValue CM1 = DAG.getConstant(0x0f, VT);
10489     SDValue CM2 = DAG.getConstant(0x3f, VT);
10490
10491     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10492     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10493     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10494                             DAG.getConstant(4, MVT::i32), DAG);
10495     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10496     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10497
10498     // a += a
10499     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10500     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10501     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10502
10503     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10504     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10505     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10506                             DAG.getConstant(2, MVT::i32), DAG);
10507     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10508     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10509
10510     // a += a
10511     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10512     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10513     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10514
10515     // return VSELECT(r, r+r, a);
10516     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10517                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10518     return R;
10519   }
10520
10521   // Decompose 256-bit shifts into smaller 128-bit shifts.
10522   if (VT.getSizeInBits() == 256) {
10523     unsigned NumElems = VT.getVectorNumElements();
10524     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10525     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10526
10527     // Extract the two vectors
10528     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10529     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10530
10531     // Recreate the shift amount vectors
10532     SDValue Amt1, Amt2;
10533     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10534       // Constant shift amount
10535       SmallVector<SDValue, 4> Amt1Csts;
10536       SmallVector<SDValue, 4> Amt2Csts;
10537       for (unsigned i = 0; i != NumElems/2; ++i)
10538         Amt1Csts.push_back(Amt->getOperand(i));
10539       for (unsigned i = NumElems/2; i != NumElems; ++i)
10540         Amt2Csts.push_back(Amt->getOperand(i));
10541
10542       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10543                                  &Amt1Csts[0], NumElems/2);
10544       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10545                                  &Amt2Csts[0], NumElems/2);
10546     } else {
10547       // Variable shift amount
10548       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10549       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10550     }
10551
10552     // Issue new vector shifts for the smaller types
10553     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10554     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10555
10556     // Concatenate the result back
10557     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10558   }
10559
10560   return SDValue();
10561 }
10562
10563 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10564   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10565   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10566   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10567   // has only one use.
10568   SDNode *N = Op.getNode();
10569   SDValue LHS = N->getOperand(0);
10570   SDValue RHS = N->getOperand(1);
10571   unsigned BaseOp = 0;
10572   unsigned Cond = 0;
10573   DebugLoc DL = Op.getDebugLoc();
10574   switch (Op.getOpcode()) {
10575   default: llvm_unreachable("Unknown ovf instruction!");
10576   case ISD::SADDO:
10577     // A subtract of one will be selected as a INC. Note that INC doesn't
10578     // set CF, so we can't do this for UADDO.
10579     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10580       if (C->isOne()) {
10581         BaseOp = X86ISD::INC;
10582         Cond = X86::COND_O;
10583         break;
10584       }
10585     BaseOp = X86ISD::ADD;
10586     Cond = X86::COND_O;
10587     break;
10588   case ISD::UADDO:
10589     BaseOp = X86ISD::ADD;
10590     Cond = X86::COND_B;
10591     break;
10592   case ISD::SSUBO:
10593     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10594     // set CF, so we can't do this for USUBO.
10595     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10596       if (C->isOne()) {
10597         BaseOp = X86ISD::DEC;
10598         Cond = X86::COND_O;
10599         break;
10600       }
10601     BaseOp = X86ISD::SUB;
10602     Cond = X86::COND_O;
10603     break;
10604   case ISD::USUBO:
10605     BaseOp = X86ISD::SUB;
10606     Cond = X86::COND_B;
10607     break;
10608   case ISD::SMULO:
10609     BaseOp = X86ISD::SMUL;
10610     Cond = X86::COND_O;
10611     break;
10612   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10613     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10614                                  MVT::i32);
10615     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10616
10617     SDValue SetCC =
10618       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10619                   DAG.getConstant(X86::COND_O, MVT::i32),
10620                   SDValue(Sum.getNode(), 2));
10621
10622     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10623   }
10624   }
10625
10626   // Also sets EFLAGS.
10627   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10628   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10629
10630   SDValue SetCC =
10631     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10632                 DAG.getConstant(Cond, MVT::i32),
10633                 SDValue(Sum.getNode(), 1));
10634
10635   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10636 }
10637
10638 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10639                                                   SelectionDAG &DAG) const {
10640   DebugLoc dl = Op.getDebugLoc();
10641   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10642   EVT VT = Op.getValueType();
10643
10644   if (!Subtarget->hasSSE2() || !VT.isVector())
10645     return SDValue();
10646
10647   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10648                       ExtraVT.getScalarType().getSizeInBits();
10649   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10650
10651   switch (VT.getSimpleVT().SimpleTy) {
10652     default: return SDValue();
10653     case MVT::v8i32:
10654     case MVT::v16i16:
10655       if (!Subtarget->hasAVX())
10656         return SDValue();
10657       if (!Subtarget->hasAVX2()) {
10658         // needs to be split
10659         unsigned NumElems = VT.getVectorNumElements();
10660
10661         // Extract the LHS vectors
10662         SDValue LHS = Op.getOperand(0);
10663         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10664         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10665
10666         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10667         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10668
10669         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10670         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10671         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10672                                    ExtraNumElems/2);
10673         SDValue Extra = DAG.getValueType(ExtraVT);
10674
10675         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10676         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10677
10678         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10679       }
10680       // fall through
10681     case MVT::v4i32:
10682     case MVT::v8i16: {
10683       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10684                                          Op.getOperand(0), ShAmt, DAG);
10685       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10686     }
10687   }
10688 }
10689
10690
10691 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10692   DebugLoc dl = Op.getDebugLoc();
10693
10694   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10695   // There isn't any reason to disable it if the target processor supports it.
10696   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10697     SDValue Chain = Op.getOperand(0);
10698     SDValue Zero = DAG.getConstant(0, MVT::i32);
10699     SDValue Ops[] = {
10700       DAG.getRegister(X86::ESP, MVT::i32), // Base
10701       DAG.getTargetConstant(1, MVT::i8),   // Scale
10702       DAG.getRegister(0, MVT::i32),        // Index
10703       DAG.getTargetConstant(0, MVT::i32),  // Disp
10704       DAG.getRegister(0, MVT::i32),        // Segment.
10705       Zero,
10706       Chain
10707     };
10708     SDNode *Res =
10709       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10710                           array_lengthof(Ops));
10711     return SDValue(Res, 0);
10712   }
10713
10714   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10715   if (!isDev)
10716     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10717
10718   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10719   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10720   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10721   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10722
10723   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10724   if (!Op1 && !Op2 && !Op3 && Op4)
10725     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10726
10727   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10728   if (Op1 && !Op2 && !Op3 && !Op4)
10729     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10730
10731   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10732   //           (MFENCE)>;
10733   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10734 }
10735
10736 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10737                                              SelectionDAG &DAG) const {
10738   DebugLoc dl = Op.getDebugLoc();
10739   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10740     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10741   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10742     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10743
10744   // The only fence that needs an instruction is a sequentially-consistent
10745   // cross-thread fence.
10746   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10747     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10748     // no-sse2). There isn't any reason to disable it if the target processor
10749     // supports it.
10750     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10751       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10752
10753     SDValue Chain = Op.getOperand(0);
10754     SDValue Zero = DAG.getConstant(0, MVT::i32);
10755     SDValue Ops[] = {
10756       DAG.getRegister(X86::ESP, MVT::i32), // Base
10757       DAG.getTargetConstant(1, MVT::i8),   // Scale
10758       DAG.getRegister(0, MVT::i32),        // Index
10759       DAG.getTargetConstant(0, MVT::i32),  // Disp
10760       DAG.getRegister(0, MVT::i32),        // Segment.
10761       Zero,
10762       Chain
10763     };
10764     SDNode *Res =
10765       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10766                          array_lengthof(Ops));
10767     return SDValue(Res, 0);
10768   }
10769
10770   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10771   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10772 }
10773
10774
10775 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10776   EVT T = Op.getValueType();
10777   DebugLoc DL = Op.getDebugLoc();
10778   unsigned Reg = 0;
10779   unsigned size = 0;
10780   switch(T.getSimpleVT().SimpleTy) {
10781   default: llvm_unreachable("Invalid value type!");
10782   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10783   case MVT::i16: Reg = X86::AX;  size = 2; break;
10784   case MVT::i32: Reg = X86::EAX; size = 4; break;
10785   case MVT::i64:
10786     assert(Subtarget->is64Bit() && "Node not type legal!");
10787     Reg = X86::RAX; size = 8;
10788     break;
10789   }
10790   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10791                                     Op.getOperand(2), SDValue());
10792   SDValue Ops[] = { cpIn.getValue(0),
10793                     Op.getOperand(1),
10794                     Op.getOperand(3),
10795                     DAG.getTargetConstant(size, MVT::i8),
10796                     cpIn.getValue(1) };
10797   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10798   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10799   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10800                                            Ops, 5, T, MMO);
10801   SDValue cpOut =
10802     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10803   return cpOut;
10804 }
10805
10806 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10807                                                  SelectionDAG &DAG) const {
10808   assert(Subtarget->is64Bit() && "Result not type legalized?");
10809   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10810   SDValue TheChain = Op.getOperand(0);
10811   DebugLoc dl = Op.getDebugLoc();
10812   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10813   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10814   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10815                                    rax.getValue(2));
10816   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10817                             DAG.getConstant(32, MVT::i8));
10818   SDValue Ops[] = {
10819     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10820     rdx.getValue(1)
10821   };
10822   return DAG.getMergeValues(Ops, 2, dl);
10823 }
10824
10825 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10826                                             SelectionDAG &DAG) const {
10827   EVT SrcVT = Op.getOperand(0).getValueType();
10828   EVT DstVT = Op.getValueType();
10829   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10830          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10831   assert((DstVT == MVT::i64 ||
10832           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10833          "Unexpected custom BITCAST");
10834   // i64 <=> MMX conversions are Legal.
10835   if (SrcVT==MVT::i64 && DstVT.isVector())
10836     return Op;
10837   if (DstVT==MVT::i64 && SrcVT.isVector())
10838     return Op;
10839   // MMX <=> MMX conversions are Legal.
10840   if (SrcVT.isVector() && DstVT.isVector())
10841     return Op;
10842   // All other conversions need to be expanded.
10843   return SDValue();
10844 }
10845
10846 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10847   SDNode *Node = Op.getNode();
10848   DebugLoc dl = Node->getDebugLoc();
10849   EVT T = Node->getValueType(0);
10850   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10851                               DAG.getConstant(0, T), Node->getOperand(2));
10852   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10853                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10854                        Node->getOperand(0),
10855                        Node->getOperand(1), negOp,
10856                        cast<AtomicSDNode>(Node)->getSrcValue(),
10857                        cast<AtomicSDNode>(Node)->getAlignment(),
10858                        cast<AtomicSDNode>(Node)->getOrdering(),
10859                        cast<AtomicSDNode>(Node)->getSynchScope());
10860 }
10861
10862 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10863   SDNode *Node = Op.getNode();
10864   DebugLoc dl = Node->getDebugLoc();
10865   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10866
10867   // Convert seq_cst store -> xchg
10868   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10869   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10870   //        (The only way to get a 16-byte store is cmpxchg16b)
10871   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10872   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10873       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10874     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10875                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10876                                  Node->getOperand(0),
10877                                  Node->getOperand(1), Node->getOperand(2),
10878                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10879                                  cast<AtomicSDNode>(Node)->getOrdering(),
10880                                  cast<AtomicSDNode>(Node)->getSynchScope());
10881     return Swap.getValue(1);
10882   }
10883   // Other atomic stores have a simple pattern.
10884   return Op;
10885 }
10886
10887 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10888   EVT VT = Op.getNode()->getValueType(0);
10889
10890   // Let legalize expand this if it isn't a legal type yet.
10891   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10892     return SDValue();
10893
10894   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10895
10896   unsigned Opc;
10897   bool ExtraOp = false;
10898   switch (Op.getOpcode()) {
10899   default: llvm_unreachable("Invalid code");
10900   case ISD::ADDC: Opc = X86ISD::ADD; break;
10901   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10902   case ISD::SUBC: Opc = X86ISD::SUB; break;
10903   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10904   }
10905
10906   if (!ExtraOp)
10907     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10908                        Op.getOperand(1));
10909   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10910                      Op.getOperand(1), Op.getOperand(2));
10911 }
10912
10913 /// LowerOperation - Provide custom lowering hooks for some operations.
10914 ///
10915 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10916   switch (Op.getOpcode()) {
10917   default: llvm_unreachable("Should not custom lower this!");
10918   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10919   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10920   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10921   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10922   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10923   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10924   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10925   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10926   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10927   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10928   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10929   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10930   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10931   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10932   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10933   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10934   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10935   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10936   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10937   case ISD::SHL_PARTS:
10938   case ISD::SRA_PARTS:
10939   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10940   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10941   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10942   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10943   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10944   case ISD::FABS:               return LowerFABS(Op, DAG);
10945   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10946   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10947   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10948   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10949   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10950   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10951   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10952   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10953   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10954   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10955   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10956   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
10957   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10958   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10959   case ISD::FRAME_TO_ARGS_OFFSET:
10960                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10961   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10962   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10963   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10964   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10965   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10966   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10967   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10968   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10969   case ISD::MUL:                return LowerMUL(Op, DAG);
10970   case ISD::SRA:
10971   case ISD::SRL:
10972   case ISD::SHL:                return LowerShift(Op, DAG);
10973   case ISD::SADDO:
10974   case ISD::UADDO:
10975   case ISD::SSUBO:
10976   case ISD::USUBO:
10977   case ISD::SMULO:
10978   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10979   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10980   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10981   case ISD::ADDC:
10982   case ISD::ADDE:
10983   case ISD::SUBC:
10984   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10985   case ISD::ADD:                return LowerADD(Op, DAG);
10986   case ISD::SUB:                return LowerSUB(Op, DAG);
10987   }
10988 }
10989
10990 static void ReplaceATOMIC_LOAD(SDNode *Node,
10991                                   SmallVectorImpl<SDValue> &Results,
10992                                   SelectionDAG &DAG) {
10993   DebugLoc dl = Node->getDebugLoc();
10994   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10995
10996   // Convert wide load -> cmpxchg8b/cmpxchg16b
10997   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10998   //        (The only way to get a 16-byte load is cmpxchg16b)
10999   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11000   SDValue Zero = DAG.getConstant(0, VT);
11001   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11002                                Node->getOperand(0),
11003                                Node->getOperand(1), Zero, Zero,
11004                                cast<AtomicSDNode>(Node)->getMemOperand(),
11005                                cast<AtomicSDNode>(Node)->getOrdering(),
11006                                cast<AtomicSDNode>(Node)->getSynchScope());
11007   Results.push_back(Swap.getValue(0));
11008   Results.push_back(Swap.getValue(1));
11009 }
11010
11011 void X86TargetLowering::
11012 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11013                         SelectionDAG &DAG, unsigned NewOp) const {
11014   DebugLoc dl = Node->getDebugLoc();
11015   assert (Node->getValueType(0) == MVT::i64 &&
11016           "Only know how to expand i64 atomics");
11017
11018   SDValue Chain = Node->getOperand(0);
11019   SDValue In1 = Node->getOperand(1);
11020   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11021                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11022   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11023                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11024   SDValue Ops[] = { Chain, In1, In2L, In2H };
11025   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11026   SDValue Result =
11027     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11028                             cast<MemSDNode>(Node)->getMemOperand());
11029   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11030   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11031   Results.push_back(Result.getValue(2));
11032 }
11033
11034 /// ReplaceNodeResults - Replace a node with an illegal result type
11035 /// with a new node built out of custom code.
11036 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11037                                            SmallVectorImpl<SDValue>&Results,
11038                                            SelectionDAG &DAG) const {
11039   DebugLoc dl = N->getDebugLoc();
11040   switch (N->getOpcode()) {
11041   default:
11042     llvm_unreachable("Do not know how to custom type legalize this operation!");
11043   case ISD::SIGN_EXTEND_INREG:
11044   case ISD::ADDC:
11045   case ISD::ADDE:
11046   case ISD::SUBC:
11047   case ISD::SUBE:
11048     // We don't want to expand or promote these.
11049     return;
11050   case ISD::FP_TO_SINT:
11051   case ISD::FP_TO_UINT: {
11052     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11053
11054     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11055       return;
11056
11057     std::pair<SDValue,SDValue> Vals =
11058         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11059     SDValue FIST = Vals.first, StackSlot = Vals.second;
11060     if (FIST.getNode() != 0) {
11061       EVT VT = N->getValueType(0);
11062       // Return a load from the stack slot.
11063       if (StackSlot.getNode() != 0)
11064         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11065                                       MachinePointerInfo(),
11066                                       false, false, false, 0));
11067       else
11068         Results.push_back(FIST);
11069     }
11070     return;
11071   }
11072   case ISD::READCYCLECOUNTER: {
11073     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11074     SDValue TheChain = N->getOperand(0);
11075     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11076     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11077                                      rd.getValue(1));
11078     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11079                                      eax.getValue(2));
11080     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11081     SDValue Ops[] = { eax, edx };
11082     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11083     Results.push_back(edx.getValue(1));
11084     return;
11085   }
11086   case ISD::ATOMIC_CMP_SWAP: {
11087     EVT T = N->getValueType(0);
11088     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11089     bool Regs64bit = T == MVT::i128;
11090     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11091     SDValue cpInL, cpInH;
11092     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11093                         DAG.getConstant(0, HalfT));
11094     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11095                         DAG.getConstant(1, HalfT));
11096     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11097                              Regs64bit ? X86::RAX : X86::EAX,
11098                              cpInL, SDValue());
11099     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11100                              Regs64bit ? X86::RDX : X86::EDX,
11101                              cpInH, cpInL.getValue(1));
11102     SDValue swapInL, swapInH;
11103     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11104                           DAG.getConstant(0, HalfT));
11105     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11106                           DAG.getConstant(1, HalfT));
11107     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11108                                Regs64bit ? X86::RBX : X86::EBX,
11109                                swapInL, cpInH.getValue(1));
11110     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11111                                Regs64bit ? X86::RCX : X86::ECX, 
11112                                swapInH, swapInL.getValue(1));
11113     SDValue Ops[] = { swapInH.getValue(0),
11114                       N->getOperand(1),
11115                       swapInH.getValue(1) };
11116     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11117     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11118     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11119                                   X86ISD::LCMPXCHG8_DAG;
11120     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11121                                              Ops, 3, T, MMO);
11122     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11123                                         Regs64bit ? X86::RAX : X86::EAX,
11124                                         HalfT, Result.getValue(1));
11125     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11126                                         Regs64bit ? X86::RDX : X86::EDX,
11127                                         HalfT, cpOutL.getValue(2));
11128     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11129     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11130     Results.push_back(cpOutH.getValue(1));
11131     return;
11132   }
11133   case ISD::ATOMIC_LOAD_ADD:
11134     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11135     return;
11136   case ISD::ATOMIC_LOAD_AND:
11137     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11138     return;
11139   case ISD::ATOMIC_LOAD_NAND:
11140     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11141     return;
11142   case ISD::ATOMIC_LOAD_OR:
11143     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11144     return;
11145   case ISD::ATOMIC_LOAD_SUB:
11146     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11147     return;
11148   case ISD::ATOMIC_LOAD_XOR:
11149     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11150     return;
11151   case ISD::ATOMIC_SWAP:
11152     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11153     return;
11154   case ISD::ATOMIC_LOAD:
11155     ReplaceATOMIC_LOAD(N, Results, DAG);
11156   }
11157 }
11158
11159 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11160   switch (Opcode) {
11161   default: return NULL;
11162   case X86ISD::BSF:                return "X86ISD::BSF";
11163   case X86ISD::BSR:                return "X86ISD::BSR";
11164   case X86ISD::SHLD:               return "X86ISD::SHLD";
11165   case X86ISD::SHRD:               return "X86ISD::SHRD";
11166   case X86ISD::FAND:               return "X86ISD::FAND";
11167   case X86ISD::FOR:                return "X86ISD::FOR";
11168   case X86ISD::FXOR:               return "X86ISD::FXOR";
11169   case X86ISD::FSRL:               return "X86ISD::FSRL";
11170   case X86ISD::FILD:               return "X86ISD::FILD";
11171   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11172   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11173   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11174   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11175   case X86ISD::FLD:                return "X86ISD::FLD";
11176   case X86ISD::FST:                return "X86ISD::FST";
11177   case X86ISD::CALL:               return "X86ISD::CALL";
11178   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11179   case X86ISD::BT:                 return "X86ISD::BT";
11180   case X86ISD::CMP:                return "X86ISD::CMP";
11181   case X86ISD::COMI:               return "X86ISD::COMI";
11182   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11183   case X86ISD::SETCC:              return "X86ISD::SETCC";
11184   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11185   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11186   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11187   case X86ISD::CMOV:               return "X86ISD::CMOV";
11188   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11189   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11190   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11191   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11192   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11193   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11194   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11195   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11196   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11197   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11198   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11199   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11200   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11201   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11202   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11203   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11204   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11205   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11206   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11207   case X86ISD::HADD:               return "X86ISD::HADD";
11208   case X86ISD::HSUB:               return "X86ISD::HSUB";
11209   case X86ISD::FHADD:              return "X86ISD::FHADD";
11210   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11211   case X86ISD::FMAX:               return "X86ISD::FMAX";
11212   case X86ISD::FMIN:               return "X86ISD::FMIN";
11213   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11214   case X86ISD::FRCP:               return "X86ISD::FRCP";
11215   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11216   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11217   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11218   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11219   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11220   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11221   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11222   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11223   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11224   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11225   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11226   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11227   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11228   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11229   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11230   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11231   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11232   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11233   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11234   case X86ISD::VSHL:               return "X86ISD::VSHL";
11235   case X86ISD::VSRL:               return "X86ISD::VSRL";
11236   case X86ISD::VSRA:               return "X86ISD::VSRA";
11237   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11238   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11239   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11240   case X86ISD::CMPP:               return "X86ISD::CMPP";
11241   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11242   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11243   case X86ISD::ADD:                return "X86ISD::ADD";
11244   case X86ISD::SUB:                return "X86ISD::SUB";
11245   case X86ISD::ADC:                return "X86ISD::ADC";
11246   case X86ISD::SBB:                return "X86ISD::SBB";
11247   case X86ISD::SMUL:               return "X86ISD::SMUL";
11248   case X86ISD::UMUL:               return "X86ISD::UMUL";
11249   case X86ISD::INC:                return "X86ISD::INC";
11250   case X86ISD::DEC:                return "X86ISD::DEC";
11251   case X86ISD::OR:                 return "X86ISD::OR";
11252   case X86ISD::XOR:                return "X86ISD::XOR";
11253   case X86ISD::AND:                return "X86ISD::AND";
11254   case X86ISD::ANDN:               return "X86ISD::ANDN";
11255   case X86ISD::BLSI:               return "X86ISD::BLSI";
11256   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11257   case X86ISD::BLSR:               return "X86ISD::BLSR";
11258   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11259   case X86ISD::PTEST:              return "X86ISD::PTEST";
11260   case X86ISD::TESTP:              return "X86ISD::TESTP";
11261   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11262   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11263   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11264   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11265   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11266   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11267   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11268   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11269   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11270   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11271   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11272   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11273   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11274   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11275   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11276   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11277   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11278   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11279   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11280   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11281   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11282   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11283   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11284   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11285   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11286   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11287   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11288   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11289   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11290   case X86ISD::SAHF:               return "X86ISD::SAHF";
11291   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11292   }
11293 }
11294
11295 // isLegalAddressingMode - Return true if the addressing mode represented
11296 // by AM is legal for this target, for a load/store of the specified type.
11297 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11298                                               Type *Ty) const {
11299   // X86 supports extremely general addressing modes.
11300   CodeModel::Model M = getTargetMachine().getCodeModel();
11301   Reloc::Model R = getTargetMachine().getRelocationModel();
11302
11303   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11304   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11305     return false;
11306
11307   if (AM.BaseGV) {
11308     unsigned GVFlags =
11309       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11310
11311     // If a reference to this global requires an extra load, we can't fold it.
11312     if (isGlobalStubReference(GVFlags))
11313       return false;
11314
11315     // If BaseGV requires a register for the PIC base, we cannot also have a
11316     // BaseReg specified.
11317     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11318       return false;
11319
11320     // If lower 4G is not available, then we must use rip-relative addressing.
11321     if ((M != CodeModel::Small || R != Reloc::Static) &&
11322         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11323       return false;
11324   }
11325
11326   switch (AM.Scale) {
11327   case 0:
11328   case 1:
11329   case 2:
11330   case 4:
11331   case 8:
11332     // These scales always work.
11333     break;
11334   case 3:
11335   case 5:
11336   case 9:
11337     // These scales are formed with basereg+scalereg.  Only accept if there is
11338     // no basereg yet.
11339     if (AM.HasBaseReg)
11340       return false;
11341     break;
11342   default:  // Other stuff never works.
11343     return false;
11344   }
11345
11346   return true;
11347 }
11348
11349
11350 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11351   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11352     return false;
11353   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11354   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11355   if (NumBits1 <= NumBits2)
11356     return false;
11357   return true;
11358 }
11359
11360 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11361   return Imm == (int32_t)Imm;
11362 }
11363
11364 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11365   // Can also use sub to handle negated immediates.
11366   return Imm == (int32_t)Imm;
11367 }
11368
11369 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11370   if (!VT1.isInteger() || !VT2.isInteger())
11371     return false;
11372   unsigned NumBits1 = VT1.getSizeInBits();
11373   unsigned NumBits2 = VT2.getSizeInBits();
11374   if (NumBits1 <= NumBits2)
11375     return false;
11376   return true;
11377 }
11378
11379 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11380   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11381   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11382 }
11383
11384 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11385   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11386   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11387 }
11388
11389 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11390   // i16 instructions are longer (0x66 prefix) and potentially slower.
11391   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11392 }
11393
11394 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11395 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11396 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11397 /// are assumed to be legal.
11398 bool
11399 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11400                                       EVT VT) const {
11401   // Very little shuffling can be done for 64-bit vectors right now.
11402   if (VT.getSizeInBits() == 64)
11403     return false;
11404
11405   // FIXME: pshufb, blends, shifts.
11406   return (VT.getVectorNumElements() == 2 ||
11407           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11408           isMOVLMask(M, VT) ||
11409           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11410           isPSHUFDMask(M, VT) ||
11411           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11412           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11413           isPALIGNRMask(M, VT, Subtarget) ||
11414           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11415           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11416           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11417           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11418 }
11419
11420 bool
11421 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11422                                           EVT VT) const {
11423   unsigned NumElts = VT.getVectorNumElements();
11424   // FIXME: This collection of masks seems suspect.
11425   if (NumElts == 2)
11426     return true;
11427   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11428     return (isMOVLMask(Mask, VT)  ||
11429             isCommutedMOVLMask(Mask, VT, true) ||
11430             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11431             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11432   }
11433   return false;
11434 }
11435
11436 //===----------------------------------------------------------------------===//
11437 //                           X86 Scheduler Hooks
11438 //===----------------------------------------------------------------------===//
11439
11440 // private utility function
11441 MachineBasicBlock *
11442 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11443                                                        MachineBasicBlock *MBB,
11444                                                        unsigned regOpc,
11445                                                        unsigned immOpc,
11446                                                        unsigned LoadOpc,
11447                                                        unsigned CXchgOpc,
11448                                                        unsigned notOpc,
11449                                                        unsigned EAXreg,
11450                                                  const TargetRegisterClass *RC,
11451                                                        bool Invert) const {
11452   // For the atomic bitwise operator, we generate
11453   //   thisMBB:
11454   //   newMBB:
11455   //     ld  t1 = [bitinstr.addr]
11456   //     op  t2 = t1, [bitinstr.val]
11457   //     not t3 = t2  (if Invert)
11458   //     mov EAX = t1
11459   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11460   //     bz  newMBB
11461   //     fallthrough -->nextMBB
11462   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11463   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11464   MachineFunction::iterator MBBIter = MBB;
11465   ++MBBIter;
11466
11467   /// First build the CFG
11468   MachineFunction *F = MBB->getParent();
11469   MachineBasicBlock *thisMBB = MBB;
11470   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11471   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11472   F->insert(MBBIter, newMBB);
11473   F->insert(MBBIter, nextMBB);
11474
11475   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11476   nextMBB->splice(nextMBB->begin(), thisMBB,
11477                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11478                   thisMBB->end());
11479   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11480
11481   // Update thisMBB to fall through to newMBB
11482   thisMBB->addSuccessor(newMBB);
11483
11484   // newMBB jumps to itself and fall through to nextMBB
11485   newMBB->addSuccessor(nextMBB);
11486   newMBB->addSuccessor(newMBB);
11487
11488   // Insert instructions into newMBB based on incoming instruction
11489   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11490          "unexpected number of operands");
11491   DebugLoc dl = bInstr->getDebugLoc();
11492   MachineOperand& destOper = bInstr->getOperand(0);
11493   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11494   int numArgs = bInstr->getNumOperands() - 1;
11495   for (int i=0; i < numArgs; ++i)
11496     argOpers[i] = &bInstr->getOperand(i+1);
11497
11498   // x86 address has 4 operands: base, index, scale, and displacement
11499   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11500   int valArgIndx = lastAddrIndx + 1;
11501
11502   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11503   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11504   for (int i=0; i <= lastAddrIndx; ++i)
11505     (*MIB).addOperand(*argOpers[i]);
11506
11507   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11508   assert((argOpers[valArgIndx]->isReg() ||
11509           argOpers[valArgIndx]->isImm()) &&
11510          "invalid operand");
11511   if (argOpers[valArgIndx]->isReg())
11512     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11513   else
11514     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11515   MIB.addReg(t1);
11516   (*MIB).addOperand(*argOpers[valArgIndx]);
11517
11518   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11519   if (Invert) {
11520     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11521   }
11522   else
11523     t3 = t2;
11524
11525   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11526   MIB.addReg(t1);
11527
11528   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11529   for (int i=0; i <= lastAddrIndx; ++i)
11530     (*MIB).addOperand(*argOpers[i]);
11531   MIB.addReg(t3);
11532   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11533   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11534                     bInstr->memoperands_end());
11535
11536   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11537   MIB.addReg(EAXreg);
11538
11539   // insert branch
11540   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11541
11542   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11543   return nextMBB;
11544 }
11545
11546 // private utility function:  64 bit atomics on 32 bit host.
11547 MachineBasicBlock *
11548 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11549                                                        MachineBasicBlock *MBB,
11550                                                        unsigned regOpcL,
11551                                                        unsigned regOpcH,
11552                                                        unsigned immOpcL,
11553                                                        unsigned immOpcH,
11554                                                        bool Invert) const {
11555   // For the atomic bitwise operator, we generate
11556   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11557   //     ld t1,t2 = [bitinstr.addr]
11558   //   newMBB:
11559   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11560   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11561   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11562   //     neg t7, t8 < t5, t6  (if Invert)
11563   //     mov ECX, EBX <- t5, t6
11564   //     mov EAX, EDX <- t1, t2
11565   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11566   //     mov t3, t4 <- EAX, EDX
11567   //     bz  newMBB
11568   //     result in out1, out2
11569   //     fallthrough -->nextMBB
11570
11571   const TargetRegisterClass *RC = &X86::GR32RegClass;
11572   const unsigned LoadOpc = X86::MOV32rm;
11573   const unsigned NotOpc = X86::NOT32r;
11574   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11575   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11576   MachineFunction::iterator MBBIter = MBB;
11577   ++MBBIter;
11578
11579   /// First build the CFG
11580   MachineFunction *F = MBB->getParent();
11581   MachineBasicBlock *thisMBB = MBB;
11582   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11583   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11584   F->insert(MBBIter, newMBB);
11585   F->insert(MBBIter, nextMBB);
11586
11587   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11588   nextMBB->splice(nextMBB->begin(), thisMBB,
11589                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11590                   thisMBB->end());
11591   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11592
11593   // Update thisMBB to fall through to newMBB
11594   thisMBB->addSuccessor(newMBB);
11595
11596   // newMBB jumps to itself and fall through to nextMBB
11597   newMBB->addSuccessor(nextMBB);
11598   newMBB->addSuccessor(newMBB);
11599
11600   DebugLoc dl = bInstr->getDebugLoc();
11601   // Insert instructions into newMBB based on incoming instruction
11602   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11603   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11604          "unexpected number of operands");
11605   MachineOperand& dest1Oper = bInstr->getOperand(0);
11606   MachineOperand& dest2Oper = bInstr->getOperand(1);
11607   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11608   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11609     argOpers[i] = &bInstr->getOperand(i+2);
11610
11611     // We use some of the operands multiple times, so conservatively just
11612     // clear any kill flags that might be present.
11613     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11614       argOpers[i]->setIsKill(false);
11615   }
11616
11617   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11618   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11619
11620   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11621   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11622   for (int i=0; i <= lastAddrIndx; ++i)
11623     (*MIB).addOperand(*argOpers[i]);
11624   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11625   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11626   // add 4 to displacement.
11627   for (int i=0; i <= lastAddrIndx-2; ++i)
11628     (*MIB).addOperand(*argOpers[i]);
11629   MachineOperand newOp3 = *(argOpers[3]);
11630   if (newOp3.isImm())
11631     newOp3.setImm(newOp3.getImm()+4);
11632   else
11633     newOp3.setOffset(newOp3.getOffset()+4);
11634   (*MIB).addOperand(newOp3);
11635   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11636
11637   // t3/4 are defined later, at the bottom of the loop
11638   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11639   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11640   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11641     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11642   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11643     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11644
11645   // The subsequent operations should be using the destination registers of
11646   // the PHI instructions.
11647   t1 = dest1Oper.getReg();
11648   t2 = dest2Oper.getReg();
11649
11650   int valArgIndx = lastAddrIndx + 1;
11651   assert((argOpers[valArgIndx]->isReg() ||
11652           argOpers[valArgIndx]->isImm()) &&
11653          "invalid operand");
11654   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11655   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11656   if (argOpers[valArgIndx]->isReg())
11657     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11658   else
11659     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11660   if (regOpcL != X86::MOV32rr)
11661     MIB.addReg(t1);
11662   (*MIB).addOperand(*argOpers[valArgIndx]);
11663   assert(argOpers[valArgIndx + 1]->isReg() ==
11664          argOpers[valArgIndx]->isReg());
11665   assert(argOpers[valArgIndx + 1]->isImm() ==
11666          argOpers[valArgIndx]->isImm());
11667   if (argOpers[valArgIndx + 1]->isReg())
11668     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11669   else
11670     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11671   if (regOpcH != X86::MOV32rr)
11672     MIB.addReg(t2);
11673   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11674
11675   unsigned t7, t8;
11676   if (Invert) {
11677     t7 = F->getRegInfo().createVirtualRegister(RC);
11678     t8 = F->getRegInfo().createVirtualRegister(RC);
11679     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11680     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11681   } else {
11682     t7 = t5;
11683     t8 = t6;
11684   }
11685
11686   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11687   MIB.addReg(t1);
11688   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11689   MIB.addReg(t2);
11690
11691   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11692   MIB.addReg(t7);
11693   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11694   MIB.addReg(t8);
11695
11696   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11697   for (int i=0; i <= lastAddrIndx; ++i)
11698     (*MIB).addOperand(*argOpers[i]);
11699
11700   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11701   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11702                     bInstr->memoperands_end());
11703
11704   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11705   MIB.addReg(X86::EAX);
11706   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11707   MIB.addReg(X86::EDX);
11708
11709   // insert branch
11710   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11711
11712   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11713   return nextMBB;
11714 }
11715
11716 // private utility function
11717 MachineBasicBlock *
11718 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11719                                                       MachineBasicBlock *MBB,
11720                                                       unsigned cmovOpc) const {
11721   // For the atomic min/max operator, we generate
11722   //   thisMBB:
11723   //   newMBB:
11724   //     ld t1 = [min/max.addr]
11725   //     mov t2 = [min/max.val]
11726   //     cmp  t1, t2
11727   //     cmov[cond] t2 = t1
11728   //     mov EAX = t1
11729   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11730   //     bz   newMBB
11731   //     fallthrough -->nextMBB
11732   //
11733   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11734   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11735   MachineFunction::iterator MBBIter = MBB;
11736   ++MBBIter;
11737
11738   /// First build the CFG
11739   MachineFunction *F = MBB->getParent();
11740   MachineBasicBlock *thisMBB = MBB;
11741   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11742   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11743   F->insert(MBBIter, newMBB);
11744   F->insert(MBBIter, nextMBB);
11745
11746   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11747   nextMBB->splice(nextMBB->begin(), thisMBB,
11748                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11749                   thisMBB->end());
11750   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11751
11752   // Update thisMBB to fall through to newMBB
11753   thisMBB->addSuccessor(newMBB);
11754
11755   // newMBB jumps to newMBB and fall through to nextMBB
11756   newMBB->addSuccessor(nextMBB);
11757   newMBB->addSuccessor(newMBB);
11758
11759   DebugLoc dl = mInstr->getDebugLoc();
11760   // Insert instructions into newMBB based on incoming instruction
11761   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11762          "unexpected number of operands");
11763   MachineOperand& destOper = mInstr->getOperand(0);
11764   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11765   int numArgs = mInstr->getNumOperands() - 1;
11766   for (int i=0; i < numArgs; ++i)
11767     argOpers[i] = &mInstr->getOperand(i+1);
11768
11769   // x86 address has 4 operands: base, index, scale, and displacement
11770   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11771   int valArgIndx = lastAddrIndx + 1;
11772
11773   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11774   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11775   for (int i=0; i <= lastAddrIndx; ++i)
11776     (*MIB).addOperand(*argOpers[i]);
11777
11778   // We only support register and immediate values
11779   assert((argOpers[valArgIndx]->isReg() ||
11780           argOpers[valArgIndx]->isImm()) &&
11781          "invalid operand");
11782
11783   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11784   if (argOpers[valArgIndx]->isReg())
11785     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11786   else
11787     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11788   (*MIB).addOperand(*argOpers[valArgIndx]);
11789
11790   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11791   MIB.addReg(t1);
11792
11793   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11794   MIB.addReg(t1);
11795   MIB.addReg(t2);
11796
11797   // Generate movc
11798   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11799   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11800   MIB.addReg(t2);
11801   MIB.addReg(t1);
11802
11803   // Cmp and exchange if none has modified the memory location
11804   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11805   for (int i=0; i <= lastAddrIndx; ++i)
11806     (*MIB).addOperand(*argOpers[i]);
11807   MIB.addReg(t3);
11808   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11809   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11810                     mInstr->memoperands_end());
11811
11812   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11813   MIB.addReg(X86::EAX);
11814
11815   // insert branch
11816   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11817
11818   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11819   return nextMBB;
11820 }
11821
11822 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11823 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11824 // in the .td file.
11825 MachineBasicBlock *
11826 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11827                             unsigned numArgs, bool memArg) const {
11828   assert(Subtarget->hasSSE42() &&
11829          "Target must have SSE4.2 or AVX features enabled");
11830
11831   DebugLoc dl = MI->getDebugLoc();
11832   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11833   unsigned Opc;
11834   if (!Subtarget->hasAVX()) {
11835     if (memArg)
11836       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11837     else
11838       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11839   } else {
11840     if (memArg)
11841       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11842     else
11843       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11844   }
11845
11846   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11847   for (unsigned i = 0; i < numArgs; ++i) {
11848     MachineOperand &Op = MI->getOperand(i+1);
11849     if (!(Op.isReg() && Op.isImplicit()))
11850       MIB.addOperand(Op);
11851   }
11852   BuildMI(*BB, MI, dl,
11853     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11854              MI->getOperand(0).getReg())
11855     .addReg(X86::XMM0);
11856
11857   MI->eraseFromParent();
11858   return BB;
11859 }
11860
11861 MachineBasicBlock *
11862 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11863   DebugLoc dl = MI->getDebugLoc();
11864   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11865
11866   // Address into RAX/EAX, other two args into ECX, EDX.
11867   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11868   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11869   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11870   for (int i = 0; i < X86::AddrNumOperands; ++i)
11871     MIB.addOperand(MI->getOperand(i));
11872
11873   unsigned ValOps = X86::AddrNumOperands;
11874   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11875     .addReg(MI->getOperand(ValOps).getReg());
11876   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11877     .addReg(MI->getOperand(ValOps+1).getReg());
11878
11879   // The instruction doesn't actually take any operands though.
11880   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11881
11882   MI->eraseFromParent(); // The pseudo is gone now.
11883   return BB;
11884 }
11885
11886 MachineBasicBlock *
11887 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11888   DebugLoc dl = MI->getDebugLoc();
11889   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11890
11891   // First arg in ECX, the second in EAX.
11892   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11893     .addReg(MI->getOperand(0).getReg());
11894   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11895     .addReg(MI->getOperand(1).getReg());
11896
11897   // The instruction doesn't actually take any operands though.
11898   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11899
11900   MI->eraseFromParent(); // The pseudo is gone now.
11901   return BB;
11902 }
11903
11904 MachineBasicBlock *
11905 X86TargetLowering::EmitVAARG64WithCustomInserter(
11906                    MachineInstr *MI,
11907                    MachineBasicBlock *MBB) const {
11908   // Emit va_arg instruction on X86-64.
11909
11910   // Operands to this pseudo-instruction:
11911   // 0  ) Output        : destination address (reg)
11912   // 1-5) Input         : va_list address (addr, i64mem)
11913   // 6  ) ArgSize       : Size (in bytes) of vararg type
11914   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11915   // 8  ) Align         : Alignment of type
11916   // 9  ) EFLAGS (implicit-def)
11917
11918   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11919   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11920
11921   unsigned DestReg = MI->getOperand(0).getReg();
11922   MachineOperand &Base = MI->getOperand(1);
11923   MachineOperand &Scale = MI->getOperand(2);
11924   MachineOperand &Index = MI->getOperand(3);
11925   MachineOperand &Disp = MI->getOperand(4);
11926   MachineOperand &Segment = MI->getOperand(5);
11927   unsigned ArgSize = MI->getOperand(6).getImm();
11928   unsigned ArgMode = MI->getOperand(7).getImm();
11929   unsigned Align = MI->getOperand(8).getImm();
11930
11931   // Memory Reference
11932   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11933   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11934   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11935
11936   // Machine Information
11937   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11938   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11939   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11940   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11941   DebugLoc DL = MI->getDebugLoc();
11942
11943   // struct va_list {
11944   //   i32   gp_offset
11945   //   i32   fp_offset
11946   //   i64   overflow_area (address)
11947   //   i64   reg_save_area (address)
11948   // }
11949   // sizeof(va_list) = 24
11950   // alignment(va_list) = 8
11951
11952   unsigned TotalNumIntRegs = 6;
11953   unsigned TotalNumXMMRegs = 8;
11954   bool UseGPOffset = (ArgMode == 1);
11955   bool UseFPOffset = (ArgMode == 2);
11956   unsigned MaxOffset = TotalNumIntRegs * 8 +
11957                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11958
11959   /* Align ArgSize to a multiple of 8 */
11960   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11961   bool NeedsAlign = (Align > 8);
11962
11963   MachineBasicBlock *thisMBB = MBB;
11964   MachineBasicBlock *overflowMBB;
11965   MachineBasicBlock *offsetMBB;
11966   MachineBasicBlock *endMBB;
11967
11968   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11969   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11970   unsigned OffsetReg = 0;
11971
11972   if (!UseGPOffset && !UseFPOffset) {
11973     // If we only pull from the overflow region, we don't create a branch.
11974     // We don't need to alter control flow.
11975     OffsetDestReg = 0; // unused
11976     OverflowDestReg = DestReg;
11977
11978     offsetMBB = NULL;
11979     overflowMBB = thisMBB;
11980     endMBB = thisMBB;
11981   } else {
11982     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11983     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11984     // If not, pull from overflow_area. (branch to overflowMBB)
11985     //
11986     //       thisMBB
11987     //         |     .
11988     //         |        .
11989     //     offsetMBB   overflowMBB
11990     //         |        .
11991     //         |     .
11992     //        endMBB
11993
11994     // Registers for the PHI in endMBB
11995     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11996     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11997
11998     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11999     MachineFunction *MF = MBB->getParent();
12000     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12001     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12002     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12003
12004     MachineFunction::iterator MBBIter = MBB;
12005     ++MBBIter;
12006
12007     // Insert the new basic blocks
12008     MF->insert(MBBIter, offsetMBB);
12009     MF->insert(MBBIter, overflowMBB);
12010     MF->insert(MBBIter, endMBB);
12011
12012     // Transfer the remainder of MBB and its successor edges to endMBB.
12013     endMBB->splice(endMBB->begin(), thisMBB,
12014                     llvm::next(MachineBasicBlock::iterator(MI)),
12015                     thisMBB->end());
12016     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12017
12018     // Make offsetMBB and overflowMBB successors of thisMBB
12019     thisMBB->addSuccessor(offsetMBB);
12020     thisMBB->addSuccessor(overflowMBB);
12021
12022     // endMBB is a successor of both offsetMBB and overflowMBB
12023     offsetMBB->addSuccessor(endMBB);
12024     overflowMBB->addSuccessor(endMBB);
12025
12026     // Load the offset value into a register
12027     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12028     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12029       .addOperand(Base)
12030       .addOperand(Scale)
12031       .addOperand(Index)
12032       .addDisp(Disp, UseFPOffset ? 4 : 0)
12033       .addOperand(Segment)
12034       .setMemRefs(MMOBegin, MMOEnd);
12035
12036     // Check if there is enough room left to pull this argument.
12037     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12038       .addReg(OffsetReg)
12039       .addImm(MaxOffset + 8 - ArgSizeA8);
12040
12041     // Branch to "overflowMBB" if offset >= max
12042     // Fall through to "offsetMBB" otherwise
12043     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12044       .addMBB(overflowMBB);
12045   }
12046
12047   // In offsetMBB, emit code to use the reg_save_area.
12048   if (offsetMBB) {
12049     assert(OffsetReg != 0);
12050
12051     // Read the reg_save_area address.
12052     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12053     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12054       .addOperand(Base)
12055       .addOperand(Scale)
12056       .addOperand(Index)
12057       .addDisp(Disp, 16)
12058       .addOperand(Segment)
12059       .setMemRefs(MMOBegin, MMOEnd);
12060
12061     // Zero-extend the offset
12062     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12063       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12064         .addImm(0)
12065         .addReg(OffsetReg)
12066         .addImm(X86::sub_32bit);
12067
12068     // Add the offset to the reg_save_area to get the final address.
12069     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12070       .addReg(OffsetReg64)
12071       .addReg(RegSaveReg);
12072
12073     // Compute the offset for the next argument
12074     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12075     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12076       .addReg(OffsetReg)
12077       .addImm(UseFPOffset ? 16 : 8);
12078
12079     // Store it back into the va_list.
12080     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12081       .addOperand(Base)
12082       .addOperand(Scale)
12083       .addOperand(Index)
12084       .addDisp(Disp, UseFPOffset ? 4 : 0)
12085       .addOperand(Segment)
12086       .addReg(NextOffsetReg)
12087       .setMemRefs(MMOBegin, MMOEnd);
12088
12089     // Jump to endMBB
12090     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12091       .addMBB(endMBB);
12092   }
12093
12094   //
12095   // Emit code to use overflow area
12096   //
12097
12098   // Load the overflow_area address into a register.
12099   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12100   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12101     .addOperand(Base)
12102     .addOperand(Scale)
12103     .addOperand(Index)
12104     .addDisp(Disp, 8)
12105     .addOperand(Segment)
12106     .setMemRefs(MMOBegin, MMOEnd);
12107
12108   // If we need to align it, do so. Otherwise, just copy the address
12109   // to OverflowDestReg.
12110   if (NeedsAlign) {
12111     // Align the overflow address
12112     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12113     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12114
12115     // aligned_addr = (addr + (align-1)) & ~(align-1)
12116     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12117       .addReg(OverflowAddrReg)
12118       .addImm(Align-1);
12119
12120     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12121       .addReg(TmpReg)
12122       .addImm(~(uint64_t)(Align-1));
12123   } else {
12124     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12125       .addReg(OverflowAddrReg);
12126   }
12127
12128   // Compute the next overflow address after this argument.
12129   // (the overflow address should be kept 8-byte aligned)
12130   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12131   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12132     .addReg(OverflowDestReg)
12133     .addImm(ArgSizeA8);
12134
12135   // Store the new overflow address.
12136   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12137     .addOperand(Base)
12138     .addOperand(Scale)
12139     .addOperand(Index)
12140     .addDisp(Disp, 8)
12141     .addOperand(Segment)
12142     .addReg(NextAddrReg)
12143     .setMemRefs(MMOBegin, MMOEnd);
12144
12145   // If we branched, emit the PHI to the front of endMBB.
12146   if (offsetMBB) {
12147     BuildMI(*endMBB, endMBB->begin(), DL,
12148             TII->get(X86::PHI), DestReg)
12149       .addReg(OffsetDestReg).addMBB(offsetMBB)
12150       .addReg(OverflowDestReg).addMBB(overflowMBB);
12151   }
12152
12153   // Erase the pseudo instruction
12154   MI->eraseFromParent();
12155
12156   return endMBB;
12157 }
12158
12159 MachineBasicBlock *
12160 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12161                                                  MachineInstr *MI,
12162                                                  MachineBasicBlock *MBB) const {
12163   // Emit code to save XMM registers to the stack. The ABI says that the
12164   // number of registers to save is given in %al, so it's theoretically
12165   // possible to do an indirect jump trick to avoid saving all of them,
12166   // however this code takes a simpler approach and just executes all
12167   // of the stores if %al is non-zero. It's less code, and it's probably
12168   // easier on the hardware branch predictor, and stores aren't all that
12169   // expensive anyway.
12170
12171   // Create the new basic blocks. One block contains all the XMM stores,
12172   // and one block is the final destination regardless of whether any
12173   // stores were performed.
12174   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12175   MachineFunction *F = MBB->getParent();
12176   MachineFunction::iterator MBBIter = MBB;
12177   ++MBBIter;
12178   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12179   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12180   F->insert(MBBIter, XMMSaveMBB);
12181   F->insert(MBBIter, EndMBB);
12182
12183   // Transfer the remainder of MBB and its successor edges to EndMBB.
12184   EndMBB->splice(EndMBB->begin(), MBB,
12185                  llvm::next(MachineBasicBlock::iterator(MI)),
12186                  MBB->end());
12187   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12188
12189   // The original block will now fall through to the XMM save block.
12190   MBB->addSuccessor(XMMSaveMBB);
12191   // The XMMSaveMBB will fall through to the end block.
12192   XMMSaveMBB->addSuccessor(EndMBB);
12193
12194   // Now add the instructions.
12195   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12196   DebugLoc DL = MI->getDebugLoc();
12197
12198   unsigned CountReg = MI->getOperand(0).getReg();
12199   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12200   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12201
12202   if (!Subtarget->isTargetWin64()) {
12203     // If %al is 0, branch around the XMM save block.
12204     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12205     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12206     MBB->addSuccessor(EndMBB);
12207   }
12208
12209   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12210   // In the XMM save block, save all the XMM argument registers.
12211   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12212     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12213     MachineMemOperand *MMO =
12214       F->getMachineMemOperand(
12215           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12216         MachineMemOperand::MOStore,
12217         /*Size=*/16, /*Align=*/16);
12218     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12219       .addFrameIndex(RegSaveFrameIndex)
12220       .addImm(/*Scale=*/1)
12221       .addReg(/*IndexReg=*/0)
12222       .addImm(/*Disp=*/Offset)
12223       .addReg(/*Segment=*/0)
12224       .addReg(MI->getOperand(i).getReg())
12225       .addMemOperand(MMO);
12226   }
12227
12228   MI->eraseFromParent();   // The pseudo instruction is gone now.
12229
12230   return EndMBB;
12231 }
12232
12233 // The EFLAGS operand of SelectItr might be missing a kill marker
12234 // because there were multiple uses of EFLAGS, and ISel didn't know
12235 // which to mark. Figure out whether SelectItr should have had a
12236 // kill marker, and set it if it should. Returns the correct kill
12237 // marker value.
12238 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12239                                      MachineBasicBlock* BB,
12240                                      const TargetRegisterInfo* TRI) {
12241   // Scan forward through BB for a use/def of EFLAGS.
12242   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12243   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12244     const MachineInstr& mi = *miI;
12245     if (mi.readsRegister(X86::EFLAGS))
12246       return false;
12247     if (mi.definesRegister(X86::EFLAGS))
12248       break; // Should have kill-flag - update below.
12249   }
12250
12251   // If we hit the end of the block, check whether EFLAGS is live into a
12252   // successor.
12253   if (miI == BB->end()) {
12254     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12255                                           sEnd = BB->succ_end();
12256          sItr != sEnd; ++sItr) {
12257       MachineBasicBlock* succ = *sItr;
12258       if (succ->isLiveIn(X86::EFLAGS))
12259         return false;
12260     }
12261   }
12262
12263   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12264   // out. SelectMI should have a kill flag on EFLAGS.
12265   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12266   return true;
12267 }
12268
12269 MachineBasicBlock *
12270 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12271                                      MachineBasicBlock *BB) const {
12272   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12273   DebugLoc DL = MI->getDebugLoc();
12274
12275   // To "insert" a SELECT_CC instruction, we actually have to insert the
12276   // diamond control-flow pattern.  The incoming instruction knows the
12277   // destination vreg to set, the condition code register to branch on, the
12278   // true/false values to select between, and a branch opcode to use.
12279   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12280   MachineFunction::iterator It = BB;
12281   ++It;
12282
12283   //  thisMBB:
12284   //  ...
12285   //   TrueVal = ...
12286   //   cmpTY ccX, r1, r2
12287   //   bCC copy1MBB
12288   //   fallthrough --> copy0MBB
12289   MachineBasicBlock *thisMBB = BB;
12290   MachineFunction *F = BB->getParent();
12291   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12292   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12293   F->insert(It, copy0MBB);
12294   F->insert(It, sinkMBB);
12295
12296   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12297   // live into the sink and copy blocks.
12298   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12299   if (!MI->killsRegister(X86::EFLAGS) &&
12300       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12301     copy0MBB->addLiveIn(X86::EFLAGS);
12302     sinkMBB->addLiveIn(X86::EFLAGS);
12303   }
12304
12305   // Transfer the remainder of BB and its successor edges to sinkMBB.
12306   sinkMBB->splice(sinkMBB->begin(), BB,
12307                   llvm::next(MachineBasicBlock::iterator(MI)),
12308                   BB->end());
12309   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12310
12311   // Add the true and fallthrough blocks as its successors.
12312   BB->addSuccessor(copy0MBB);
12313   BB->addSuccessor(sinkMBB);
12314
12315   // Create the conditional branch instruction.
12316   unsigned Opc =
12317     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12318   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12319
12320   //  copy0MBB:
12321   //   %FalseValue = ...
12322   //   # fallthrough to sinkMBB
12323   copy0MBB->addSuccessor(sinkMBB);
12324
12325   //  sinkMBB:
12326   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12327   //  ...
12328   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12329           TII->get(X86::PHI), MI->getOperand(0).getReg())
12330     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12331     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12332
12333   MI->eraseFromParent();   // The pseudo instruction is gone now.
12334   return sinkMBB;
12335 }
12336
12337 MachineBasicBlock *
12338 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12339                                         bool Is64Bit) const {
12340   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12341   DebugLoc DL = MI->getDebugLoc();
12342   MachineFunction *MF = BB->getParent();
12343   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12344
12345   assert(getTargetMachine().Options.EnableSegmentedStacks);
12346
12347   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12348   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12349
12350   // BB:
12351   //  ... [Till the alloca]
12352   // If stacklet is not large enough, jump to mallocMBB
12353   //
12354   // bumpMBB:
12355   //  Allocate by subtracting from RSP
12356   //  Jump to continueMBB
12357   //
12358   // mallocMBB:
12359   //  Allocate by call to runtime
12360   //
12361   // continueMBB:
12362   //  ...
12363   //  [rest of original BB]
12364   //
12365
12366   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12367   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12368   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12369
12370   MachineRegisterInfo &MRI = MF->getRegInfo();
12371   const TargetRegisterClass *AddrRegClass =
12372     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12373
12374   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12375     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12376     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12377     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12378     sizeVReg = MI->getOperand(1).getReg(),
12379     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12380
12381   MachineFunction::iterator MBBIter = BB;
12382   ++MBBIter;
12383
12384   MF->insert(MBBIter, bumpMBB);
12385   MF->insert(MBBIter, mallocMBB);
12386   MF->insert(MBBIter, continueMBB);
12387
12388   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12389                       (MachineBasicBlock::iterator(MI)), BB->end());
12390   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12391
12392   // Add code to the main basic block to check if the stack limit has been hit,
12393   // and if so, jump to mallocMBB otherwise to bumpMBB.
12394   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12395   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12396     .addReg(tmpSPVReg).addReg(sizeVReg);
12397   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12398     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12399     .addReg(SPLimitVReg);
12400   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12401
12402   // bumpMBB simply decreases the stack pointer, since we know the current
12403   // stacklet has enough space.
12404   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12405     .addReg(SPLimitVReg);
12406   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12407     .addReg(SPLimitVReg);
12408   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12409
12410   // Calls into a routine in libgcc to allocate more space from the heap.
12411   const uint32_t *RegMask =
12412     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12413   if (Is64Bit) {
12414     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12415       .addReg(sizeVReg);
12416     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12417       .addExternalSymbol("__morestack_allocate_stack_space")
12418       .addRegMask(RegMask)
12419       .addReg(X86::RDI, RegState::Implicit)
12420       .addReg(X86::RAX, RegState::ImplicitDefine);
12421   } else {
12422     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12423       .addImm(12);
12424     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12425     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12426       .addExternalSymbol("__morestack_allocate_stack_space")
12427       .addRegMask(RegMask)
12428       .addReg(X86::EAX, RegState::ImplicitDefine);
12429   }
12430
12431   if (!Is64Bit)
12432     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12433       .addImm(16);
12434
12435   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12436     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12437   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12438
12439   // Set up the CFG correctly.
12440   BB->addSuccessor(bumpMBB);
12441   BB->addSuccessor(mallocMBB);
12442   mallocMBB->addSuccessor(continueMBB);
12443   bumpMBB->addSuccessor(continueMBB);
12444
12445   // Take care of the PHI nodes.
12446   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12447           MI->getOperand(0).getReg())
12448     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12449     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12450
12451   // Delete the original pseudo instruction.
12452   MI->eraseFromParent();
12453
12454   // And we're done.
12455   return continueMBB;
12456 }
12457
12458 MachineBasicBlock *
12459 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12460                                           MachineBasicBlock *BB) const {
12461   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12462   DebugLoc DL = MI->getDebugLoc();
12463
12464   assert(!Subtarget->isTargetEnvMacho());
12465
12466   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12467   // non-trivial part is impdef of ESP.
12468
12469   if (Subtarget->isTargetWin64()) {
12470     if (Subtarget->isTargetCygMing()) {
12471       // ___chkstk(Mingw64):
12472       // Clobbers R10, R11, RAX and EFLAGS.
12473       // Updates RSP.
12474       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12475         .addExternalSymbol("___chkstk")
12476         .addReg(X86::RAX, RegState::Implicit)
12477         .addReg(X86::RSP, RegState::Implicit)
12478         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12479         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12480         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12481     } else {
12482       // __chkstk(MSVCRT): does not update stack pointer.
12483       // Clobbers R10, R11 and EFLAGS.
12484       // FIXME: RAX(allocated size) might be reused and not killed.
12485       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12486         .addExternalSymbol("__chkstk")
12487         .addReg(X86::RAX, RegState::Implicit)
12488         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12489       // RAX has the offset to subtracted from RSP.
12490       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12491         .addReg(X86::RSP)
12492         .addReg(X86::RAX);
12493     }
12494   } else {
12495     const char *StackProbeSymbol =
12496       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12497
12498     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12499       .addExternalSymbol(StackProbeSymbol)
12500       .addReg(X86::EAX, RegState::Implicit)
12501       .addReg(X86::ESP, RegState::Implicit)
12502       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12503       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12504       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12505   }
12506
12507   MI->eraseFromParent();   // The pseudo instruction is gone now.
12508   return BB;
12509 }
12510
12511 MachineBasicBlock *
12512 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12513                                       MachineBasicBlock *BB) const {
12514   // This is pretty easy.  We're taking the value that we received from
12515   // our load from the relocation, sticking it in either RDI (x86-64)
12516   // or EAX and doing an indirect call.  The return value will then
12517   // be in the normal return register.
12518   const X86InstrInfo *TII
12519     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12520   DebugLoc DL = MI->getDebugLoc();
12521   MachineFunction *F = BB->getParent();
12522
12523   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12524   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12525
12526   // Get a register mask for the lowered call.
12527   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12528   // proper register mask.
12529   const uint32_t *RegMask =
12530     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12531   if (Subtarget->is64Bit()) {
12532     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12533                                       TII->get(X86::MOV64rm), X86::RDI)
12534     .addReg(X86::RIP)
12535     .addImm(0).addReg(0)
12536     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12537                       MI->getOperand(3).getTargetFlags())
12538     .addReg(0);
12539     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12540     addDirectMem(MIB, X86::RDI);
12541     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12542   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12543     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12544                                       TII->get(X86::MOV32rm), X86::EAX)
12545     .addReg(0)
12546     .addImm(0).addReg(0)
12547     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12548                       MI->getOperand(3).getTargetFlags())
12549     .addReg(0);
12550     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12551     addDirectMem(MIB, X86::EAX);
12552     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12553   } else {
12554     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12555                                       TII->get(X86::MOV32rm), X86::EAX)
12556     .addReg(TII->getGlobalBaseReg(F))
12557     .addImm(0).addReg(0)
12558     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12559                       MI->getOperand(3).getTargetFlags())
12560     .addReg(0);
12561     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12562     addDirectMem(MIB, X86::EAX);
12563     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12564   }
12565
12566   MI->eraseFromParent(); // The pseudo instruction is gone now.
12567   return BB;
12568 }
12569
12570 MachineBasicBlock *
12571 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12572                                                MachineBasicBlock *BB) const {
12573   switch (MI->getOpcode()) {
12574   default: llvm_unreachable("Unexpected instr type to insert");
12575   case X86::TAILJMPd64:
12576   case X86::TAILJMPr64:
12577   case X86::TAILJMPm64:
12578     llvm_unreachable("TAILJMP64 would not be touched here.");
12579   case X86::TCRETURNdi64:
12580   case X86::TCRETURNri64:
12581   case X86::TCRETURNmi64:
12582     return BB;
12583   case X86::WIN_ALLOCA:
12584     return EmitLoweredWinAlloca(MI, BB);
12585   case X86::SEG_ALLOCA_32:
12586     return EmitLoweredSegAlloca(MI, BB, false);
12587   case X86::SEG_ALLOCA_64:
12588     return EmitLoweredSegAlloca(MI, BB, true);
12589   case X86::TLSCall_32:
12590   case X86::TLSCall_64:
12591     return EmitLoweredTLSCall(MI, BB);
12592   case X86::CMOV_GR8:
12593   case X86::CMOV_FR32:
12594   case X86::CMOV_FR64:
12595   case X86::CMOV_V4F32:
12596   case X86::CMOV_V2F64:
12597   case X86::CMOV_V2I64:
12598   case X86::CMOV_V8F32:
12599   case X86::CMOV_V4F64:
12600   case X86::CMOV_V4I64:
12601   case X86::CMOV_GR16:
12602   case X86::CMOV_GR32:
12603   case X86::CMOV_RFP32:
12604   case X86::CMOV_RFP64:
12605   case X86::CMOV_RFP80:
12606     return EmitLoweredSelect(MI, BB);
12607
12608   case X86::FP32_TO_INT16_IN_MEM:
12609   case X86::FP32_TO_INT32_IN_MEM:
12610   case X86::FP32_TO_INT64_IN_MEM:
12611   case X86::FP64_TO_INT16_IN_MEM:
12612   case X86::FP64_TO_INT32_IN_MEM:
12613   case X86::FP64_TO_INT64_IN_MEM:
12614   case X86::FP80_TO_INT16_IN_MEM:
12615   case X86::FP80_TO_INT32_IN_MEM:
12616   case X86::FP80_TO_INT64_IN_MEM: {
12617     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12618     DebugLoc DL = MI->getDebugLoc();
12619
12620     // Change the floating point control register to use "round towards zero"
12621     // mode when truncating to an integer value.
12622     MachineFunction *F = BB->getParent();
12623     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12624     addFrameReference(BuildMI(*BB, MI, DL,
12625                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12626
12627     // Load the old value of the high byte of the control word...
12628     unsigned OldCW =
12629       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12630     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12631                       CWFrameIdx);
12632
12633     // Set the high part to be round to zero...
12634     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12635       .addImm(0xC7F);
12636
12637     // Reload the modified control word now...
12638     addFrameReference(BuildMI(*BB, MI, DL,
12639                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12640
12641     // Restore the memory image of control word to original value
12642     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12643       .addReg(OldCW);
12644
12645     // Get the X86 opcode to use.
12646     unsigned Opc;
12647     switch (MI->getOpcode()) {
12648     default: llvm_unreachable("illegal opcode!");
12649     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12650     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12651     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12652     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12653     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12654     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12655     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12656     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12657     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12658     }
12659
12660     X86AddressMode AM;
12661     MachineOperand &Op = MI->getOperand(0);
12662     if (Op.isReg()) {
12663       AM.BaseType = X86AddressMode::RegBase;
12664       AM.Base.Reg = Op.getReg();
12665     } else {
12666       AM.BaseType = X86AddressMode::FrameIndexBase;
12667       AM.Base.FrameIndex = Op.getIndex();
12668     }
12669     Op = MI->getOperand(1);
12670     if (Op.isImm())
12671       AM.Scale = Op.getImm();
12672     Op = MI->getOperand(2);
12673     if (Op.isImm())
12674       AM.IndexReg = Op.getImm();
12675     Op = MI->getOperand(3);
12676     if (Op.isGlobal()) {
12677       AM.GV = Op.getGlobal();
12678     } else {
12679       AM.Disp = Op.getImm();
12680     }
12681     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12682                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12683
12684     // Reload the original control word now.
12685     addFrameReference(BuildMI(*BB, MI, DL,
12686                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12687
12688     MI->eraseFromParent();   // The pseudo instruction is gone now.
12689     return BB;
12690   }
12691     // String/text processing lowering.
12692   case X86::PCMPISTRM128REG:
12693   case X86::VPCMPISTRM128REG:
12694     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12695   case X86::PCMPISTRM128MEM:
12696   case X86::VPCMPISTRM128MEM:
12697     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12698   case X86::PCMPESTRM128REG:
12699   case X86::VPCMPESTRM128REG:
12700     return EmitPCMP(MI, BB, 5, false /* in mem */);
12701   case X86::PCMPESTRM128MEM:
12702   case X86::VPCMPESTRM128MEM:
12703     return EmitPCMP(MI, BB, 5, true /* in mem */);
12704
12705     // Thread synchronization.
12706   case X86::MONITOR:
12707     return EmitMonitor(MI, BB);
12708   case X86::MWAIT:
12709     return EmitMwait(MI, BB);
12710
12711     // Atomic Lowering.
12712   case X86::ATOMAND32:
12713     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12714                                                X86::AND32ri, X86::MOV32rm,
12715                                                X86::LCMPXCHG32,
12716                                                X86::NOT32r, X86::EAX,
12717                                                &X86::GR32RegClass);
12718   case X86::ATOMOR32:
12719     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12720                                                X86::OR32ri, X86::MOV32rm,
12721                                                X86::LCMPXCHG32,
12722                                                X86::NOT32r, X86::EAX,
12723                                                &X86::GR32RegClass);
12724   case X86::ATOMXOR32:
12725     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12726                                                X86::XOR32ri, X86::MOV32rm,
12727                                                X86::LCMPXCHG32,
12728                                                X86::NOT32r, X86::EAX,
12729                                                &X86::GR32RegClass);
12730   case X86::ATOMNAND32:
12731     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12732                                                X86::AND32ri, X86::MOV32rm,
12733                                                X86::LCMPXCHG32,
12734                                                X86::NOT32r, X86::EAX,
12735                                                &X86::GR32RegClass, true);
12736   case X86::ATOMMIN32:
12737     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12738   case X86::ATOMMAX32:
12739     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12740   case X86::ATOMUMIN32:
12741     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12742   case X86::ATOMUMAX32:
12743     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12744
12745   case X86::ATOMAND16:
12746     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12747                                                X86::AND16ri, X86::MOV16rm,
12748                                                X86::LCMPXCHG16,
12749                                                X86::NOT16r, X86::AX,
12750                                                &X86::GR16RegClass);
12751   case X86::ATOMOR16:
12752     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12753                                                X86::OR16ri, X86::MOV16rm,
12754                                                X86::LCMPXCHG16,
12755                                                X86::NOT16r, X86::AX,
12756                                                &X86::GR16RegClass);
12757   case X86::ATOMXOR16:
12758     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12759                                                X86::XOR16ri, X86::MOV16rm,
12760                                                X86::LCMPXCHG16,
12761                                                X86::NOT16r, X86::AX,
12762                                                &X86::GR16RegClass);
12763   case X86::ATOMNAND16:
12764     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12765                                                X86::AND16ri, X86::MOV16rm,
12766                                                X86::LCMPXCHG16,
12767                                                X86::NOT16r, X86::AX,
12768                                                &X86::GR16RegClass, true);
12769   case X86::ATOMMIN16:
12770     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12771   case X86::ATOMMAX16:
12772     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12773   case X86::ATOMUMIN16:
12774     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12775   case X86::ATOMUMAX16:
12776     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12777
12778   case X86::ATOMAND8:
12779     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12780                                                X86::AND8ri, X86::MOV8rm,
12781                                                X86::LCMPXCHG8,
12782                                                X86::NOT8r, X86::AL,
12783                                                &X86::GR8RegClass);
12784   case X86::ATOMOR8:
12785     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12786                                                X86::OR8ri, X86::MOV8rm,
12787                                                X86::LCMPXCHG8,
12788                                                X86::NOT8r, X86::AL,
12789                                                &X86::GR8RegClass);
12790   case X86::ATOMXOR8:
12791     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12792                                                X86::XOR8ri, X86::MOV8rm,
12793                                                X86::LCMPXCHG8,
12794                                                X86::NOT8r, X86::AL,
12795                                                &X86::GR8RegClass);
12796   case X86::ATOMNAND8:
12797     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12798                                                X86::AND8ri, X86::MOV8rm,
12799                                                X86::LCMPXCHG8,
12800                                                X86::NOT8r, X86::AL,
12801                                                &X86::GR8RegClass, true);
12802   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12803   // This group is for 64-bit host.
12804   case X86::ATOMAND64:
12805     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12806                                                X86::AND64ri32, X86::MOV64rm,
12807                                                X86::LCMPXCHG64,
12808                                                X86::NOT64r, X86::RAX,
12809                                                &X86::GR64RegClass);
12810   case X86::ATOMOR64:
12811     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12812                                                X86::OR64ri32, X86::MOV64rm,
12813                                                X86::LCMPXCHG64,
12814                                                X86::NOT64r, X86::RAX,
12815                                                &X86::GR64RegClass);
12816   case X86::ATOMXOR64:
12817     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12818                                                X86::XOR64ri32, X86::MOV64rm,
12819                                                X86::LCMPXCHG64,
12820                                                X86::NOT64r, X86::RAX,
12821                                                &X86::GR64RegClass);
12822   case X86::ATOMNAND64:
12823     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12824                                                X86::AND64ri32, X86::MOV64rm,
12825                                                X86::LCMPXCHG64,
12826                                                X86::NOT64r, X86::RAX,
12827                                                &X86::GR64RegClass, true);
12828   case X86::ATOMMIN64:
12829     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12830   case X86::ATOMMAX64:
12831     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12832   case X86::ATOMUMIN64:
12833     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12834   case X86::ATOMUMAX64:
12835     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12836
12837   // This group does 64-bit operations on a 32-bit host.
12838   case X86::ATOMAND6432:
12839     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12840                                                X86::AND32rr, X86::AND32rr,
12841                                                X86::AND32ri, X86::AND32ri,
12842                                                false);
12843   case X86::ATOMOR6432:
12844     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12845                                                X86::OR32rr, X86::OR32rr,
12846                                                X86::OR32ri, X86::OR32ri,
12847                                                false);
12848   case X86::ATOMXOR6432:
12849     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12850                                                X86::XOR32rr, X86::XOR32rr,
12851                                                X86::XOR32ri, X86::XOR32ri,
12852                                                false);
12853   case X86::ATOMNAND6432:
12854     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12855                                                X86::AND32rr, X86::AND32rr,
12856                                                X86::AND32ri, X86::AND32ri,
12857                                                true);
12858   case X86::ATOMADD6432:
12859     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12860                                                X86::ADD32rr, X86::ADC32rr,
12861                                                X86::ADD32ri, X86::ADC32ri,
12862                                                false);
12863   case X86::ATOMSUB6432:
12864     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12865                                                X86::SUB32rr, X86::SBB32rr,
12866                                                X86::SUB32ri, X86::SBB32ri,
12867                                                false);
12868   case X86::ATOMSWAP6432:
12869     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12870                                                X86::MOV32rr, X86::MOV32rr,
12871                                                X86::MOV32ri, X86::MOV32ri,
12872                                                false);
12873   case X86::VASTART_SAVE_XMM_REGS:
12874     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12875
12876   case X86::VAARG_64:
12877     return EmitVAARG64WithCustomInserter(MI, BB);
12878   }
12879 }
12880
12881 //===----------------------------------------------------------------------===//
12882 //                           X86 Optimization Hooks
12883 //===----------------------------------------------------------------------===//
12884
12885 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12886                                                        APInt &KnownZero,
12887                                                        APInt &KnownOne,
12888                                                        const SelectionDAG &DAG,
12889                                                        unsigned Depth) const {
12890   unsigned BitWidth = KnownZero.getBitWidth();
12891   unsigned Opc = Op.getOpcode();
12892   assert((Opc >= ISD::BUILTIN_OP_END ||
12893           Opc == ISD::INTRINSIC_WO_CHAIN ||
12894           Opc == ISD::INTRINSIC_W_CHAIN ||
12895           Opc == ISD::INTRINSIC_VOID) &&
12896          "Should use MaskedValueIsZero if you don't know whether Op"
12897          " is a target node!");
12898
12899   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12900   switch (Opc) {
12901   default: break;
12902   case X86ISD::ADD:
12903   case X86ISD::SUB:
12904   case X86ISD::ADC:
12905   case X86ISD::SBB:
12906   case X86ISD::SMUL:
12907   case X86ISD::UMUL:
12908   case X86ISD::INC:
12909   case X86ISD::DEC:
12910   case X86ISD::OR:
12911   case X86ISD::XOR:
12912   case X86ISD::AND:
12913     // These nodes' second result is a boolean.
12914     if (Op.getResNo() == 0)
12915       break;
12916     // Fallthrough
12917   case X86ISD::SETCC:
12918     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12919     break;
12920   case ISD::INTRINSIC_WO_CHAIN: {
12921     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12922     unsigned NumLoBits = 0;
12923     switch (IntId) {
12924     default: break;
12925     case Intrinsic::x86_sse_movmsk_ps:
12926     case Intrinsic::x86_avx_movmsk_ps_256:
12927     case Intrinsic::x86_sse2_movmsk_pd:
12928     case Intrinsic::x86_avx_movmsk_pd_256:
12929     case Intrinsic::x86_mmx_pmovmskb:
12930     case Intrinsic::x86_sse2_pmovmskb_128:
12931     case Intrinsic::x86_avx2_pmovmskb: {
12932       // High bits of movmskp{s|d}, pmovmskb are known zero.
12933       switch (IntId) {
12934         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12935         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12936         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12937         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12938         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12939         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12940         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12941         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12942       }
12943       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12944       break;
12945     }
12946     }
12947     break;
12948   }
12949   }
12950 }
12951
12952 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12953                                                          unsigned Depth) const {
12954   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12955   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12956     return Op.getValueType().getScalarType().getSizeInBits();
12957
12958   // Fallback case.
12959   return 1;
12960 }
12961
12962 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12963 /// node is a GlobalAddress + offset.
12964 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12965                                        const GlobalValue* &GA,
12966                                        int64_t &Offset) const {
12967   if (N->getOpcode() == X86ISD::Wrapper) {
12968     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12969       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12970       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12971       return true;
12972     }
12973   }
12974   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12975 }
12976
12977 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12978 /// same as extracting the high 128-bit part of 256-bit vector and then
12979 /// inserting the result into the low part of a new 256-bit vector
12980 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12981   EVT VT = SVOp->getValueType(0);
12982   unsigned NumElems = VT.getVectorNumElements();
12983
12984   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12985   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
12986     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12987         SVOp->getMaskElt(j) >= 0)
12988       return false;
12989
12990   return true;
12991 }
12992
12993 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12994 /// same as extracting the low 128-bit part of 256-bit vector and then
12995 /// inserting the result into the high part of a new 256-bit vector
12996 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12997   EVT VT = SVOp->getValueType(0);
12998   unsigned NumElems = VT.getVectorNumElements();
12999
13000   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13001   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13002     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13003         SVOp->getMaskElt(j) >= 0)
13004       return false;
13005
13006   return true;
13007 }
13008
13009 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13010 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13011                                         TargetLowering::DAGCombinerInfo &DCI,
13012                                         const X86Subtarget* Subtarget) {
13013   DebugLoc dl = N->getDebugLoc();
13014   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13015   SDValue V1 = SVOp->getOperand(0);
13016   SDValue V2 = SVOp->getOperand(1);
13017   EVT VT = SVOp->getValueType(0);
13018   unsigned NumElems = VT.getVectorNumElements();
13019
13020   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13021       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13022     //
13023     //                   0,0,0,...
13024     //                      |
13025     //    V      UNDEF    BUILD_VECTOR    UNDEF
13026     //     \      /           \           /
13027     //  CONCAT_VECTOR         CONCAT_VECTOR
13028     //         \                  /
13029     //          \                /
13030     //          RESULT: V + zero extended
13031     //
13032     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13033         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13034         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13035       return SDValue();
13036
13037     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13038       return SDValue();
13039
13040     // To match the shuffle mask, the first half of the mask should
13041     // be exactly the first vector, and all the rest a splat with the
13042     // first element of the second one.
13043     for (unsigned i = 0; i != NumElems/2; ++i)
13044       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13045           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13046         return SDValue();
13047
13048     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13049     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13050       if (Ld->hasNUsesOfValue(1, 0)) {
13051         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13052         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13053         SDValue ResNode =
13054           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13055                                   Ld->getMemoryVT(),
13056                                   Ld->getPointerInfo(),
13057                                   Ld->getAlignment(),
13058                                   false/*isVolatile*/, true/*ReadMem*/,
13059                                   false/*WriteMem*/);
13060         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13061       }
13062     } 
13063
13064     // Emit a zeroed vector and insert the desired subvector on its
13065     // first half.
13066     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13067     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13068     return DCI.CombineTo(N, InsV);
13069   }
13070
13071   //===--------------------------------------------------------------------===//
13072   // Combine some shuffles into subvector extracts and inserts:
13073   //
13074
13075   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13076   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13077     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13078     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13079     return DCI.CombineTo(N, InsV);
13080   }
13081
13082   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13083   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13084     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13085     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13086     return DCI.CombineTo(N, InsV);
13087   }
13088
13089   return SDValue();
13090 }
13091
13092 /// PerformShuffleCombine - Performs several different shuffle combines.
13093 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13094                                      TargetLowering::DAGCombinerInfo &DCI,
13095                                      const X86Subtarget *Subtarget) {
13096   DebugLoc dl = N->getDebugLoc();
13097   EVT VT = N->getValueType(0);
13098
13099   // Don't create instructions with illegal types after legalize types has run.
13100   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13101   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13102     return SDValue();
13103
13104   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13105   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13106       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13107     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13108
13109   // Only handle 128 wide vector from here on.
13110   if (VT.getSizeInBits() != 128)
13111     return SDValue();
13112
13113   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13114   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13115   // consecutive, non-overlapping, and in the right order.
13116   SmallVector<SDValue, 16> Elts;
13117   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13118     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13119
13120   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13121 }
13122
13123
13124 /// DCI, PerformTruncateCombine - Converts truncate operation to
13125 /// a sequence of vector shuffle operations.
13126 /// It is possible when we truncate 256-bit vector to 128-bit vector
13127
13128 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13129                                                   DAGCombinerInfo &DCI) const {
13130   if (!DCI.isBeforeLegalizeOps())
13131     return SDValue();
13132
13133   if (!Subtarget->hasAVX())
13134     return SDValue();
13135
13136   EVT VT = N->getValueType(0);
13137   SDValue Op = N->getOperand(0);
13138   EVT OpVT = Op.getValueType();
13139   DebugLoc dl = N->getDebugLoc();
13140
13141   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13142
13143     if (Subtarget->hasAVX2()) {
13144       // AVX2: v4i64 -> v4i32
13145
13146       // VPERMD
13147       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13148
13149       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13150       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13151                                 ShufMask);
13152
13153       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13154                          DAG.getIntPtrConstant(0));
13155     }
13156
13157     // AVX: v4i64 -> v4i32
13158     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13159                                DAG.getIntPtrConstant(0));
13160
13161     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13162                                DAG.getIntPtrConstant(2));
13163
13164     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13165     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13166
13167     // PSHUFD
13168     static const int ShufMask1[] = {0, 2, 0, 0};
13169
13170     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13171     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13172
13173     // MOVLHPS
13174     static const int ShufMask2[] = {0, 1, 4, 5};
13175
13176     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13177   }
13178
13179   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13180
13181     if (Subtarget->hasAVX2()) {
13182       // AVX2: v8i32 -> v8i16
13183
13184       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13185
13186       // PSHUFB
13187       SmallVector<SDValue,32> pshufbMask;
13188       for (unsigned i = 0; i < 2; ++i) {
13189         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13190         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13191         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13192         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13193         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13194         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13195         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13196         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13197         for (unsigned j = 0; j < 8; ++j)
13198           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13199       }
13200       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13201                                &pshufbMask[0], 32);
13202       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13203
13204       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13205
13206       static const int ShufMask[] = {0,  2,  -1,  -1};
13207       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13208                                 &ShufMask[0]);
13209
13210       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13211                        DAG.getIntPtrConstant(0));
13212
13213       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13214     }
13215
13216     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13217                                DAG.getIntPtrConstant(0));
13218
13219     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13220                                DAG.getIntPtrConstant(4));
13221
13222     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13223     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13224
13225     // PSHUFB
13226     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13227                                    -1, -1, -1, -1, -1, -1, -1, -1};
13228
13229     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13230                                 ShufMask1);
13231     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13232                                 ShufMask1);
13233
13234     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13235     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13236
13237     // MOVLHPS
13238     static const int ShufMask2[] = {0, 1, 4, 5};
13239
13240     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13241     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13242   }
13243
13244   return SDValue();
13245 }
13246
13247 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13248 /// specific shuffle of a load can be folded into a single element load.
13249 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13250 /// shuffles have been customed lowered so we need to handle those here.
13251 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13252                                          TargetLowering::DAGCombinerInfo &DCI) {
13253   if (DCI.isBeforeLegalizeOps())
13254     return SDValue();
13255
13256   SDValue InVec = N->getOperand(0);
13257   SDValue EltNo = N->getOperand(1);
13258
13259   if (!isa<ConstantSDNode>(EltNo))
13260     return SDValue();
13261
13262   EVT VT = InVec.getValueType();
13263
13264   bool HasShuffleIntoBitcast = false;
13265   if (InVec.getOpcode() == ISD::BITCAST) {
13266     // Don't duplicate a load with other uses.
13267     if (!InVec.hasOneUse())
13268       return SDValue();
13269     EVT BCVT = InVec.getOperand(0).getValueType();
13270     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13271       return SDValue();
13272     InVec = InVec.getOperand(0);
13273     HasShuffleIntoBitcast = true;
13274   }
13275
13276   if (!isTargetShuffle(InVec.getOpcode()))
13277     return SDValue();
13278
13279   // Don't duplicate a load with other uses.
13280   if (!InVec.hasOneUse())
13281     return SDValue();
13282
13283   SmallVector<int, 16> ShuffleMask;
13284   bool UnaryShuffle;
13285   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13286                             UnaryShuffle))
13287     return SDValue();
13288
13289   // Select the input vector, guarding against out of range extract vector.
13290   unsigned NumElems = VT.getVectorNumElements();
13291   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13292   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13293   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13294                                          : InVec.getOperand(1);
13295
13296   // If inputs to shuffle are the same for both ops, then allow 2 uses
13297   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13298
13299   if (LdNode.getOpcode() == ISD::BITCAST) {
13300     // Don't duplicate a load with other uses.
13301     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13302       return SDValue();
13303
13304     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13305     LdNode = LdNode.getOperand(0);
13306   }
13307
13308   if (!ISD::isNormalLoad(LdNode.getNode()))
13309     return SDValue();
13310
13311   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13312
13313   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13314     return SDValue();
13315
13316   if (HasShuffleIntoBitcast) {
13317     // If there's a bitcast before the shuffle, check if the load type and
13318     // alignment is valid.
13319     unsigned Align = LN0->getAlignment();
13320     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13321     unsigned NewAlign = TLI.getTargetData()->
13322       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13323
13324     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13325       return SDValue();
13326   }
13327
13328   // All checks match so transform back to vector_shuffle so that DAG combiner
13329   // can finish the job
13330   DebugLoc dl = N->getDebugLoc();
13331
13332   // Create shuffle node taking into account the case that its a unary shuffle
13333   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13334   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13335                                  InVec.getOperand(0), Shuffle,
13336                                  &ShuffleMask[0]);
13337   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13338   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13339                      EltNo);
13340 }
13341
13342 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13343 /// generation and convert it from being a bunch of shuffles and extracts
13344 /// to a simple store and scalar loads to extract the elements.
13345 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13346                                          TargetLowering::DAGCombinerInfo &DCI) {
13347   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13348   if (NewOp.getNode())
13349     return NewOp;
13350
13351   SDValue InputVector = N->getOperand(0);
13352
13353   // Only operate on vectors of 4 elements, where the alternative shuffling
13354   // gets to be more expensive.
13355   if (InputVector.getValueType() != MVT::v4i32)
13356     return SDValue();
13357
13358   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13359   // single use which is a sign-extend or zero-extend, and all elements are
13360   // used.
13361   SmallVector<SDNode *, 4> Uses;
13362   unsigned ExtractedElements = 0;
13363   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13364        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13365     if (UI.getUse().getResNo() != InputVector.getResNo())
13366       return SDValue();
13367
13368     SDNode *Extract = *UI;
13369     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13370       return SDValue();
13371
13372     if (Extract->getValueType(0) != MVT::i32)
13373       return SDValue();
13374     if (!Extract->hasOneUse())
13375       return SDValue();
13376     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13377         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13378       return SDValue();
13379     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13380       return SDValue();
13381
13382     // Record which element was extracted.
13383     ExtractedElements |=
13384       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13385
13386     Uses.push_back(Extract);
13387   }
13388
13389   // If not all the elements were used, this may not be worthwhile.
13390   if (ExtractedElements != 15)
13391     return SDValue();
13392
13393   // Ok, we've now decided to do the transformation.
13394   DebugLoc dl = InputVector.getDebugLoc();
13395
13396   // Store the value to a temporary stack slot.
13397   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13398   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13399                             MachinePointerInfo(), false, false, 0);
13400
13401   // Replace each use (extract) with a load of the appropriate element.
13402   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13403        UE = Uses.end(); UI != UE; ++UI) {
13404     SDNode *Extract = *UI;
13405
13406     // cOMpute the element's address.
13407     SDValue Idx = Extract->getOperand(1);
13408     unsigned EltSize =
13409         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13410     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13411     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13412     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13413
13414     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13415                                      StackPtr, OffsetVal);
13416
13417     // Load the scalar.
13418     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13419                                      ScalarAddr, MachinePointerInfo(),
13420                                      false, false, false, 0);
13421
13422     // Replace the exact with the load.
13423     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13424   }
13425
13426   // The replacement was made in place; don't return anything.
13427   return SDValue();
13428 }
13429
13430 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13431 /// nodes.
13432 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13433                                     TargetLowering::DAGCombinerInfo &DCI,
13434                                     const X86Subtarget *Subtarget) {
13435   DebugLoc DL = N->getDebugLoc();
13436   SDValue Cond = N->getOperand(0);
13437   // Get the LHS/RHS of the select.
13438   SDValue LHS = N->getOperand(1);
13439   SDValue RHS = N->getOperand(2);
13440   EVT VT = LHS.getValueType();
13441
13442   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13443   // instructions match the semantics of the common C idiom x<y?x:y but not
13444   // x<=y?x:y, because of how they handle negative zero (which can be
13445   // ignored in unsafe-math mode).
13446   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13447       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13448       (Subtarget->hasSSE2() ||
13449        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13450     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13451
13452     unsigned Opcode = 0;
13453     // Check for x CC y ? x : y.
13454     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13455         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13456       switch (CC) {
13457       default: break;
13458       case ISD::SETULT:
13459         // Converting this to a min would handle NaNs incorrectly, and swapping
13460         // the operands would cause it to handle comparisons between positive
13461         // and negative zero incorrectly.
13462         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13463           if (!DAG.getTarget().Options.UnsafeFPMath &&
13464               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13465             break;
13466           std::swap(LHS, RHS);
13467         }
13468         Opcode = X86ISD::FMIN;
13469         break;
13470       case ISD::SETOLE:
13471         // Converting this to a min would handle comparisons between positive
13472         // and negative zero incorrectly.
13473         if (!DAG.getTarget().Options.UnsafeFPMath &&
13474             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13475           break;
13476         Opcode = X86ISD::FMIN;
13477         break;
13478       case ISD::SETULE:
13479         // Converting this to a min would handle both negative zeros and NaNs
13480         // incorrectly, but we can swap the operands to fix both.
13481         std::swap(LHS, RHS);
13482       case ISD::SETOLT:
13483       case ISD::SETLT:
13484       case ISD::SETLE:
13485         Opcode = X86ISD::FMIN;
13486         break;
13487
13488       case ISD::SETOGE:
13489         // Converting this to a max would handle comparisons between positive
13490         // and negative zero incorrectly.
13491         if (!DAG.getTarget().Options.UnsafeFPMath &&
13492             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13493           break;
13494         Opcode = X86ISD::FMAX;
13495         break;
13496       case ISD::SETUGT:
13497         // Converting this to a max would handle NaNs incorrectly, and swapping
13498         // the operands would cause it to handle comparisons between positive
13499         // and negative zero incorrectly.
13500         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13501           if (!DAG.getTarget().Options.UnsafeFPMath &&
13502               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13503             break;
13504           std::swap(LHS, RHS);
13505         }
13506         Opcode = X86ISD::FMAX;
13507         break;
13508       case ISD::SETUGE:
13509         // Converting this to a max would handle both negative zeros and NaNs
13510         // incorrectly, but we can swap the operands to fix both.
13511         std::swap(LHS, RHS);
13512       case ISD::SETOGT:
13513       case ISD::SETGT:
13514       case ISD::SETGE:
13515         Opcode = X86ISD::FMAX;
13516         break;
13517       }
13518     // Check for x CC y ? y : x -- a min/max with reversed arms.
13519     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13520                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13521       switch (CC) {
13522       default: break;
13523       case ISD::SETOGE:
13524         // Converting this to a min would handle comparisons between positive
13525         // and negative zero incorrectly, and swapping the operands would
13526         // cause it to handle NaNs incorrectly.
13527         if (!DAG.getTarget().Options.UnsafeFPMath &&
13528             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13529           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13530             break;
13531           std::swap(LHS, RHS);
13532         }
13533         Opcode = X86ISD::FMIN;
13534         break;
13535       case ISD::SETUGT:
13536         // Converting this to a min would handle NaNs incorrectly.
13537         if (!DAG.getTarget().Options.UnsafeFPMath &&
13538             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13539           break;
13540         Opcode = X86ISD::FMIN;
13541         break;
13542       case ISD::SETUGE:
13543         // Converting this to a min would handle both negative zeros and NaNs
13544         // incorrectly, but we can swap the operands to fix both.
13545         std::swap(LHS, RHS);
13546       case ISD::SETOGT:
13547       case ISD::SETGT:
13548       case ISD::SETGE:
13549         Opcode = X86ISD::FMIN;
13550         break;
13551
13552       case ISD::SETULT:
13553         // Converting this to a max would handle NaNs incorrectly.
13554         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13555           break;
13556         Opcode = X86ISD::FMAX;
13557         break;
13558       case ISD::SETOLE:
13559         // Converting this to a max would handle comparisons between positive
13560         // and negative zero incorrectly, and swapping the operands would
13561         // cause it to handle NaNs incorrectly.
13562         if (!DAG.getTarget().Options.UnsafeFPMath &&
13563             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13564           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13565             break;
13566           std::swap(LHS, RHS);
13567         }
13568         Opcode = X86ISD::FMAX;
13569         break;
13570       case ISD::SETULE:
13571         // Converting this to a max would handle both negative zeros and NaNs
13572         // incorrectly, but we can swap the operands to fix both.
13573         std::swap(LHS, RHS);
13574       case ISD::SETOLT:
13575       case ISD::SETLT:
13576       case ISD::SETLE:
13577         Opcode = X86ISD::FMAX;
13578         break;
13579       }
13580     }
13581
13582     if (Opcode)
13583       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13584   }
13585
13586   // If this is a select between two integer constants, try to do some
13587   // optimizations.
13588   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13589     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13590       // Don't do this for crazy integer types.
13591       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13592         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13593         // so that TrueC (the true value) is larger than FalseC.
13594         bool NeedsCondInvert = false;
13595
13596         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13597             // Efficiently invertible.
13598             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13599              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13600               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13601           NeedsCondInvert = true;
13602           std::swap(TrueC, FalseC);
13603         }
13604
13605         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13606         if (FalseC->getAPIntValue() == 0 &&
13607             TrueC->getAPIntValue().isPowerOf2()) {
13608           if (NeedsCondInvert) // Invert the condition if needed.
13609             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13610                                DAG.getConstant(1, Cond.getValueType()));
13611
13612           // Zero extend the condition if needed.
13613           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13614
13615           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13616           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13617                              DAG.getConstant(ShAmt, MVT::i8));
13618         }
13619
13620         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13621         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13622           if (NeedsCondInvert) // Invert the condition if needed.
13623             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13624                                DAG.getConstant(1, Cond.getValueType()));
13625
13626           // Zero extend the condition if needed.
13627           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13628                              FalseC->getValueType(0), Cond);
13629           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13630                              SDValue(FalseC, 0));
13631         }
13632
13633         // Optimize cases that will turn into an LEA instruction.  This requires
13634         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13635         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13636           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13637           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13638
13639           bool isFastMultiplier = false;
13640           if (Diff < 10) {
13641             switch ((unsigned char)Diff) {
13642               default: break;
13643               case 1:  // result = add base, cond
13644               case 2:  // result = lea base(    , cond*2)
13645               case 3:  // result = lea base(cond, cond*2)
13646               case 4:  // result = lea base(    , cond*4)
13647               case 5:  // result = lea base(cond, cond*4)
13648               case 8:  // result = lea base(    , cond*8)
13649               case 9:  // result = lea base(cond, cond*8)
13650                 isFastMultiplier = true;
13651                 break;
13652             }
13653           }
13654
13655           if (isFastMultiplier) {
13656             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13657             if (NeedsCondInvert) // Invert the condition if needed.
13658               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13659                                  DAG.getConstant(1, Cond.getValueType()));
13660
13661             // Zero extend the condition if needed.
13662             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13663                                Cond);
13664             // Scale the condition by the difference.
13665             if (Diff != 1)
13666               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13667                                  DAG.getConstant(Diff, Cond.getValueType()));
13668
13669             // Add the base if non-zero.
13670             if (FalseC->getAPIntValue() != 0)
13671               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13672                                  SDValue(FalseC, 0));
13673             return Cond;
13674           }
13675         }
13676       }
13677   }
13678
13679   // Canonicalize max and min:
13680   // (x > y) ? x : y -> (x >= y) ? x : y
13681   // (x < y) ? x : y -> (x <= y) ? x : y
13682   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13683   // the need for an extra compare
13684   // against zero. e.g.
13685   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13686   // subl   %esi, %edi
13687   // testl  %edi, %edi
13688   // movl   $0, %eax
13689   // cmovgl %edi, %eax
13690   // =>
13691   // xorl   %eax, %eax
13692   // subl   %esi, $edi
13693   // cmovsl %eax, %edi
13694   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13695       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13696       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13697     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13698     switch (CC) {
13699     default: break;
13700     case ISD::SETLT:
13701     case ISD::SETGT: {
13702       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13703       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13704                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13705       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13706     }
13707     }
13708   }
13709
13710   // If we know that this node is legal then we know that it is going to be
13711   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13712   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13713   // to simplify previous instructions.
13714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13715   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13716       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13717     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13718
13719     // Don't optimize vector selects that map to mask-registers.
13720     if (BitWidth == 1)
13721       return SDValue();
13722
13723     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13724     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13725
13726     APInt KnownZero, KnownOne;
13727     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13728                                           DCI.isBeforeLegalizeOps());
13729     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13730         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13731       DCI.CommitTargetLoweringOpt(TLO);
13732   }
13733
13734   return SDValue();
13735 }
13736
13737 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13738 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13739                                   TargetLowering::DAGCombinerInfo &DCI) {
13740   DebugLoc DL = N->getDebugLoc();
13741
13742   // If the flag operand isn't dead, don't touch this CMOV.
13743   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13744     return SDValue();
13745
13746   SDValue FalseOp = N->getOperand(0);
13747   SDValue TrueOp = N->getOperand(1);
13748   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13749   SDValue Cond = N->getOperand(3);
13750   if (CC == X86::COND_E || CC == X86::COND_NE) {
13751     switch (Cond.getOpcode()) {
13752     default: break;
13753     case X86ISD::BSR:
13754     case X86ISD::BSF:
13755       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13756       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13757         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13758     }
13759   }
13760
13761   // If this is a select between two integer constants, try to do some
13762   // optimizations.  Note that the operands are ordered the opposite of SELECT
13763   // operands.
13764   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13765     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13766       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13767       // larger than FalseC (the false value).
13768       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13769         CC = X86::GetOppositeBranchCondition(CC);
13770         std::swap(TrueC, FalseC);
13771       }
13772
13773       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13774       // This is efficient for any integer data type (including i8/i16) and
13775       // shift amount.
13776       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13777         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13778                            DAG.getConstant(CC, MVT::i8), Cond);
13779
13780         // Zero extend the condition if needed.
13781         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13782
13783         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13784         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13785                            DAG.getConstant(ShAmt, MVT::i8));
13786         if (N->getNumValues() == 2)  // Dead flag value?
13787           return DCI.CombineTo(N, Cond, SDValue());
13788         return Cond;
13789       }
13790
13791       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13792       // for any integer data type, including i8/i16.
13793       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13794         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13795                            DAG.getConstant(CC, MVT::i8), Cond);
13796
13797         // Zero extend the condition if needed.
13798         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13799                            FalseC->getValueType(0), Cond);
13800         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13801                            SDValue(FalseC, 0));
13802
13803         if (N->getNumValues() == 2)  // Dead flag value?
13804           return DCI.CombineTo(N, Cond, SDValue());
13805         return Cond;
13806       }
13807
13808       // Optimize cases that will turn into an LEA instruction.  This requires
13809       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13810       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13811         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13812         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13813
13814         bool isFastMultiplier = false;
13815         if (Diff < 10) {
13816           switch ((unsigned char)Diff) {
13817           default: break;
13818           case 1:  // result = add base, cond
13819           case 2:  // result = lea base(    , cond*2)
13820           case 3:  // result = lea base(cond, cond*2)
13821           case 4:  // result = lea base(    , cond*4)
13822           case 5:  // result = lea base(cond, cond*4)
13823           case 8:  // result = lea base(    , cond*8)
13824           case 9:  // result = lea base(cond, cond*8)
13825             isFastMultiplier = true;
13826             break;
13827           }
13828         }
13829
13830         if (isFastMultiplier) {
13831           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13832           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13833                              DAG.getConstant(CC, MVT::i8), Cond);
13834           // Zero extend the condition if needed.
13835           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13836                              Cond);
13837           // Scale the condition by the difference.
13838           if (Diff != 1)
13839             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13840                                DAG.getConstant(Diff, Cond.getValueType()));
13841
13842           // Add the base if non-zero.
13843           if (FalseC->getAPIntValue() != 0)
13844             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13845                                SDValue(FalseC, 0));
13846           if (N->getNumValues() == 2)  // Dead flag value?
13847             return DCI.CombineTo(N, Cond, SDValue());
13848           return Cond;
13849         }
13850       }
13851     }
13852   }
13853   return SDValue();
13854 }
13855
13856
13857 /// PerformMulCombine - Optimize a single multiply with constant into two
13858 /// in order to implement it with two cheaper instructions, e.g.
13859 /// LEA + SHL, LEA + LEA.
13860 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13861                                  TargetLowering::DAGCombinerInfo &DCI) {
13862   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13863     return SDValue();
13864
13865   EVT VT = N->getValueType(0);
13866   if (VT != MVT::i64)
13867     return SDValue();
13868
13869   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13870   if (!C)
13871     return SDValue();
13872   uint64_t MulAmt = C->getZExtValue();
13873   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13874     return SDValue();
13875
13876   uint64_t MulAmt1 = 0;
13877   uint64_t MulAmt2 = 0;
13878   if ((MulAmt % 9) == 0) {
13879     MulAmt1 = 9;
13880     MulAmt2 = MulAmt / 9;
13881   } else if ((MulAmt % 5) == 0) {
13882     MulAmt1 = 5;
13883     MulAmt2 = MulAmt / 5;
13884   } else if ((MulAmt % 3) == 0) {
13885     MulAmt1 = 3;
13886     MulAmt2 = MulAmt / 3;
13887   }
13888   if (MulAmt2 &&
13889       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13890     DebugLoc DL = N->getDebugLoc();
13891
13892     if (isPowerOf2_64(MulAmt2) &&
13893         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13894       // If second multiplifer is pow2, issue it first. We want the multiply by
13895       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13896       // is an add.
13897       std::swap(MulAmt1, MulAmt2);
13898
13899     SDValue NewMul;
13900     if (isPowerOf2_64(MulAmt1))
13901       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13902                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13903     else
13904       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13905                            DAG.getConstant(MulAmt1, VT));
13906
13907     if (isPowerOf2_64(MulAmt2))
13908       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13909                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13910     else
13911       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13912                            DAG.getConstant(MulAmt2, VT));
13913
13914     // Do not add new nodes to DAG combiner worklist.
13915     DCI.CombineTo(N, NewMul, false);
13916   }
13917   return SDValue();
13918 }
13919
13920 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13921   SDValue N0 = N->getOperand(0);
13922   SDValue N1 = N->getOperand(1);
13923   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13924   EVT VT = N0.getValueType();
13925
13926   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13927   // since the result of setcc_c is all zero's or all ones.
13928   if (VT.isInteger() && !VT.isVector() &&
13929       N1C && N0.getOpcode() == ISD::AND &&
13930       N0.getOperand(1).getOpcode() == ISD::Constant) {
13931     SDValue N00 = N0.getOperand(0);
13932     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13933         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13934           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13935          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13936       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13937       APInt ShAmt = N1C->getAPIntValue();
13938       Mask = Mask.shl(ShAmt);
13939       if (Mask != 0)
13940         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13941                            N00, DAG.getConstant(Mask, VT));
13942     }
13943   }
13944
13945
13946   // Hardware support for vector shifts is sparse which makes us scalarize the
13947   // vector operations in many cases. Also, on sandybridge ADD is faster than
13948   // shl.
13949   // (shl V, 1) -> add V,V
13950   if (isSplatVector(N1.getNode())) {
13951     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13952     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13953     // We shift all of the values by one. In many cases we do not have
13954     // hardware support for this operation. This is better expressed as an ADD
13955     // of two values.
13956     if (N1C && (1 == N1C->getZExtValue())) {
13957       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13958     }
13959   }
13960
13961   return SDValue();
13962 }
13963
13964 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13965 ///                       when possible.
13966 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13967                                    TargetLowering::DAGCombinerInfo &DCI,
13968                                    const X86Subtarget *Subtarget) {
13969   EVT VT = N->getValueType(0);
13970   if (N->getOpcode() == ISD::SHL) {
13971     SDValue V = PerformSHLCombine(N, DAG);
13972     if (V.getNode()) return V;
13973   }
13974
13975   // On X86 with SSE2 support, we can transform this to a vector shift if
13976   // all elements are shifted by the same amount.  We can't do this in legalize
13977   // because the a constant vector is typically transformed to a constant pool
13978   // so we have no knowledge of the shift amount.
13979   if (!Subtarget->hasSSE2())
13980     return SDValue();
13981
13982   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13983       (!Subtarget->hasAVX2() ||
13984        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13985     return SDValue();
13986
13987   SDValue ShAmtOp = N->getOperand(1);
13988   EVT EltVT = VT.getVectorElementType();
13989   DebugLoc DL = N->getDebugLoc();
13990   SDValue BaseShAmt = SDValue();
13991   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13992     unsigned NumElts = VT.getVectorNumElements();
13993     unsigned i = 0;
13994     for (; i != NumElts; ++i) {
13995       SDValue Arg = ShAmtOp.getOperand(i);
13996       if (Arg.getOpcode() == ISD::UNDEF) continue;
13997       BaseShAmt = Arg;
13998       break;
13999     }
14000     // Handle the case where the build_vector is all undef
14001     // FIXME: Should DAG allow this?
14002     if (i == NumElts)
14003       return SDValue();
14004
14005     for (; i != NumElts; ++i) {
14006       SDValue Arg = ShAmtOp.getOperand(i);
14007       if (Arg.getOpcode() == ISD::UNDEF) continue;
14008       if (Arg != BaseShAmt) {
14009         return SDValue();
14010       }
14011     }
14012   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14013              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14014     SDValue InVec = ShAmtOp.getOperand(0);
14015     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14016       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14017       unsigned i = 0;
14018       for (; i != NumElts; ++i) {
14019         SDValue Arg = InVec.getOperand(i);
14020         if (Arg.getOpcode() == ISD::UNDEF) continue;
14021         BaseShAmt = Arg;
14022         break;
14023       }
14024     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14025        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14026          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14027          if (C->getZExtValue() == SplatIdx)
14028            BaseShAmt = InVec.getOperand(1);
14029        }
14030     }
14031     if (BaseShAmt.getNode() == 0) {
14032       // Don't create instructions with illegal types after legalize
14033       // types has run.
14034       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14035           !DCI.isBeforeLegalize())
14036         return SDValue();
14037
14038       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14039                               DAG.getIntPtrConstant(0));
14040     }
14041   } else
14042     return SDValue();
14043
14044   // The shift amount is an i32.
14045   if (EltVT.bitsGT(MVT::i32))
14046     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14047   else if (EltVT.bitsLT(MVT::i32))
14048     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14049
14050   // The shift amount is identical so we can do a vector shift.
14051   SDValue  ValOp = N->getOperand(0);
14052   switch (N->getOpcode()) {
14053   default:
14054     llvm_unreachable("Unknown shift opcode!");
14055   case ISD::SHL:
14056     switch (VT.getSimpleVT().SimpleTy) {
14057     default: return SDValue();
14058     case MVT::v2i64:
14059     case MVT::v4i32:
14060     case MVT::v8i16:
14061     case MVT::v4i64:
14062     case MVT::v8i32:
14063     case MVT::v16i16:
14064       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14065     }
14066   case ISD::SRA:
14067     switch (VT.getSimpleVT().SimpleTy) {
14068     default: return SDValue();
14069     case MVT::v4i32:
14070     case MVT::v8i16:
14071     case MVT::v8i32:
14072     case MVT::v16i16:
14073       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14074     }
14075   case ISD::SRL:
14076     switch (VT.getSimpleVT().SimpleTy) {
14077     default: return SDValue();
14078     case MVT::v2i64:
14079     case MVT::v4i32:
14080     case MVT::v8i16:
14081     case MVT::v4i64:
14082     case MVT::v8i32:
14083     case MVT::v16i16:
14084       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14085     }
14086   }
14087 }
14088
14089
14090 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14091 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14092 // and friends.  Likewise for OR -> CMPNEQSS.
14093 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14094                             TargetLowering::DAGCombinerInfo &DCI,
14095                             const X86Subtarget *Subtarget) {
14096   unsigned opcode;
14097
14098   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14099   // we're requiring SSE2 for both.
14100   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14101     SDValue N0 = N->getOperand(0);
14102     SDValue N1 = N->getOperand(1);
14103     SDValue CMP0 = N0->getOperand(1);
14104     SDValue CMP1 = N1->getOperand(1);
14105     DebugLoc DL = N->getDebugLoc();
14106
14107     // The SETCCs should both refer to the same CMP.
14108     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14109       return SDValue();
14110
14111     SDValue CMP00 = CMP0->getOperand(0);
14112     SDValue CMP01 = CMP0->getOperand(1);
14113     EVT     VT    = CMP00.getValueType();
14114
14115     if (VT == MVT::f32 || VT == MVT::f64) {
14116       bool ExpectingFlags = false;
14117       // Check for any users that want flags:
14118       for (SDNode::use_iterator UI = N->use_begin(),
14119              UE = N->use_end();
14120            !ExpectingFlags && UI != UE; ++UI)
14121         switch (UI->getOpcode()) {
14122         default:
14123         case ISD::BR_CC:
14124         case ISD::BRCOND:
14125         case ISD::SELECT:
14126           ExpectingFlags = true;
14127           break;
14128         case ISD::CopyToReg:
14129         case ISD::SIGN_EXTEND:
14130         case ISD::ZERO_EXTEND:
14131         case ISD::ANY_EXTEND:
14132           break;
14133         }
14134
14135       if (!ExpectingFlags) {
14136         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14137         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14138
14139         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14140           X86::CondCode tmp = cc0;
14141           cc0 = cc1;
14142           cc1 = tmp;
14143         }
14144
14145         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14146             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14147           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14148           X86ISD::NodeType NTOperator = is64BitFP ?
14149             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14150           // FIXME: need symbolic constants for these magic numbers.
14151           // See X86ATTInstPrinter.cpp:printSSECC().
14152           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14153           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14154                                               DAG.getConstant(x86cc, MVT::i8));
14155           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14156                                               OnesOrZeroesF);
14157           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14158                                       DAG.getConstant(1, MVT::i32));
14159           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14160           return OneBitOfTruth;
14161         }
14162       }
14163     }
14164   }
14165   return SDValue();
14166 }
14167
14168 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14169 /// so it can be folded inside ANDNP.
14170 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14171   EVT VT = N->getValueType(0);
14172
14173   // Match direct AllOnes for 128 and 256-bit vectors
14174   if (ISD::isBuildVectorAllOnes(N))
14175     return true;
14176
14177   // Look through a bit convert.
14178   if (N->getOpcode() == ISD::BITCAST)
14179     N = N->getOperand(0).getNode();
14180
14181   // Sometimes the operand may come from a insert_subvector building a 256-bit
14182   // allones vector
14183   if (VT.getSizeInBits() == 256 &&
14184       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14185     SDValue V1 = N->getOperand(0);
14186     SDValue V2 = N->getOperand(1);
14187
14188     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14189         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14190         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14191         ISD::isBuildVectorAllOnes(V2.getNode()))
14192       return true;
14193   }
14194
14195   return false;
14196 }
14197
14198 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14199                                  TargetLowering::DAGCombinerInfo &DCI,
14200                                  const X86Subtarget *Subtarget) {
14201   if (DCI.isBeforeLegalizeOps())
14202     return SDValue();
14203
14204   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14205   if (R.getNode())
14206     return R;
14207
14208   EVT VT = N->getValueType(0);
14209
14210   // Create ANDN, BLSI, and BLSR instructions
14211   // BLSI is X & (-X)
14212   // BLSR is X & (X-1)
14213   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14214     SDValue N0 = N->getOperand(0);
14215     SDValue N1 = N->getOperand(1);
14216     DebugLoc DL = N->getDebugLoc();
14217
14218     // Check LHS for not
14219     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14220       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14221     // Check RHS for not
14222     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14223       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14224
14225     // Check LHS for neg
14226     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14227         isZero(N0.getOperand(0)))
14228       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14229
14230     // Check RHS for neg
14231     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14232         isZero(N1.getOperand(0)))
14233       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14234
14235     // Check LHS for X-1
14236     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14237         isAllOnes(N0.getOperand(1)))
14238       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14239
14240     // Check RHS for X-1
14241     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14242         isAllOnes(N1.getOperand(1)))
14243       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14244
14245     return SDValue();
14246   }
14247
14248   // Want to form ANDNP nodes:
14249   // 1) In the hopes of then easily combining them with OR and AND nodes
14250   //    to form PBLEND/PSIGN.
14251   // 2) To match ANDN packed intrinsics
14252   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14253     return SDValue();
14254
14255   SDValue N0 = N->getOperand(0);
14256   SDValue N1 = N->getOperand(1);
14257   DebugLoc DL = N->getDebugLoc();
14258
14259   // Check LHS for vnot
14260   if (N0.getOpcode() == ISD::XOR &&
14261       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14262       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14263     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14264
14265   // Check RHS for vnot
14266   if (N1.getOpcode() == ISD::XOR &&
14267       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14268       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14269     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14270
14271   return SDValue();
14272 }
14273
14274 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14275                                 TargetLowering::DAGCombinerInfo &DCI,
14276                                 const X86Subtarget *Subtarget) {
14277   if (DCI.isBeforeLegalizeOps())
14278     return SDValue();
14279
14280   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14281   if (R.getNode())
14282     return R;
14283
14284   EVT VT = N->getValueType(0);
14285
14286   SDValue N0 = N->getOperand(0);
14287   SDValue N1 = N->getOperand(1);
14288
14289   // look for psign/blend
14290   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14291     if (!Subtarget->hasSSSE3() ||
14292         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14293       return SDValue();
14294
14295     // Canonicalize pandn to RHS
14296     if (N0.getOpcode() == X86ISD::ANDNP)
14297       std::swap(N0, N1);
14298     // or (and (m, y), (pandn m, x))
14299     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14300       SDValue Mask = N1.getOperand(0);
14301       SDValue X    = N1.getOperand(1);
14302       SDValue Y;
14303       if (N0.getOperand(0) == Mask)
14304         Y = N0.getOperand(1);
14305       if (N0.getOperand(1) == Mask)
14306         Y = N0.getOperand(0);
14307
14308       // Check to see if the mask appeared in both the AND and ANDNP and
14309       if (!Y.getNode())
14310         return SDValue();
14311
14312       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14313       // Look through mask bitcast.
14314       if (Mask.getOpcode() == ISD::BITCAST)
14315         Mask = Mask.getOperand(0);
14316       if (X.getOpcode() == ISD::BITCAST)
14317         X = X.getOperand(0);
14318       if (Y.getOpcode() == ISD::BITCAST)
14319         Y = Y.getOperand(0);
14320
14321       EVT MaskVT = Mask.getValueType();
14322
14323       // Validate that the Mask operand is a vector sra node.
14324       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14325       // there is no psrai.b
14326       if (Mask.getOpcode() != X86ISD::VSRAI)
14327         return SDValue();
14328
14329       // Check that the SRA is all signbits.
14330       SDValue SraC = Mask.getOperand(1);
14331       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14332       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14333       if ((SraAmt + 1) != EltBits)
14334         return SDValue();
14335
14336       DebugLoc DL = N->getDebugLoc();
14337
14338       // Now we know we at least have a plendvb with the mask val.  See if
14339       // we can form a psignb/w/d.
14340       // psign = x.type == y.type == mask.type && y = sub(0, x);
14341       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14342           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14343           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14344         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14345                "Unsupported VT for PSIGN");
14346         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14347         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14348       }
14349       // PBLENDVB only available on SSE 4.1
14350       if (!Subtarget->hasSSE41())
14351         return SDValue();
14352
14353       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14354
14355       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14356       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14357       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14358       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14359       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14360     }
14361   }
14362
14363   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14364     return SDValue();
14365
14366   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14367   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14368     std::swap(N0, N1);
14369   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14370     return SDValue();
14371   if (!N0.hasOneUse() || !N1.hasOneUse())
14372     return SDValue();
14373
14374   SDValue ShAmt0 = N0.getOperand(1);
14375   if (ShAmt0.getValueType() != MVT::i8)
14376     return SDValue();
14377   SDValue ShAmt1 = N1.getOperand(1);
14378   if (ShAmt1.getValueType() != MVT::i8)
14379     return SDValue();
14380   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14381     ShAmt0 = ShAmt0.getOperand(0);
14382   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14383     ShAmt1 = ShAmt1.getOperand(0);
14384
14385   DebugLoc DL = N->getDebugLoc();
14386   unsigned Opc = X86ISD::SHLD;
14387   SDValue Op0 = N0.getOperand(0);
14388   SDValue Op1 = N1.getOperand(0);
14389   if (ShAmt0.getOpcode() == ISD::SUB) {
14390     Opc = X86ISD::SHRD;
14391     std::swap(Op0, Op1);
14392     std::swap(ShAmt0, ShAmt1);
14393   }
14394
14395   unsigned Bits = VT.getSizeInBits();
14396   if (ShAmt1.getOpcode() == ISD::SUB) {
14397     SDValue Sum = ShAmt1.getOperand(0);
14398     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14399       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14400       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14401         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14402       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14403         return DAG.getNode(Opc, DL, VT,
14404                            Op0, Op1,
14405                            DAG.getNode(ISD::TRUNCATE, DL,
14406                                        MVT::i8, ShAmt0));
14407     }
14408   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14409     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14410     if (ShAmt0C &&
14411         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14412       return DAG.getNode(Opc, DL, VT,
14413                          N0.getOperand(0), N1.getOperand(0),
14414                          DAG.getNode(ISD::TRUNCATE, DL,
14415                                        MVT::i8, ShAmt0));
14416   }
14417
14418   return SDValue();
14419 }
14420
14421 // Generate NEG and CMOV for integer abs.
14422 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14423   EVT VT = N->getValueType(0);
14424
14425   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14426   // 8-bit integer abs to NEG and CMOV.
14427   if (VT.isInteger() && VT.getSizeInBits() == 8)
14428     return SDValue();
14429
14430   SDValue N0 = N->getOperand(0);
14431   SDValue N1 = N->getOperand(1);
14432   DebugLoc DL = N->getDebugLoc();
14433
14434   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14435   // and change it to SUB and CMOV.
14436   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14437       N0.getOpcode() == ISD::ADD &&
14438       N0.getOperand(1) == N1 &&
14439       N1.getOpcode() == ISD::SRA &&
14440       N1.getOperand(0) == N0.getOperand(0))
14441     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14442       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14443         // Generate SUB & CMOV.
14444         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14445                                   DAG.getConstant(0, VT), N0.getOperand(0));
14446
14447         SDValue Ops[] = { N0.getOperand(0), Neg,
14448                           DAG.getConstant(X86::COND_GE, MVT::i8),
14449                           SDValue(Neg.getNode(), 1) };
14450         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14451                            Ops, array_lengthof(Ops));
14452       }
14453   return SDValue();
14454 }
14455
14456 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14457 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14458                                  TargetLowering::DAGCombinerInfo &DCI,
14459                                  const X86Subtarget *Subtarget) {
14460   if (DCI.isBeforeLegalizeOps())
14461     return SDValue();
14462
14463   if (Subtarget->hasCMov()) {
14464     SDValue RV = performIntegerAbsCombine(N, DAG);
14465     if (RV.getNode())
14466       return RV;
14467   }
14468
14469   // Try forming BMI if it is available.
14470   if (!Subtarget->hasBMI())
14471     return SDValue();
14472
14473   EVT VT = N->getValueType(0);
14474
14475   if (VT != MVT::i32 && VT != MVT::i64)
14476     return SDValue();
14477
14478   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14479
14480   // Create BLSMSK instructions by finding X ^ (X-1)
14481   SDValue N0 = N->getOperand(0);
14482   SDValue N1 = N->getOperand(1);
14483   DebugLoc DL = N->getDebugLoc();
14484
14485   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14486       isAllOnes(N0.getOperand(1)))
14487     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14488
14489   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14490       isAllOnes(N1.getOperand(1)))
14491     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14492
14493   return SDValue();
14494 }
14495
14496 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14497 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14498                                   TargetLowering::DAGCombinerInfo &DCI,
14499                                   const X86Subtarget *Subtarget) {
14500   LoadSDNode *Ld = cast<LoadSDNode>(N);
14501   EVT RegVT = Ld->getValueType(0);
14502   EVT MemVT = Ld->getMemoryVT();
14503   DebugLoc dl = Ld->getDebugLoc();
14504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14505
14506   ISD::LoadExtType Ext = Ld->getExtensionType();
14507
14508   // If this is a vector EXT Load then attempt to optimize it using a
14509   // shuffle. We need SSE4 for the shuffles.
14510   // TODO: It is possible to support ZExt by zeroing the undef values
14511   // during the shuffle phase or after the shuffle.
14512   if (RegVT.isVector() && RegVT.isInteger() &&
14513       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14514     assert(MemVT != RegVT && "Cannot extend to the same type");
14515     assert(MemVT.isVector() && "Must load a vector from memory");
14516
14517     unsigned NumElems = RegVT.getVectorNumElements();
14518     unsigned RegSz = RegVT.getSizeInBits();
14519     unsigned MemSz = MemVT.getSizeInBits();
14520     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14521
14522     // All sizes must be a power of two.
14523     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14524       return SDValue();
14525
14526     // Attempt to load the original value using scalar loads.
14527     // Find the largest scalar type that divides the total loaded size.
14528     MVT SclrLoadTy = MVT::i8;
14529     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14530          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14531       MVT Tp = (MVT::SimpleValueType)tp;
14532       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14533         SclrLoadTy = Tp;
14534       }
14535     }
14536
14537     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14538     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14539         (64 <= MemSz))
14540       SclrLoadTy = MVT::f64;
14541
14542     // Calculate the number of scalar loads that we need to perform
14543     // in order to load our vector from memory.
14544     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14545
14546     // Represent our vector as a sequence of elements which are the
14547     // largest scalar that we can load.
14548     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14549       RegSz/SclrLoadTy.getSizeInBits());
14550
14551     // Represent the data using the same element type that is stored in
14552     // memory. In practice, we ''widen'' MemVT.
14553     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14554                                   RegSz/MemVT.getScalarType().getSizeInBits());
14555
14556     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14557       "Invalid vector type");
14558
14559     // We can't shuffle using an illegal type.
14560     if (!TLI.isTypeLegal(WideVecVT))
14561       return SDValue();
14562
14563     SmallVector<SDValue, 8> Chains;
14564     SDValue Ptr = Ld->getBasePtr();
14565     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14566                                         TLI.getPointerTy());
14567     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14568
14569     for (unsigned i = 0; i < NumLoads; ++i) {
14570       // Perform a single load.
14571       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14572                                        Ptr, Ld->getPointerInfo(),
14573                                        Ld->isVolatile(), Ld->isNonTemporal(),
14574                                        Ld->isInvariant(), Ld->getAlignment());
14575       Chains.push_back(ScalarLoad.getValue(1));
14576       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14577       // another round of DAGCombining.
14578       if (i == 0)
14579         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14580       else
14581         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14582                           ScalarLoad, DAG.getIntPtrConstant(i));
14583
14584       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14585     }
14586
14587     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14588                                Chains.size());
14589
14590     // Bitcast the loaded value to a vector of the original element type, in
14591     // the size of the target vector type.
14592     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14593     unsigned SizeRatio = RegSz/MemSz;
14594
14595     // Redistribute the loaded elements into the different locations.
14596     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14597     for (unsigned i = 0; i != NumElems; ++i)
14598       ShuffleVec[i*SizeRatio] = i;
14599
14600     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14601                                          DAG.getUNDEF(WideVecVT),
14602                                          &ShuffleVec[0]);
14603
14604     // Bitcast to the requested type.
14605     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14606     // Replace the original load with the new sequence
14607     // and return the new chain.
14608     return DCI.CombineTo(N, Shuff, TF, true);
14609   }
14610
14611   return SDValue();
14612 }
14613
14614 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14615 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14616                                    const X86Subtarget *Subtarget) {
14617   StoreSDNode *St = cast<StoreSDNode>(N);
14618   EVT VT = St->getValue().getValueType();
14619   EVT StVT = St->getMemoryVT();
14620   DebugLoc dl = St->getDebugLoc();
14621   SDValue StoredVal = St->getOperand(1);
14622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14623
14624   // If we are saving a concatenation of two XMM registers, perform two stores.
14625   // On Sandy Bridge, 256-bit memory operations are executed by two
14626   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14627   // memory  operation.
14628   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14629       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14630       StoredVal.getNumOperands() == 2) {
14631     SDValue Value0 = StoredVal.getOperand(0);
14632     SDValue Value1 = StoredVal.getOperand(1);
14633
14634     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14635     SDValue Ptr0 = St->getBasePtr();
14636     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14637
14638     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14639                                 St->getPointerInfo(), St->isVolatile(),
14640                                 St->isNonTemporal(), St->getAlignment());
14641     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14642                                 St->getPointerInfo(), St->isVolatile(),
14643                                 St->isNonTemporal(), St->getAlignment());
14644     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14645   }
14646
14647   // Optimize trunc store (of multiple scalars) to shuffle and store.
14648   // First, pack all of the elements in one place. Next, store to memory
14649   // in fewer chunks.
14650   if (St->isTruncatingStore() && VT.isVector()) {
14651     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14652     unsigned NumElems = VT.getVectorNumElements();
14653     assert(StVT != VT && "Cannot truncate to the same type");
14654     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14655     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14656
14657     // From, To sizes and ElemCount must be pow of two
14658     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14659     // We are going to use the original vector elt for storing.
14660     // Accumulated smaller vector elements must be a multiple of the store size.
14661     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14662
14663     unsigned SizeRatio  = FromSz / ToSz;
14664
14665     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14666
14667     // Create a type on which we perform the shuffle
14668     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14669             StVT.getScalarType(), NumElems*SizeRatio);
14670
14671     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14672
14673     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14674     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14675     for (unsigned i = 0; i != NumElems; ++i)
14676       ShuffleVec[i] = i * SizeRatio;
14677
14678     // Can't shuffle using an illegal type.
14679     if (!TLI.isTypeLegal(WideVecVT))
14680       return SDValue();
14681
14682     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14683                                          DAG.getUNDEF(WideVecVT),
14684                                          &ShuffleVec[0]);
14685     // At this point all of the data is stored at the bottom of the
14686     // register. We now need to save it to mem.
14687
14688     // Find the largest store unit
14689     MVT StoreType = MVT::i8;
14690     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14691          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14692       MVT Tp = (MVT::SimpleValueType)tp;
14693       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14694         StoreType = Tp;
14695     }
14696
14697     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14698     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14699         (64 <= NumElems * ToSz))
14700       StoreType = MVT::f64;
14701
14702     // Bitcast the original vector into a vector of store-size units
14703     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14704             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14705     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14706     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14707     SmallVector<SDValue, 8> Chains;
14708     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14709                                         TLI.getPointerTy());
14710     SDValue Ptr = St->getBasePtr();
14711
14712     // Perform one or more big stores into memory.
14713     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14714       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14715                                    StoreType, ShuffWide,
14716                                    DAG.getIntPtrConstant(i));
14717       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14718                                 St->getPointerInfo(), St->isVolatile(),
14719                                 St->isNonTemporal(), St->getAlignment());
14720       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14721       Chains.push_back(Ch);
14722     }
14723
14724     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14725                                Chains.size());
14726   }
14727
14728
14729   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14730   // the FP state in cases where an emms may be missing.
14731   // A preferable solution to the general problem is to figure out the right
14732   // places to insert EMMS.  This qualifies as a quick hack.
14733
14734   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14735   if (VT.getSizeInBits() != 64)
14736     return SDValue();
14737
14738   const Function *F = DAG.getMachineFunction().getFunction();
14739   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14740   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14741                      && Subtarget->hasSSE2();
14742   if ((VT.isVector() ||
14743        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14744       isa<LoadSDNode>(St->getValue()) &&
14745       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14746       St->getChain().hasOneUse() && !St->isVolatile()) {
14747     SDNode* LdVal = St->getValue().getNode();
14748     LoadSDNode *Ld = 0;
14749     int TokenFactorIndex = -1;
14750     SmallVector<SDValue, 8> Ops;
14751     SDNode* ChainVal = St->getChain().getNode();
14752     // Must be a store of a load.  We currently handle two cases:  the load
14753     // is a direct child, and it's under an intervening TokenFactor.  It is
14754     // possible to dig deeper under nested TokenFactors.
14755     if (ChainVal == LdVal)
14756       Ld = cast<LoadSDNode>(St->getChain());
14757     else if (St->getValue().hasOneUse() &&
14758              ChainVal->getOpcode() == ISD::TokenFactor) {
14759       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14760         if (ChainVal->getOperand(i).getNode() == LdVal) {
14761           TokenFactorIndex = i;
14762           Ld = cast<LoadSDNode>(St->getValue());
14763         } else
14764           Ops.push_back(ChainVal->getOperand(i));
14765       }
14766     }
14767
14768     if (!Ld || !ISD::isNormalLoad(Ld))
14769       return SDValue();
14770
14771     // If this is not the MMX case, i.e. we are just turning i64 load/store
14772     // into f64 load/store, avoid the transformation if there are multiple
14773     // uses of the loaded value.
14774     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14775       return SDValue();
14776
14777     DebugLoc LdDL = Ld->getDebugLoc();
14778     DebugLoc StDL = N->getDebugLoc();
14779     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14780     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14781     // pair instead.
14782     if (Subtarget->is64Bit() || F64IsLegal) {
14783       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14784       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14785                                   Ld->getPointerInfo(), Ld->isVolatile(),
14786                                   Ld->isNonTemporal(), Ld->isInvariant(),
14787                                   Ld->getAlignment());
14788       SDValue NewChain = NewLd.getValue(1);
14789       if (TokenFactorIndex != -1) {
14790         Ops.push_back(NewChain);
14791         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14792                                Ops.size());
14793       }
14794       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14795                           St->getPointerInfo(),
14796                           St->isVolatile(), St->isNonTemporal(),
14797                           St->getAlignment());
14798     }
14799
14800     // Otherwise, lower to two pairs of 32-bit loads / stores.
14801     SDValue LoAddr = Ld->getBasePtr();
14802     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14803                                  DAG.getConstant(4, MVT::i32));
14804
14805     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14806                                Ld->getPointerInfo(),
14807                                Ld->isVolatile(), Ld->isNonTemporal(),
14808                                Ld->isInvariant(), Ld->getAlignment());
14809     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14810                                Ld->getPointerInfo().getWithOffset(4),
14811                                Ld->isVolatile(), Ld->isNonTemporal(),
14812                                Ld->isInvariant(),
14813                                MinAlign(Ld->getAlignment(), 4));
14814
14815     SDValue NewChain = LoLd.getValue(1);
14816     if (TokenFactorIndex != -1) {
14817       Ops.push_back(LoLd);
14818       Ops.push_back(HiLd);
14819       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14820                              Ops.size());
14821     }
14822
14823     LoAddr = St->getBasePtr();
14824     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14825                          DAG.getConstant(4, MVT::i32));
14826
14827     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14828                                 St->getPointerInfo(),
14829                                 St->isVolatile(), St->isNonTemporal(),
14830                                 St->getAlignment());
14831     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14832                                 St->getPointerInfo().getWithOffset(4),
14833                                 St->isVolatile(),
14834                                 St->isNonTemporal(),
14835                                 MinAlign(St->getAlignment(), 4));
14836     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14837   }
14838   return SDValue();
14839 }
14840
14841 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14842 /// and return the operands for the horizontal operation in LHS and RHS.  A
14843 /// horizontal operation performs the binary operation on successive elements
14844 /// of its first operand, then on successive elements of its second operand,
14845 /// returning the resulting values in a vector.  For example, if
14846 ///   A = < float a0, float a1, float a2, float a3 >
14847 /// and
14848 ///   B = < float b0, float b1, float b2, float b3 >
14849 /// then the result of doing a horizontal operation on A and B is
14850 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14851 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14852 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14853 /// set to A, RHS to B, and the routine returns 'true'.
14854 /// Note that the binary operation should have the property that if one of the
14855 /// operands is UNDEF then the result is UNDEF.
14856 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14857   // Look for the following pattern: if
14858   //   A = < float a0, float a1, float a2, float a3 >
14859   //   B = < float b0, float b1, float b2, float b3 >
14860   // and
14861   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14862   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14863   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14864   // which is A horizontal-op B.
14865
14866   // At least one of the operands should be a vector shuffle.
14867   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14868       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14869     return false;
14870
14871   EVT VT = LHS.getValueType();
14872
14873   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14874          "Unsupported vector type for horizontal add/sub");
14875
14876   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14877   // operate independently on 128-bit lanes.
14878   unsigned NumElts = VT.getVectorNumElements();
14879   unsigned NumLanes = VT.getSizeInBits()/128;
14880   unsigned NumLaneElts = NumElts / NumLanes;
14881   assert((NumLaneElts % 2 == 0) &&
14882          "Vector type should have an even number of elements in each lane");
14883   unsigned HalfLaneElts = NumLaneElts/2;
14884
14885   // View LHS in the form
14886   //   LHS = VECTOR_SHUFFLE A, B, LMask
14887   // If LHS is not a shuffle then pretend it is the shuffle
14888   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14889   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14890   // type VT.
14891   SDValue A, B;
14892   SmallVector<int, 16> LMask(NumElts);
14893   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14894     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14895       A = LHS.getOperand(0);
14896     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14897       B = LHS.getOperand(1);
14898     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14899     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14900   } else {
14901     if (LHS.getOpcode() != ISD::UNDEF)
14902       A = LHS;
14903     for (unsigned i = 0; i != NumElts; ++i)
14904       LMask[i] = i;
14905   }
14906
14907   // Likewise, view RHS in the form
14908   //   RHS = VECTOR_SHUFFLE C, D, RMask
14909   SDValue C, D;
14910   SmallVector<int, 16> RMask(NumElts);
14911   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14912     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14913       C = RHS.getOperand(0);
14914     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14915       D = RHS.getOperand(1);
14916     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14917     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14918   } else {
14919     if (RHS.getOpcode() != ISD::UNDEF)
14920       C = RHS;
14921     for (unsigned i = 0; i != NumElts; ++i)
14922       RMask[i] = i;
14923   }
14924
14925   // Check that the shuffles are both shuffling the same vectors.
14926   if (!(A == C && B == D) && !(A == D && B == C))
14927     return false;
14928
14929   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14930   if (!A.getNode() && !B.getNode())
14931     return false;
14932
14933   // If A and B occur in reverse order in RHS, then "swap" them (which means
14934   // rewriting the mask).
14935   if (A != C)
14936     CommuteVectorShuffleMask(RMask, NumElts);
14937
14938   // At this point LHS and RHS are equivalent to
14939   //   LHS = VECTOR_SHUFFLE A, B, LMask
14940   //   RHS = VECTOR_SHUFFLE A, B, RMask
14941   // Check that the masks correspond to performing a horizontal operation.
14942   for (unsigned i = 0; i != NumElts; ++i) {
14943     int LIdx = LMask[i], RIdx = RMask[i];
14944
14945     // Ignore any UNDEF components.
14946     if (LIdx < 0 || RIdx < 0 ||
14947         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14948         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14949       continue;
14950
14951     // Check that successive elements are being operated on.  If not, this is
14952     // not a horizontal operation.
14953     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14954     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14955     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14956     if (!(LIdx == Index && RIdx == Index + 1) &&
14957         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14958       return false;
14959   }
14960
14961   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14962   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14963   return true;
14964 }
14965
14966 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14967 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14968                                   const X86Subtarget *Subtarget) {
14969   EVT VT = N->getValueType(0);
14970   SDValue LHS = N->getOperand(0);
14971   SDValue RHS = N->getOperand(1);
14972
14973   // Try to synthesize horizontal adds from adds of shuffles.
14974   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14975        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14976       isHorizontalBinOp(LHS, RHS, true))
14977     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14978   return SDValue();
14979 }
14980
14981 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14982 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14983                                   const X86Subtarget *Subtarget) {
14984   EVT VT = N->getValueType(0);
14985   SDValue LHS = N->getOperand(0);
14986   SDValue RHS = N->getOperand(1);
14987
14988   // Try to synthesize horizontal subs from subs of shuffles.
14989   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14990        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14991       isHorizontalBinOp(LHS, RHS, false))
14992     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14993   return SDValue();
14994 }
14995
14996 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14997 /// X86ISD::FXOR nodes.
14998 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14999   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15000   // F[X]OR(0.0, x) -> x
15001   // F[X]OR(x, 0.0) -> x
15002   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15003     if (C->getValueAPF().isPosZero())
15004       return N->getOperand(1);
15005   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15006     if (C->getValueAPF().isPosZero())
15007       return N->getOperand(0);
15008   return SDValue();
15009 }
15010
15011 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15012 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15013   // FAND(0.0, x) -> 0.0
15014   // FAND(x, 0.0) -> 0.0
15015   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15016     if (C->getValueAPF().isPosZero())
15017       return N->getOperand(0);
15018   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15019     if (C->getValueAPF().isPosZero())
15020       return N->getOperand(1);
15021   return SDValue();
15022 }
15023
15024 static SDValue PerformBTCombine(SDNode *N,
15025                                 SelectionDAG &DAG,
15026                                 TargetLowering::DAGCombinerInfo &DCI) {
15027   // BT ignores high bits in the bit index operand.
15028   SDValue Op1 = N->getOperand(1);
15029   if (Op1.hasOneUse()) {
15030     unsigned BitWidth = Op1.getValueSizeInBits();
15031     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15032     APInt KnownZero, KnownOne;
15033     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15034                                           !DCI.isBeforeLegalizeOps());
15035     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15036     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15037         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15038       DCI.CommitTargetLoweringOpt(TLO);
15039   }
15040   return SDValue();
15041 }
15042
15043 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15044   SDValue Op = N->getOperand(0);
15045   if (Op.getOpcode() == ISD::BITCAST)
15046     Op = Op.getOperand(0);
15047   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15048   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15049       VT.getVectorElementType().getSizeInBits() ==
15050       OpVT.getVectorElementType().getSizeInBits()) {
15051     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15052   }
15053   return SDValue();
15054 }
15055
15056 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15057                                   TargetLowering::DAGCombinerInfo &DCI,
15058                                   const X86Subtarget *Subtarget) {
15059   if (!DCI.isBeforeLegalizeOps())
15060     return SDValue();
15061
15062   if (!Subtarget->hasAVX())
15063     return SDValue();
15064
15065   EVT VT = N->getValueType(0);
15066   SDValue Op = N->getOperand(0);
15067   EVT OpVT = Op.getValueType();
15068   DebugLoc dl = N->getDebugLoc();
15069
15070   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15071       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15072
15073     if (Subtarget->hasAVX2())
15074       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15075
15076     // Optimize vectors in AVX mode
15077     // Sign extend  v8i16 to v8i32 and
15078     //              v4i32 to v4i64
15079     //
15080     // Divide input vector into two parts
15081     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15082     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15083     // concat the vectors to original VT
15084
15085     unsigned NumElems = OpVT.getVectorNumElements();
15086     SmallVector<int,8> ShufMask1(NumElems, -1);
15087     for (unsigned i = 0; i != NumElems/2; ++i)
15088       ShufMask1[i] = i;
15089
15090     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15091                                         &ShufMask1[0]);
15092
15093     SmallVector<int,8> ShufMask2(NumElems, -1);
15094     for (unsigned i = 0; i != NumElems/2; ++i)
15095       ShufMask2[i] = i + NumElems/2;
15096
15097     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15098                                         &ShufMask2[0]);
15099
15100     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15101                                   VT.getVectorNumElements()/2);
15102
15103     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15104     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15105
15106     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15107   }
15108   return SDValue();
15109 }
15110
15111 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15112                                   TargetLowering::DAGCombinerInfo &DCI,
15113                                   const X86Subtarget *Subtarget) {
15114   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15115   //           (and (i32 x86isd::setcc_carry), 1)
15116   // This eliminates the zext. This transformation is necessary because
15117   // ISD::SETCC is always legalized to i8.
15118   DebugLoc dl = N->getDebugLoc();
15119   SDValue N0 = N->getOperand(0);
15120   EVT VT = N->getValueType(0);
15121   EVT OpVT = N0.getValueType();
15122
15123   if (N0.getOpcode() == ISD::AND &&
15124       N0.hasOneUse() &&
15125       N0.getOperand(0).hasOneUse()) {
15126     SDValue N00 = N0.getOperand(0);
15127     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15128       return SDValue();
15129     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15130     if (!C || C->getZExtValue() != 1)
15131       return SDValue();
15132     return DAG.getNode(ISD::AND, dl, VT,
15133                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15134                                    N00.getOperand(0), N00.getOperand(1)),
15135                        DAG.getConstant(1, VT));
15136   }
15137
15138   // Optimize vectors in AVX mode:
15139   //
15140   //   v8i16 -> v8i32
15141   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15142   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15143   //   Concat upper and lower parts.
15144   //
15145   //   v4i32 -> v4i64
15146   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15147   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15148   //   Concat upper and lower parts.
15149   //
15150   if (!DCI.isBeforeLegalizeOps())
15151     return SDValue();
15152
15153   if (!Subtarget->hasAVX())
15154     return SDValue();
15155
15156   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15157       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15158
15159     if (Subtarget->hasAVX2())
15160       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15161
15162     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15163     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15164     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15165
15166     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15167                                VT.getVectorNumElements()/2);
15168
15169     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15170     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15171
15172     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15173   }
15174
15175   return SDValue();
15176 }
15177
15178 // Optimize x == -y --> x+y == 0
15179 //          x != -y --> x+y != 0
15180 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15181   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15182   SDValue LHS = N->getOperand(0);
15183   SDValue RHS = N->getOperand(1); 
15184
15185   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15186     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15187       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15188         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15189                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15190         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15191                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15192       }
15193   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15194     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15195       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15196         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15197                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15198         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15199                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15200       }
15201   return SDValue();
15202 }
15203
15204 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15205 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15206   unsigned X86CC = N->getConstantOperandVal(0);
15207   SDValue EFLAG = N->getOperand(1);
15208   DebugLoc DL = N->getDebugLoc();
15209
15210   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15211   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15212   // cases.
15213   if (X86CC == X86::COND_B)
15214     return DAG.getNode(ISD::AND, DL, MVT::i8,
15215                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15216                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
15217                        DAG.getConstant(1, MVT::i8));
15218
15219   return SDValue();
15220 }
15221
15222 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15223   SDValue Op0 = N->getOperand(0);
15224   EVT InVT = Op0->getValueType(0);
15225
15226   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15227   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15228     DebugLoc dl = N->getDebugLoc();
15229     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15230     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15231     // Notice that we use SINT_TO_FP because we know that the high bits
15232     // are zero and SINT_TO_FP is better supported by the hardware.
15233     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15234   }
15235
15236   return SDValue();
15237 }
15238
15239 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15240                                         const X86TargetLowering *XTLI) {
15241   SDValue Op0 = N->getOperand(0);
15242   EVT InVT = Op0->getValueType(0);
15243
15244   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15245   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15246     DebugLoc dl = N->getDebugLoc();
15247     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15248     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15249     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15250   }
15251
15252   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15253   // a 32-bit target where SSE doesn't support i64->FP operations.
15254   if (Op0.getOpcode() == ISD::LOAD) {
15255     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15256     EVT VT = Ld->getValueType(0);
15257     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15258         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15259         !XTLI->getSubtarget()->is64Bit() &&
15260         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15261       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15262                                           Ld->getChain(), Op0, DAG);
15263       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15264       return FILDChain;
15265     }
15266   }
15267   return SDValue();
15268 }
15269
15270 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15271   EVT VT = N->getValueType(0);
15272
15273   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15274   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15275     DebugLoc dl = N->getDebugLoc();
15276     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15277     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15278     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15279   }
15280
15281   return SDValue();
15282 }
15283
15284 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15285 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15286                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15287   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15288   // the result is either zero or one (depending on the input carry bit).
15289   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15290   if (X86::isZeroNode(N->getOperand(0)) &&
15291       X86::isZeroNode(N->getOperand(1)) &&
15292       // We don't have a good way to replace an EFLAGS use, so only do this when
15293       // dead right now.
15294       SDValue(N, 1).use_empty()) {
15295     DebugLoc DL = N->getDebugLoc();
15296     EVT VT = N->getValueType(0);
15297     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15298     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15299                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15300                                            DAG.getConstant(X86::COND_B,MVT::i8),
15301                                            N->getOperand(2)),
15302                                DAG.getConstant(1, VT));
15303     return DCI.CombineTo(N, Res1, CarryOut);
15304   }
15305
15306   return SDValue();
15307 }
15308
15309 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15310 //      (add Y, (setne X, 0)) -> sbb -1, Y
15311 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15312 //      (sub (setne X, 0), Y) -> adc -1, Y
15313 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15314   DebugLoc DL = N->getDebugLoc();
15315
15316   // Look through ZExts.
15317   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15318   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15319     return SDValue();
15320
15321   SDValue SetCC = Ext.getOperand(0);
15322   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15323     return SDValue();
15324
15325   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15326   if (CC != X86::COND_E && CC != X86::COND_NE)
15327     return SDValue();
15328
15329   SDValue Cmp = SetCC.getOperand(1);
15330   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15331       !X86::isZeroNode(Cmp.getOperand(1)) ||
15332       !Cmp.getOperand(0).getValueType().isInteger())
15333     return SDValue();
15334
15335   SDValue CmpOp0 = Cmp.getOperand(0);
15336   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15337                                DAG.getConstant(1, CmpOp0.getValueType()));
15338
15339   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15340   if (CC == X86::COND_NE)
15341     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15342                        DL, OtherVal.getValueType(), OtherVal,
15343                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15344   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15345                      DL, OtherVal.getValueType(), OtherVal,
15346                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15347 }
15348
15349 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15350 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15351                                  const X86Subtarget *Subtarget) {
15352   EVT VT = N->getValueType(0);
15353   SDValue Op0 = N->getOperand(0);
15354   SDValue Op1 = N->getOperand(1);
15355
15356   // Try to synthesize horizontal adds from adds of shuffles.
15357   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15358        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15359       isHorizontalBinOp(Op0, Op1, true))
15360     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15361
15362   return OptimizeConditionalInDecrement(N, DAG);
15363 }
15364
15365 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15366                                  const X86Subtarget *Subtarget) {
15367   SDValue Op0 = N->getOperand(0);
15368   SDValue Op1 = N->getOperand(1);
15369
15370   // X86 can't encode an immediate LHS of a sub. See if we can push the
15371   // negation into a preceding instruction.
15372   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15373     // If the RHS of the sub is a XOR with one use and a constant, invert the
15374     // immediate. Then add one to the LHS of the sub so we can turn
15375     // X-Y -> X+~Y+1, saving one register.
15376     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15377         isa<ConstantSDNode>(Op1.getOperand(1))) {
15378       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15379       EVT VT = Op0.getValueType();
15380       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15381                                    Op1.getOperand(0),
15382                                    DAG.getConstant(~XorC, VT));
15383       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15384                          DAG.getConstant(C->getAPIntValue()+1, VT));
15385     }
15386   }
15387
15388   // Try to synthesize horizontal adds from adds of shuffles.
15389   EVT VT = N->getValueType(0);
15390   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15391        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15392       isHorizontalBinOp(Op0, Op1, true))
15393     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15394
15395   return OptimizeConditionalInDecrement(N, DAG);
15396 }
15397
15398 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15399                                              DAGCombinerInfo &DCI) const {
15400   SelectionDAG &DAG = DCI.DAG;
15401   switch (N->getOpcode()) {
15402   default: break;
15403   case ISD::EXTRACT_VECTOR_ELT:
15404     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15405   case ISD::VSELECT:
15406   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15407   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15408   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15409   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15410   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15411   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15412   case ISD::SHL:
15413   case ISD::SRA:
15414   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15415   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15416   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15417   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15418   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
15419   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15420   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15421   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15422   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15423   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15424   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15425   case X86ISD::FXOR:
15426   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15427   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15428   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15429   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15430   case ISD::ANY_EXTEND:
15431   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15432   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15433   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15434   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15435   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15436   case X86ISD::SHUFP:       // Handle all target specific shuffles
15437   case X86ISD::PALIGN:
15438   case X86ISD::UNPCKH:
15439   case X86ISD::UNPCKL:
15440   case X86ISD::MOVHLPS:
15441   case X86ISD::MOVLHPS:
15442   case X86ISD::PSHUFD:
15443   case X86ISD::PSHUFHW:
15444   case X86ISD::PSHUFLW:
15445   case X86ISD::MOVSS:
15446   case X86ISD::MOVSD:
15447   case X86ISD::VPERMILP:
15448   case X86ISD::VPERM2X128:
15449   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15450   }
15451
15452   return SDValue();
15453 }
15454
15455 /// isTypeDesirableForOp - Return true if the target has native support for
15456 /// the specified value type and it is 'desirable' to use the type for the
15457 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15458 /// instruction encodings are longer and some i16 instructions are slow.
15459 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15460   if (!isTypeLegal(VT))
15461     return false;
15462   if (VT != MVT::i16)
15463     return true;
15464
15465   switch (Opc) {
15466   default:
15467     return true;
15468   case ISD::LOAD:
15469   case ISD::SIGN_EXTEND:
15470   case ISD::ZERO_EXTEND:
15471   case ISD::ANY_EXTEND:
15472   case ISD::SHL:
15473   case ISD::SRL:
15474   case ISD::SUB:
15475   case ISD::ADD:
15476   case ISD::MUL:
15477   case ISD::AND:
15478   case ISD::OR:
15479   case ISD::XOR:
15480     return false;
15481   }
15482 }
15483
15484 /// IsDesirableToPromoteOp - This method query the target whether it is
15485 /// beneficial for dag combiner to promote the specified node. If true, it
15486 /// should return the desired promotion type by reference.
15487 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15488   EVT VT = Op.getValueType();
15489   if (VT != MVT::i16)
15490     return false;
15491
15492   bool Promote = false;
15493   bool Commute = false;
15494   switch (Op.getOpcode()) {
15495   default: break;
15496   case ISD::LOAD: {
15497     LoadSDNode *LD = cast<LoadSDNode>(Op);
15498     // If the non-extending load has a single use and it's not live out, then it
15499     // might be folded.
15500     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15501                                                      Op.hasOneUse()*/) {
15502       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15503              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15504         // The only case where we'd want to promote LOAD (rather then it being
15505         // promoted as an operand is when it's only use is liveout.
15506         if (UI->getOpcode() != ISD::CopyToReg)
15507           return false;
15508       }
15509     }
15510     Promote = true;
15511     break;
15512   }
15513   case ISD::SIGN_EXTEND:
15514   case ISD::ZERO_EXTEND:
15515   case ISD::ANY_EXTEND:
15516     Promote = true;
15517     break;
15518   case ISD::SHL:
15519   case ISD::SRL: {
15520     SDValue N0 = Op.getOperand(0);
15521     // Look out for (store (shl (load), x)).
15522     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15523       return false;
15524     Promote = true;
15525     break;
15526   }
15527   case ISD::ADD:
15528   case ISD::MUL:
15529   case ISD::AND:
15530   case ISD::OR:
15531   case ISD::XOR:
15532     Commute = true;
15533     // fallthrough
15534   case ISD::SUB: {
15535     SDValue N0 = Op.getOperand(0);
15536     SDValue N1 = Op.getOperand(1);
15537     if (!Commute && MayFoldLoad(N1))
15538       return false;
15539     // Avoid disabling potential load folding opportunities.
15540     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15541       return false;
15542     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15543       return false;
15544     Promote = true;
15545   }
15546   }
15547
15548   PVT = MVT::i32;
15549   return Promote;
15550 }
15551
15552 //===----------------------------------------------------------------------===//
15553 //                           X86 Inline Assembly Support
15554 //===----------------------------------------------------------------------===//
15555
15556 namespace {
15557   // Helper to match a string separated by whitespace.
15558   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15559     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15560
15561     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15562       StringRef piece(*args[i]);
15563       if (!s.startswith(piece)) // Check if the piece matches.
15564         return false;
15565
15566       s = s.substr(piece.size());
15567       StringRef::size_type pos = s.find_first_not_of(" \t");
15568       if (pos == 0) // We matched a prefix.
15569         return false;
15570
15571       s = s.substr(pos);
15572     }
15573
15574     return s.empty();
15575   }
15576   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15577 }
15578
15579 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15580   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15581
15582   std::string AsmStr = IA->getAsmString();
15583
15584   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15585   if (!Ty || Ty->getBitWidth() % 16 != 0)
15586     return false;
15587
15588   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15589   SmallVector<StringRef, 4> AsmPieces;
15590   SplitString(AsmStr, AsmPieces, ";\n");
15591
15592   switch (AsmPieces.size()) {
15593   default: return false;
15594   case 1:
15595     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15596     // we will turn this bswap into something that will be lowered to logical
15597     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15598     // lower so don't worry about this.
15599     // bswap $0
15600     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15601         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15602         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15603         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15604         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15605         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15606       // No need to check constraints, nothing other than the equivalent of
15607       // "=r,0" would be valid here.
15608       return IntrinsicLowering::LowerToByteSwap(CI);
15609     }
15610
15611     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15612     if (CI->getType()->isIntegerTy(16) &&
15613         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15614         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15615          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15616       AsmPieces.clear();
15617       const std::string &ConstraintsStr = IA->getConstraintString();
15618       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15619       std::sort(AsmPieces.begin(), AsmPieces.end());
15620       if (AsmPieces.size() == 4 &&
15621           AsmPieces[0] == "~{cc}" &&
15622           AsmPieces[1] == "~{dirflag}" &&
15623           AsmPieces[2] == "~{flags}" &&
15624           AsmPieces[3] == "~{fpsr}")
15625       return IntrinsicLowering::LowerToByteSwap(CI);
15626     }
15627     break;
15628   case 3:
15629     if (CI->getType()->isIntegerTy(32) &&
15630         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15631         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15632         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15633         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15634       AsmPieces.clear();
15635       const std::string &ConstraintsStr = IA->getConstraintString();
15636       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15637       std::sort(AsmPieces.begin(), AsmPieces.end());
15638       if (AsmPieces.size() == 4 &&
15639           AsmPieces[0] == "~{cc}" &&
15640           AsmPieces[1] == "~{dirflag}" &&
15641           AsmPieces[2] == "~{flags}" &&
15642           AsmPieces[3] == "~{fpsr}")
15643         return IntrinsicLowering::LowerToByteSwap(CI);
15644     }
15645
15646     if (CI->getType()->isIntegerTy(64)) {
15647       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15648       if (Constraints.size() >= 2 &&
15649           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15650           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15651         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15652         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15653             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15654             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15655           return IntrinsicLowering::LowerToByteSwap(CI);
15656       }
15657     }
15658     break;
15659   }
15660   return false;
15661 }
15662
15663
15664
15665 /// getConstraintType - Given a constraint letter, return the type of
15666 /// constraint it is for this target.
15667 X86TargetLowering::ConstraintType
15668 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15669   if (Constraint.size() == 1) {
15670     switch (Constraint[0]) {
15671     case 'R':
15672     case 'q':
15673     case 'Q':
15674     case 'f':
15675     case 't':
15676     case 'u':
15677     case 'y':
15678     case 'x':
15679     case 'Y':
15680     case 'l':
15681       return C_RegisterClass;
15682     case 'a':
15683     case 'b':
15684     case 'c':
15685     case 'd':
15686     case 'S':
15687     case 'D':
15688     case 'A':
15689       return C_Register;
15690     case 'I':
15691     case 'J':
15692     case 'K':
15693     case 'L':
15694     case 'M':
15695     case 'N':
15696     case 'G':
15697     case 'C':
15698     case 'e':
15699     case 'Z':
15700       return C_Other;
15701     default:
15702       break;
15703     }
15704   }
15705   return TargetLowering::getConstraintType(Constraint);
15706 }
15707
15708 /// Examine constraint type and operand type and determine a weight value.
15709 /// This object must already have been set up with the operand type
15710 /// and the current alternative constraint selected.
15711 TargetLowering::ConstraintWeight
15712   X86TargetLowering::getSingleConstraintMatchWeight(
15713     AsmOperandInfo &info, const char *constraint) const {
15714   ConstraintWeight weight = CW_Invalid;
15715   Value *CallOperandVal = info.CallOperandVal;
15716     // If we don't have a value, we can't do a match,
15717     // but allow it at the lowest weight.
15718   if (CallOperandVal == NULL)
15719     return CW_Default;
15720   Type *type = CallOperandVal->getType();
15721   // Look at the constraint type.
15722   switch (*constraint) {
15723   default:
15724     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15725   case 'R':
15726   case 'q':
15727   case 'Q':
15728   case 'a':
15729   case 'b':
15730   case 'c':
15731   case 'd':
15732   case 'S':
15733   case 'D':
15734   case 'A':
15735     if (CallOperandVal->getType()->isIntegerTy())
15736       weight = CW_SpecificReg;
15737     break;
15738   case 'f':
15739   case 't':
15740   case 'u':
15741       if (type->isFloatingPointTy())
15742         weight = CW_SpecificReg;
15743       break;
15744   case 'y':
15745       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15746         weight = CW_SpecificReg;
15747       break;
15748   case 'x':
15749   case 'Y':
15750     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15751         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15752       weight = CW_Register;
15753     break;
15754   case 'I':
15755     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15756       if (C->getZExtValue() <= 31)
15757         weight = CW_Constant;
15758     }
15759     break;
15760   case 'J':
15761     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15762       if (C->getZExtValue() <= 63)
15763         weight = CW_Constant;
15764     }
15765     break;
15766   case 'K':
15767     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15768       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15769         weight = CW_Constant;
15770     }
15771     break;
15772   case 'L':
15773     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15774       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15775         weight = CW_Constant;
15776     }
15777     break;
15778   case 'M':
15779     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15780       if (C->getZExtValue() <= 3)
15781         weight = CW_Constant;
15782     }
15783     break;
15784   case 'N':
15785     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15786       if (C->getZExtValue() <= 0xff)
15787         weight = CW_Constant;
15788     }
15789     break;
15790   case 'G':
15791   case 'C':
15792     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15793       weight = CW_Constant;
15794     }
15795     break;
15796   case 'e':
15797     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15798       if ((C->getSExtValue() >= -0x80000000LL) &&
15799           (C->getSExtValue() <= 0x7fffffffLL))
15800         weight = CW_Constant;
15801     }
15802     break;
15803   case 'Z':
15804     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15805       if (C->getZExtValue() <= 0xffffffff)
15806         weight = CW_Constant;
15807     }
15808     break;
15809   }
15810   return weight;
15811 }
15812
15813 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15814 /// with another that has more specific requirements based on the type of the
15815 /// corresponding operand.
15816 const char *X86TargetLowering::
15817 LowerXConstraint(EVT ConstraintVT) const {
15818   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15819   // 'f' like normal targets.
15820   if (ConstraintVT.isFloatingPoint()) {
15821     if (Subtarget->hasSSE2())
15822       return "Y";
15823     if (Subtarget->hasSSE1())
15824       return "x";
15825   }
15826
15827   return TargetLowering::LowerXConstraint(ConstraintVT);
15828 }
15829
15830 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15831 /// vector.  If it is invalid, don't add anything to Ops.
15832 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15833                                                      std::string &Constraint,
15834                                                      std::vector<SDValue>&Ops,
15835                                                      SelectionDAG &DAG) const {
15836   SDValue Result(0, 0);
15837
15838   // Only support length 1 constraints for now.
15839   if (Constraint.length() > 1) return;
15840
15841   char ConstraintLetter = Constraint[0];
15842   switch (ConstraintLetter) {
15843   default: break;
15844   case 'I':
15845     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15846       if (C->getZExtValue() <= 31) {
15847         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15848         break;
15849       }
15850     }
15851     return;
15852   case 'J':
15853     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15854       if (C->getZExtValue() <= 63) {
15855         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15856         break;
15857       }
15858     }
15859     return;
15860   case 'K':
15861     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15862       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15863         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15864         break;
15865       }
15866     }
15867     return;
15868   case 'N':
15869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15870       if (C->getZExtValue() <= 255) {
15871         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15872         break;
15873       }
15874     }
15875     return;
15876   case 'e': {
15877     // 32-bit signed value
15878     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15879       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15880                                            C->getSExtValue())) {
15881         // Widen to 64 bits here to get it sign extended.
15882         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15883         break;
15884       }
15885     // FIXME gcc accepts some relocatable values here too, but only in certain
15886     // memory models; it's complicated.
15887     }
15888     return;
15889   }
15890   case 'Z': {
15891     // 32-bit unsigned value
15892     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15893       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15894                                            C->getZExtValue())) {
15895         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15896         break;
15897       }
15898     }
15899     // FIXME gcc accepts some relocatable values here too, but only in certain
15900     // memory models; it's complicated.
15901     return;
15902   }
15903   case 'i': {
15904     // Literal immediates are always ok.
15905     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15906       // Widen to 64 bits here to get it sign extended.
15907       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15908       break;
15909     }
15910
15911     // In any sort of PIC mode addresses need to be computed at runtime by
15912     // adding in a register or some sort of table lookup.  These can't
15913     // be used as immediates.
15914     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15915       return;
15916
15917     // If we are in non-pic codegen mode, we allow the address of a global (with
15918     // an optional displacement) to be used with 'i'.
15919     GlobalAddressSDNode *GA = 0;
15920     int64_t Offset = 0;
15921
15922     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15923     while (1) {
15924       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15925         Offset += GA->getOffset();
15926         break;
15927       } else if (Op.getOpcode() == ISD::ADD) {
15928         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15929           Offset += C->getZExtValue();
15930           Op = Op.getOperand(0);
15931           continue;
15932         }
15933       } else if (Op.getOpcode() == ISD::SUB) {
15934         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15935           Offset += -C->getZExtValue();
15936           Op = Op.getOperand(0);
15937           continue;
15938         }
15939       }
15940
15941       // Otherwise, this isn't something we can handle, reject it.
15942       return;
15943     }
15944
15945     const GlobalValue *GV = GA->getGlobal();
15946     // If we require an extra load to get this address, as in PIC mode, we
15947     // can't accept it.
15948     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15949                                                         getTargetMachine())))
15950       return;
15951
15952     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15953                                         GA->getValueType(0), Offset);
15954     break;
15955   }
15956   }
15957
15958   if (Result.getNode()) {
15959     Ops.push_back(Result);
15960     return;
15961   }
15962   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15963 }
15964
15965 std::pair<unsigned, const TargetRegisterClass*>
15966 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15967                                                 EVT VT) const {
15968   // First, see if this is a constraint that directly corresponds to an LLVM
15969   // register class.
15970   if (Constraint.size() == 1) {
15971     // GCC Constraint Letters
15972     switch (Constraint[0]) {
15973     default: break;
15974       // TODO: Slight differences here in allocation order and leaving
15975       // RIP in the class. Do they matter any more here than they do
15976       // in the normal allocation?
15977     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15978       if (Subtarget->is64Bit()) {
15979         if (VT == MVT::i32 || VT == MVT::f32)
15980           return std::make_pair(0U, &X86::GR32RegClass);
15981         if (VT == MVT::i16)
15982           return std::make_pair(0U, &X86::GR16RegClass);
15983         if (VT == MVT::i8 || VT == MVT::i1)
15984           return std::make_pair(0U, &X86::GR8RegClass);
15985         if (VT == MVT::i64 || VT == MVT::f64)
15986           return std::make_pair(0U, &X86::GR64RegClass);
15987         break;
15988       }
15989       // 32-bit fallthrough
15990     case 'Q':   // Q_REGS
15991       if (VT == MVT::i32 || VT == MVT::f32)
15992         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15993       if (VT == MVT::i16)
15994         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15995       if (VT == MVT::i8 || VT == MVT::i1)
15996         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15997       if (VT == MVT::i64)
15998         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15999       break;
16000     case 'r':   // GENERAL_REGS
16001     case 'l':   // INDEX_REGS
16002       if (VT == MVT::i8 || VT == MVT::i1)
16003         return std::make_pair(0U, &X86::GR8RegClass);
16004       if (VT == MVT::i16)
16005         return std::make_pair(0U, &X86::GR16RegClass);
16006       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16007         return std::make_pair(0U, &X86::GR32RegClass);
16008       return std::make_pair(0U, &X86::GR64RegClass);
16009     case 'R':   // LEGACY_REGS
16010       if (VT == MVT::i8 || VT == MVT::i1)
16011         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16012       if (VT == MVT::i16)
16013         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16014       if (VT == MVT::i32 || !Subtarget->is64Bit())
16015         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16016       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16017     case 'f':  // FP Stack registers.
16018       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16019       // value to the correct fpstack register class.
16020       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16021         return std::make_pair(0U, &X86::RFP32RegClass);
16022       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16023         return std::make_pair(0U, &X86::RFP64RegClass);
16024       return std::make_pair(0U, &X86::RFP80RegClass);
16025     case 'y':   // MMX_REGS if MMX allowed.
16026       if (!Subtarget->hasMMX()) break;
16027       return std::make_pair(0U, &X86::VR64RegClass);
16028     case 'Y':   // SSE_REGS if SSE2 allowed
16029       if (!Subtarget->hasSSE2()) break;
16030       // FALL THROUGH.
16031     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16032       if (!Subtarget->hasSSE1()) break;
16033
16034       switch (VT.getSimpleVT().SimpleTy) {
16035       default: break;
16036       // Scalar SSE types.
16037       case MVT::f32:
16038       case MVT::i32:
16039         return std::make_pair(0U, &X86::FR32RegClass);
16040       case MVT::f64:
16041       case MVT::i64:
16042         return std::make_pair(0U, &X86::FR64RegClass);
16043       // Vector types.
16044       case MVT::v16i8:
16045       case MVT::v8i16:
16046       case MVT::v4i32:
16047       case MVT::v2i64:
16048       case MVT::v4f32:
16049       case MVT::v2f64:
16050         return std::make_pair(0U, &X86::VR128RegClass);
16051       // AVX types.
16052       case MVT::v32i8:
16053       case MVT::v16i16:
16054       case MVT::v8i32:
16055       case MVT::v4i64:
16056       case MVT::v8f32:
16057       case MVT::v4f64:
16058         return std::make_pair(0U, &X86::VR256RegClass);
16059       }
16060       break;
16061     }
16062   }
16063
16064   // Use the default implementation in TargetLowering to convert the register
16065   // constraint into a member of a register class.
16066   std::pair<unsigned, const TargetRegisterClass*> Res;
16067   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16068
16069   // Not found as a standard register?
16070   if (Res.second == 0) {
16071     // Map st(0) -> st(7) -> ST0
16072     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16073         tolower(Constraint[1]) == 's' &&
16074         tolower(Constraint[2]) == 't' &&
16075         Constraint[3] == '(' &&
16076         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16077         Constraint[5] == ')' &&
16078         Constraint[6] == '}') {
16079
16080       Res.first = X86::ST0+Constraint[4]-'0';
16081       Res.second = &X86::RFP80RegClass;
16082       return Res;
16083     }
16084
16085     // GCC allows "st(0)" to be called just plain "st".
16086     if (StringRef("{st}").equals_lower(Constraint)) {
16087       Res.first = X86::ST0;
16088       Res.second = &X86::RFP80RegClass;
16089       return Res;
16090     }
16091
16092     // flags -> EFLAGS
16093     if (StringRef("{flags}").equals_lower(Constraint)) {
16094       Res.first = X86::EFLAGS;
16095       Res.second = &X86::CCRRegClass;
16096       return Res;
16097     }
16098
16099     // 'A' means EAX + EDX.
16100     if (Constraint == "A") {
16101       Res.first = X86::EAX;
16102       Res.second = &X86::GR32_ADRegClass;
16103       return Res;
16104     }
16105     return Res;
16106   }
16107
16108   // Otherwise, check to see if this is a register class of the wrong value
16109   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16110   // turn into {ax},{dx}.
16111   if (Res.second->hasType(VT))
16112     return Res;   // Correct type already, nothing to do.
16113
16114   // All of the single-register GCC register classes map their values onto
16115   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16116   // really want an 8-bit or 32-bit register, map to the appropriate register
16117   // class and return the appropriate register.
16118   if (Res.second == &X86::GR16RegClass) {
16119     if (VT == MVT::i8) {
16120       unsigned DestReg = 0;
16121       switch (Res.first) {
16122       default: break;
16123       case X86::AX: DestReg = X86::AL; break;
16124       case X86::DX: DestReg = X86::DL; break;
16125       case X86::CX: DestReg = X86::CL; break;
16126       case X86::BX: DestReg = X86::BL; break;
16127       }
16128       if (DestReg) {
16129         Res.first = DestReg;
16130         Res.second = &X86::GR8RegClass;
16131       }
16132     } else if (VT == MVT::i32) {
16133       unsigned DestReg = 0;
16134       switch (Res.first) {
16135       default: break;
16136       case X86::AX: DestReg = X86::EAX; break;
16137       case X86::DX: DestReg = X86::EDX; break;
16138       case X86::CX: DestReg = X86::ECX; break;
16139       case X86::BX: DestReg = X86::EBX; break;
16140       case X86::SI: DestReg = X86::ESI; break;
16141       case X86::DI: DestReg = X86::EDI; break;
16142       case X86::BP: DestReg = X86::EBP; break;
16143       case X86::SP: DestReg = X86::ESP; break;
16144       }
16145       if (DestReg) {
16146         Res.first = DestReg;
16147         Res.second = &X86::GR32RegClass;
16148       }
16149     } else if (VT == MVT::i64) {
16150       unsigned DestReg = 0;
16151       switch (Res.first) {
16152       default: break;
16153       case X86::AX: DestReg = X86::RAX; break;
16154       case X86::DX: DestReg = X86::RDX; break;
16155       case X86::CX: DestReg = X86::RCX; break;
16156       case X86::BX: DestReg = X86::RBX; break;
16157       case X86::SI: DestReg = X86::RSI; break;
16158       case X86::DI: DestReg = X86::RDI; break;
16159       case X86::BP: DestReg = X86::RBP; break;
16160       case X86::SP: DestReg = X86::RSP; break;
16161       }
16162       if (DestReg) {
16163         Res.first = DestReg;
16164         Res.second = &X86::GR64RegClass;
16165       }
16166     }
16167   } else if (Res.second == &X86::FR32RegClass ||
16168              Res.second == &X86::FR64RegClass ||
16169              Res.second == &X86::VR128RegClass) {
16170     // Handle references to XMM physical registers that got mapped into the
16171     // wrong class.  This can happen with constraints like {xmm0} where the
16172     // target independent register mapper will just pick the first match it can
16173     // find, ignoring the required type.
16174
16175     if (VT == MVT::f32 || VT == MVT::i32)
16176       Res.second = &X86::FR32RegClass;
16177     else if (VT == MVT::f64 || VT == MVT::i64)
16178       Res.second = &X86::FR64RegClass;
16179     else if (X86::VR128RegClass.hasType(VT))
16180       Res.second = &X86::VR128RegClass;
16181     else if (X86::VR256RegClass.hasType(VT))
16182       Res.second = &X86::VR256RegClass;
16183   }
16184
16185   return Res;
16186 }